diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 048fad85c5..9a2c75ff28 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -24,4 +24,8 @@ grep -q '/common/docker/' "$SHARD_FILE" && pull public.ecr.aws/docker/library/py # The Cedar sidecar pin lives in application.yml; read it rather than duplicate it. CEDAR_IMAGE="$(grep -oE 'cedar-image: *"[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')" grep -q '/verifiedpermissions/' "$SHARD_FILE" && [ -n "$CEDAR_IMAGE" ] && pull "$CEDAR_IMAGE" +# Same for the GraphQL sidecar. AppSyncCfnIntegrationTest also starts it but lives under +# services/cloudformation/, so it needs its own token alongside the /appsync/ path match. +GRAPHQL_IMAGE="$(grep -oE 'graphql-image: *"[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')" +grep -qE '/appsync/|AppSyncCfnIntegrationTest' "$SHARD_FILE" && [ -n "$GRAPHQL_IMAGE" ] && pull "$GRAPHQL_IMAGE" exit 0 diff --git a/README.md b/README.md index dcfe332484..cdf9766bf9 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,7 @@ Floci uses real Docker containers when in-process emulation would reduce fidelit | OpenSearch | `opensearchproject/opensearch:2` | Full OpenSearch engine with REST API | | ECR | `registry:2` | OCI-compatible registry for docker push and docker pull | | Verified Permissions | `floci/floci-sidecar-cedar:1.1.0` | Cedar 4 policy parsing, schema validation and authorization decisions, via a [Floci sidecar](https://github.com/floci-io/floci-sidecars) | +| AppSync | `floci/floci-sidecar-graphql:0.2.0` | graphql-java schema validation, query planning and execution, via a [Floci sidecar](https://github.com/floci-io/floci-sidecars) | Docker-backed services require the Docker socket: diff --git a/docs/services/appsync.md b/docs/services/appsync.md index 8b00389df0..8c38c1fc7d 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -29,7 +29,7 @@ targets and HTTP URLs that use a literal private or loopback address. | Operation | Description | |---|---| -| `StartSchemaCreation` | Start schema creation — validates and parses SDL using graphql-java (invalid SDL returns 400) | +| `StartSchemaCreation` | Start schema creation: validates and parses SDL via the GraphQL sidecar (invalid SDL returns 400) | | `GetSchemaCreationStatus` | Get schema creation status | | `GetIntrospectionSchema` | Get the introspection schema | @@ -143,9 +143,41 @@ As on AWS, `ApiKey.id` is the key value itself (`da2-` followed by 26 lowercase ## Schema Registry -`StartSchemaCreation` validates the provided GraphQL SDL using [graphql-java](https://github.com/graphql-java/graphql-java). Invalid schemas are rejected asynchronously (status `FAILED` with details after `PROCESSING`). Valid schemas are registered in an in-memory `SchemaRegistry` and persisted to the schema store. +Schema parsing and query execution run in the **GraphQL sidecar** (issue #2917), not in Floci's +own process: [graphql-java](https://github.com/graphql-java/graphql-java) is a ~3.8MB dependency +used only by AppSync, so keeping it out of Floci's JVM/native image altogether, mirroring the +Cedar sidecar pattern already used for Verified Permissions, avoids paying that cost in every +build regardless of whether AppSync is ever used. The sidecar is `floci/floci-sidecar-graphql`, +published from [floci-io/floci-sidecars](https://github.com/floci-io/floci-sidecars) and pinned to +an exact version (a cached `latest` is never re-pulled): pull it ahead of time on an air-gapped +host with `docker pull floci/floci-sidecar-graphql:0.2.0`. `GraphqlSidecarManager` lazily starts +the sidecar container on first use and checks the contract version it reports on `/health`; a +sidecar speaking another contract major is refused immediately with an `InternalServerException` +naming the image and the variable to change. `floci.services.appsync.graphql-url` points at an +already-running instance instead (Docker Compose setups) and is checked the same way. -On emulator startup, after storage load and orphan recovery, Floci **rehydrates** SUCCESS SDLs from the schema store into `SchemaRegistry` so `POST /v1/apis/{apiId}/graphql` works across restarts (memory/persistent/hybrid/wal). +The sidecar itself carries no AppSync-specific knowledge: no `@aws_auth`, no IAM, no directive +semantics, and no AWS scalar vocabulary either. `StartSchemaCreation` sends the SDL (with +AppSync's directive declarations and the 17 custom scalar types injected, customers never declare +those themselves) plus a `scalars` mapping (each AppSync scalar name onto one of the sidecar's +generic coercion kinds, e.g. `AWSDateTime` onto `date-time`) to the sidecar's +`/v1/schema/validate`, which parses and compiles it generically. Invalid schemas are rejected +asynchronously (status `FAILED` with details after `PROCESSING`), using the sidecar's structured, +per-problem errors to build the same `codeErrors` shape this API always returned. Valid schemas +are registered in Floci's own `SchemaRegistry` (now just a raw-SDL cache; nothing is compiled +in-process) and persisted to the schema store. + +At execution time, Floci calls the sidecar's `/v1/plan` to learn which `(type, field)` coordinates +a query will visit and what directives are on each, computes `@aws_auth`/IAM/Cognito/Lambda +authorization decisions itself (this AWS-specific logic never runs in the sidecar), and passes any +denied coordinates to `/v1/execute` as an opaque list; the sidecar nulls those fields out with the +given error, without ever knowing why. + +On emulator startup, after storage load and orphan recovery, Floci **rehydrates** SUCCESS SDLs +from the schema store into `SchemaRegistry` so `POST /v1/apis/{apiId}/graphql` works across +restarts (memory/persistent/hybrid/wal), without re-validating against the sidecar, since a +persisted SDL already passed validation once and restarts shouldn't eagerly start a container that +might otherwise never be needed. The following **AWS scalar types** are pre-registered and available in any schema without requiring explicit `scalar` declarations: @@ -184,7 +216,7 @@ The following **AppSync directives** are pre-defined and recognized in schemas: Unknown directives are rejected during schema registration. -Schema extensions (`extend type Query { ... }`) are supported natively through graphql-java. +Schema extensions (`extend type Query { ... }`) are supported natively through graphql-java, running in the sidecar. ## GraphQL execute (data-plane) diff --git a/pom.xml b/pom.xml index 106d98b78c..1f675aa706 100644 --- a/pom.xml +++ b/pom.xml @@ -253,13 +253,6 @@ 2.4.1 - - - com.graphql-java - graphql-java - 26.1 - - com.networknt diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 0bb1233d12..c2477f6c07 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -2057,6 +2057,12 @@ public interface EmulatorConfig { * Env: FLOCI_SERVICES_APPSYNC_VTL_TIMEOUT_MILLIS */ @WithDefault("5000") long vtlTimeoutMillis(); + + /** When set, Floci uses this URL and skips GraphQL sidecar container management. */ + Optional graphqlUrl(); + + @WithDefault("floci/floci-sidecar-graphql:0.2.0") + String graphqlImage(); } interface OamServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java new file mode 100644 index 0000000000..a51333c8a1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java @@ -0,0 +1,223 @@ +package io.github.hectorvent.floci.services.appsync; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * HTTP client for the stateless GraphQL sidecar (issue #2917). Every call sends the full SDL + * plus the request; the sidecar caches and registers nothing across calls. + * + *

This client carries no AppSync-specific behavior of its own. {@link #plan} and the + * {@code denyFields} parameter of {@link #execute} are how {@code @aws_auth}/IAM field + * authorization gets applied without the sidecar knowing what those directives mean: + * {@link io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuthorizationPlanner} + * is where that AWS-specific interpretation actually lives. AWS custom-scalar semantics + * (AWSDateTime, AWSJSON, etc.) run inside the sidecar itself, since scalar coercion happens + * inline during graphql-java's own execution with no clean seam to apply it out here. + */ +@ApplicationScoped +public class GraphqlSidecarClient { + private final GraphqlSidecarManager manager; + private final ObjectMapper mapper; + private final HttpClient httpClient; + + @Inject + public GraphqlSidecarClient(GraphqlSidecarManager manager, ObjectMapper mapper) { + this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); + } + + GraphqlSidecarClient(GraphqlSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) { + this.manager = manager; + this.mapper = mapper; + this.httpClient = httpClient; + } + + /** One structured problem in an SDL: mirrors what {@code StartSchemaCreation}'s codeErrors need. */ + public record SchemaIssue(String category, String message, int line, int column) { + } + + /** Thrown by {@link #validateSchema} with the sidecar's structured per-problem detail, not just a flat message. */ + public static final class SchemaValidationException extends AppSyncTransportException { + private final List issues; + + public SchemaValidationException(String message, List issues) { + super(400, "BadRequestException", message); + this.issues = issues; + } + + public List issues() { + return issues; + } + } + + /** Validates/compiles an SDL document. Throws {@link SchemaValidationException} if the schema is invalid. */ + public void validateSchema(String sdl, Map scalars) { + ObjectNode body = mapper.createObjectNode(); + body.put("sdl", sdl); + body.set("scalars", mapper.valueToTree(scalars)); + SidecarResponse response = call("/v1/schema/validate", body, "schema validation"); + if (response.status() == 400) { + throw new SchemaValidationException( + response.body().path("error").asText("Schema validation failed."), + issuesFrom(response.body().path("issues"))); + } + requireSuccess(response, "schema validation"); + } + + private List issuesFrom(JsonNode array) { + List issues = new ArrayList<>(); + if (array.isArray()) { + for (JsonNode node : array) { + issues.add(new SchemaIssue(node.path("category").asText("VALIDATION_ERROR"), node.path("message").asText(), + node.path("line").asInt(0), node.path("column").asInt(0))); + } + } + return issues; + } + + /** One directive application: {@code args} is whatever the directive's arguments deserialize to (usually a Map). */ + public record PlannedDirective(String name, Object args) { + } + + /** {@code typeDirectives} is the containing object type's own applied directives, from the sidecar's query planner. */ + public record PlannedField(String typeName, String fieldName, List directives, + List typeDirectives) { + } + + /** {@code errorType}/{@code message} are supplied by the caller; this sidecar has no opinion on them. */ + public record DenyField(String typeName, String fieldName, String errorType, String message) { + } + + /** + * {@code operationType} is {@code QUERY}/{@code MUTATION}/{@code SUBSCRIPTION}, or {@code + * null} when the query didn't parse or named an operation that doesn't exist, in which case + * {@code fields} is empty too. That's deliberate (see {@link #plan}): a bad query is {@code + * /v1/execute}'s problem to report correctly, not planning's to reject early. + */ + public record PlanResult(String operationType, List fields) { + } + + /** + * Learns the query's operation type and every {@code (typeName, fieldName)} coordinate it + * would visit, with directives on each, in one call, since both come from parsing the same + * query once. Never throws for a malformed query (see {@link PlanResult}). + */ + public PlanResult plan(String sdl, Map scalars, String query, String operationName) { + ObjectNode body = mapper.createObjectNode(); + body.put("sdl", sdl); + body.set("scalars", mapper.valueToTree(scalars)); + body.put("query", query); + if (operationName != null && !operationName.isBlank()) { + body.put("operationName", operationName); + } + JsonNode response = requireSuccess(call("/v1/plan", body, "query planning"), "query planning"); + String operationType = response.path("operationType").isTextual() + ? response.path("operationType").asText() : null; + List fields = new ArrayList<>(); + for (JsonNode node : response.path("fields")) { + fields.add(new PlannedField( + node.path("typeName").asText(), + node.path("fieldName").asText(), + directivesFrom(node.path("directives")), + directivesFrom(node.path("typeDirectives")))); + } + return new PlanResult(operationType, fields); + } + + @SuppressWarnings("unchecked") + private List directivesFrom(JsonNode array) { + List directives = new ArrayList<>(); + if (array.isArray()) { + for (JsonNode node : array) { + directives.add(new PlannedDirective(node.path("name").asText(), + mapper.convertValue(node.path("args"), Map.class))); + } + } + return directives; + } + + /** Executes a query against the given SDL. {@code denyFields} coordinates come back null with the given error. */ + public Map execute(String sdl, Map scalars, String query, + Map variables, String operationName, + List denyFields) { + ObjectNode body = mapper.createObjectNode(); + body.put("sdl", sdl); + body.set("scalars", mapper.valueToTree(scalars)); + body.put("query", query); + body.set("variables", mapper.valueToTree(variables == null ? Map.of() : variables)); + if (operationName != null && !operationName.isBlank()) { + body.put("operationName", operationName); + } + if (denyFields != null && !denyFields.isEmpty()) { + ArrayNode array = body.putArray("denyFields"); + for (DenyField deny : denyFields) { + ObjectNode node = array.addObject(); + node.put("typeName", deny.typeName()); + node.put("fieldName", deny.fieldName()); + node.put("errorType", deny.errorType()); + node.put("message", deny.message()); + } + } + JsonNode response = requireSuccess(call("/v1/execute", body, "query execution"), "query execution"); + return mapper.convertValue(response, Map.class); + } + + private record SidecarResponse(int status, JsonNode body) { + } + + /** Raw call: returns whatever status/body the sidecar sent, without deciding what's an error. */ + private SidecarResponse call(String path, JsonNode body, String operation) { + try { + String baseUrl = manager.ensureReady(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(baseUrl + path)) + .timeout(Duration.ofSeconds(30)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body))) + .build(); + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + JsonNode responseBody = response.body() == null || response.body().isBlank() + ? mapper.createObjectNode() : mapper.readTree(response.body()); + return new SidecarResponse(response.statusCode(), responseBody); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AppSyncTransportException(500, "InternalFailureException", + "GraphQL sidecar " + operation + " was interrupted."); + } catch (Exception e) { + throw new AppSyncTransportException(500, "InternalFailureException", + "Failed to call GraphQL sidecar for " + operation + ": " + safeMessage(e)); + } + } + + /** For callers that don't need to special-case a 400 body shape: any non-200 becomes a transport exception. */ + private JsonNode requireSuccess(SidecarResponse response, String operation) { + if (response.status() == 400) { + throw new AppSyncTransportException(400, "BadRequestException", + response.body().path("error").asText("GraphQL " + operation + " failed.")); + } + if (response.status() != 200) { + throw new AppSyncTransportException(500, "InternalFailureException", + "GraphQL sidecar " + operation + " failed with HTTP " + response.status() + "."); + } + return response.body(); + } + + private static String safeMessage(Exception e) { + String message = e.getMessage(); + return message == null || message.isBlank() ? e.getClass().getSimpleName() : message; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java new file mode 100644 index 0000000000..07445c863d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java @@ -0,0 +1,231 @@ +package io.github.hectorvent.floci.services.appsync; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; +import io.quarkus.runtime.ShutdownEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Lazily starts and manages the GraphQL sidecar used by AppSync (issue #2917). + * + *

The sidecar is the {@code floci/floci-sidecar-graphql} image from floci-io/floci-sidecars. + * Its {@code GET /health} answers the sidecar contract: {@code {"status","name","version","contract"}}. + * A sidecar speaking a different contract major fails fast with a message naming the fix, rather + * than surfacing later as an unexplained request error. A sidecar whose health body is not JSON + * predates the contract and is accepted with a warning. + */ +@ApplicationScoped +public class GraphqlSidecarManager { + /** The sidecar contract major this manager speaks; see docs/contract.md in floci-io/floci-sidecars. */ + static final String REQUIRED_CONTRACT = "1"; + static final String IMAGE_ENV = "FLOCI_SERVICES_APPSYNC_GRAPHQL_IMAGE"; + static final String URL_ENV = "FLOCI_SERVICES_APPSYNC_GRAPHQL_URL"; + + private static final Logger LOG = Logger.getLogger(GraphqlSidecarManager.class); + private static final String CONTAINER_NAME = "floci-graphql"; + private static final int GRAPHQL_PORT = 8181; + private static final int HEALTH_POLL_MAX_MS = 30_000; + private static final int HEALTH_POLL_INTERVAL_MS = 500; + + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final EmulatorConfig config; + private final ObjectMapper objectMapper; + private final AtomicBoolean contractReported = new AtomicBoolean(); + + private volatile String resolvedUrl; + private volatile String containerId; + + @Inject + public GraphqlSidecarManager(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + EmulatorConfig config, + ObjectMapper objectMapper) { + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.config = config; + this.objectMapper = objectMapper; + } + + public synchronized boolean isAvailable() { + if (resolvedUrl != null) { + if (containerId == null || probeHealth(resolvedUrl)) { + return true; + } + discardStaleManagedEndpoint(); + return false; + } + Optional configured = config.services().appsync().graphqlUrl(); + if (configured.isPresent() && !configured.get().isBlank()) { + String url = trimTrailingSlash(configured.get()); + if (probeHealth(url)) { + resolvedUrl = url; + LOG.infov("GraphQL sidecar is available at pre-configured URL: {0}", url); + return true; + } + } + return false; + } + + public synchronized String ensureReady() { + if (resolvedUrl != null) { + if (containerId == null || probeHealth(resolvedUrl)) { + return resolvedUrl; + } + discardStaleManagedEndpoint(); + } + Optional configured = config.services().appsync().graphqlUrl(); + if (configured.isPresent() && !configured.get().isBlank()) { + String url = trimTrailingSlash(configured.get()); + // Best effort: a sidecar that is not up yet is reported by the first real call, + // but a sidecar speaking the wrong contract is refused here, once, with the fix. + probeHealth(url); + resolvedUrl = url; + LOG.infov("Using pre-configured GraphQL sidecar URL: {0}", resolvedUrl); + return resolvedUrl; + } + startContainer(); + return resolvedUrl; + } + + private void discardStaleManagedEndpoint() { + String staleUrl = resolvedUrl; + String staleContainerId = containerId; + resolvedUrl = null; + containerId = null; + LOG.warnv("GraphQL sidecar at {0} is no longer healthy; restarting the managed container", staleUrl); + if (staleContainerId != null) { + try { + lifecycleManager.stopAndRemove(staleContainerId, null); + } catch (Exception e) { + LOG.debugv(e, "Failed to remove stale GraphQL sidecar container {0}", staleContainerId); + } + } + } + + private void startContainer() { + String image = config.services().appsync().graphqlImage(); + LOG.infov("Starting GraphQL sidecar container using image {0}", image); + String containerName = ContainerStorageHelper.dockerName(config, CONTAINER_NAME); + lifecycleManager.removeIfExists(containerName); + + ContainerSpec spec = containerBuilder.newContainer(image) + .withName(containerName) + .withDynamicPort(GRAPHQL_PORT) + .withDockerNetwork(config.services().dockerNetwork()) + .withEmbeddedDns() + .withLogRotation() + .build(); + ContainerInfo info = lifecycleManager.createAndStart(spec); + EndpointInfo endpoint = info.getEndpoint(GRAPHQL_PORT); + containerId = info.containerId(); + String url = "http://" + endpoint; + waitForHealth(url); + resolvedUrl = url; + LOG.infov("GraphQL sidecar is ready at {0}", resolvedUrl); + } + + /** + * {@code false} means not ready yet (connection refused, non-200, timeout). A sidecar that + * answers but speaks another contract major throws instead, so callers never retry it. + */ + private boolean probeHealth(String baseUrl) { + try { + HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + "/health").toURL().openConnection(); + connection.setConnectTimeout(500); + connection.setReadTimeout(500); + if (connection.getResponseCode() != 200) { + return false; + } + String body; + try (InputStream in = connection.getInputStream()) { + body = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + checkContract(baseUrl, body); + return true; + } catch (IOException e) { + LOG.debugv(e, "GraphQL sidecar health probe failed for {0}", baseUrl); + return false; + } + } + + private void checkContract(String baseUrl, String body) { + JsonNode health = parseHealth(body); + if (health == null || !health.hasNonNull("contract")) { + if (contractReported.compareAndSet(false, true)) { + LOG.warnv("GraphQL sidecar at {0} predates the sidecar contract (health body is not contract JSON); " + + "it still works, but move to floci/floci-sidecar-graphql to get version checks", baseUrl); + } + return; + } + String contract = health.path("contract").asText(); + String name = health.path("name").asText("unknown"); + String version = health.path("version").asText("unknown"); + if (!REQUIRED_CONTRACT.equals(contract)) { + throw new IllegalStateException("GraphQL sidecar at " + baseUrl + " (" + name + " " + version + + ") speaks sidecar contract " + contract + " but this Floci requires contract " + + REQUIRED_CONTRACT + ". Set " + IMAGE_ENV + " (currently " + + config.services().appsync().graphqlImage() + ") or " + URL_ENV + + " to a compatible sidecar."); + } + if (contractReported.compareAndSet(false, true)) { + LOG.infov("GraphQL sidecar {0} {1} (contract {2}) at {3}", name, version, contract, baseUrl); + } + } + + private JsonNode parseHealth(String body) { + try { + return objectMapper.readTree(body); + } catch (JsonProcessingException e) { + LOG.debugv(e, "GraphQL sidecar health body is not JSON: {0}", body); + return null; + } + } + + private void waitForHealth(String baseUrl) { + long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS; + while (System.currentTimeMillis() < deadline) { + if (probeHealth(baseUrl)) { + return; + } + try { + Thread.sleep(HEALTH_POLL_INTERVAL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for GraphQL sidecar", e); + } + } + throw new IllegalStateException("GraphQL sidecar did not become healthy within " + HEALTH_POLL_MAX_MS + " ms"); + } + + void onStop(@Observes ShutdownEvent event) { + if (containerId == null) { + return; + } + LOG.info("Stopping GraphQL sidecar container"); + lifecycleManager.stopAndRemove(containerId, null); + } + + private static String trimTrailingSlash(String url) { + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java index 790a024a78..9bd59fda96 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java @@ -1,10 +1,5 @@ package io.github.hectorvent.floci.services.appsync.graphql; -import graphql.ErrorType; -import graphql.ExecutionResult; -import graphql.GraphQLError; -import graphql.ErrorClassification; -import graphql.language.SourceLocation; import jakarta.enterprise.context.ApplicationScoped; import java.util.ArrayList; @@ -13,8 +8,11 @@ import java.util.List; import java.util.Map; /** - * Maps graphql-java {@link ExecutionResult} errors to AWS AppSync wire shapes - * with top-level {@code errorType}/{@code errorInfo} (not extensions-only). + * Maps the GraphQL sidecar's {@code /v1/execute} result (graphql-java's own {@code + * ExecutionResult.toSpecification()} shape, already spec-compliant JSON by the time it crosses + * the wire) to AWS AppSync's wire shape, with top-level {@code errorType}/{@code errorInfo} + * (not extensions-only). No graphql-java types here: this only ever sees plain {@code + * Map}/{@code List} JSON, since that's all the sidecar can hand back over HTTP (issue #2917). * * @see AppSync DG {@code $util.error} ({@code errorType}/{@code errorInfo}) * @see AppSync HTTP behavior (AppSync team / @robzhu) @@ -28,19 +26,22 @@ public class AppSyncErrorFormatter { */ public static final String MSG_EMPTY_BODY = "Request body is empty."; public static final String MSG_UNABLE_TO_PARSE = "Unable to parse GraphQL query."; - public static final String MSG_MISSING_OPERATION_NAME = "Missing operation name."; public static final String MSG_NO_SCHEMA = "No schema definition exists."; - public Map format(ExecutionResult result) { + /** {@code sidecarResult} is exactly what {@link io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient#execute} returned. */ + @SuppressWarnings("unchecked") + public Map format(Map sidecarResult) { Map response = new LinkedHashMap<>(); - if (result.isDataPresent()) { - response.put("data", result.getData()); + if (sidecarResult.containsKey("data")) { + response.put("data", sidecarResult.get("data")); } - List errors = result.getErrors(); - if (errors != null && !errors.isEmpty()) { - List> formatted = new ArrayList<>(errors.size()); - for (GraphQLError error : errors) { - formatted.add(formatError(error)); + Object errors = sidecarResult.get("errors"); + if (errors instanceof List list && !list.isEmpty()) { + List> formatted = new ArrayList<>(list.size()); + for (Object error : list) { + if (error instanceof Map map) { + formatted.add(formatError((Map) map)); + } } response.put("errors", formatted); } @@ -56,48 +57,36 @@ public class AppSyncErrorFormatter { return response; } - private Map formatError(GraphQLError error) { + @SuppressWarnings("unchecked") + private Map formatError(Map error) { Map map = new LinkedHashMap<>(); - map.put("message", error.getMessage()); - List locations = error.getLocations(); - if (locations != null && !locations.isEmpty()) { - List> locationMaps = new ArrayList<>(locations.size()); - for (SourceLocation location : locations) { - Map loc = new LinkedHashMap<>(); - loc.put("line", location.getLine()); - loc.put("column", location.getColumn()); - locationMaps.add(loc); - } - map.put("locations", locationMaps); + map.put("message", error.get("message")); + Object locations = error.get("locations"); + if (locations != null) { + map.put("locations", locations); } - List path = error.getPath(); - if (path != null && !path.isEmpty()) { + Object path = error.get("path"); + if (path != null) { map.put("path", path); } - map.put("errorType", toAppSyncErrorType(error.getErrorType())); + String classification = null; + Object extensions = error.get("extensions"); + if (extensions instanceof Map extensionsMap) { + Object raw = extensionsMap.get("classification"); + classification = raw == null ? null : String.valueOf(raw); + } + map.put("errorType", toAppSyncErrorType(classification)); map.put("errorInfo", null); return map; } - static String toAppSyncErrorType(ErrorClassification classification) { - if (classification == ErrorType.InvalidSyntax) { - return "SyntaxError"; - } - if (classification == ErrorType.ValidationError) { - return "ValidationError"; - } - if (classification == ErrorType.OperationNotSupported) { - return "OperationNotSupported"; - } - if (classification == ErrorType.DataFetchingException) { - return "DataFetchingException"; - } + static String toAppSyncErrorType(String classification) { if (classification == null) { return "Unknown"; } - if (classification instanceof ErrorType errorType) { - return errorType.name(); - } - return classification.toString(); + // graphql-java's own ErrorType enum names almost all match AppSync's wire names already; + // InvalidSyntax is the one AppSync spells differently. Anything else (including a custom + // classification like the sidecar's denyFields "Unauthorized") passes through unchanged. + return "InvalidSyntax".equals(classification) ? "SyntaxError" : classification; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java index 86548c571f..27832c2266 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java @@ -6,9 +6,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.services.appsync.AppSyncService; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.DenyField; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult; import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuthContext; import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthMiddleware; import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthRequestInfo; +import io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuthorizationPlanner; import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; import jakarta.inject.Inject; import jakarta.ws.rs.POST; @@ -26,6 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.UUID; /** @@ -41,7 +46,9 @@ public class AppSyncExecutionController { private final AppSyncService appSyncService; private final SchemaRegistry schemaRegistry; - private final QueryExecutor queryExecutor; + private final SidecarSchemaCompiler schemaCompiler; + private final SidecarFieldAuthorizationPlanner fieldAuthorizationPlanner; + private final GraphqlSidecarClient sidecarClient; private final AppSyncErrorFormatter errorFormatter; private final ObjectMapper objectMapper; private final AuthMiddleware authMiddleware; @@ -50,14 +57,18 @@ public class AppSyncExecutionController { @Inject public AppSyncExecutionController(AppSyncService appSyncService, SchemaRegistry schemaRegistry, - QueryExecutor queryExecutor, + SidecarSchemaCompiler schemaCompiler, + SidecarFieldAuthorizationPlanner fieldAuthorizationPlanner, + GraphqlSidecarClient sidecarClient, AppSyncErrorFormatter errorFormatter, ObjectMapper objectMapper, AuthMiddleware authMiddleware, RequestContext requestContext) { this.appSyncService = appSyncService; this.schemaRegistry = schemaRegistry; - this.queryExecutor = queryExecutor; + this.schemaCompiler = schemaCompiler; + this.fieldAuthorizationPlanner = fieldAuthorizationPlanner; + this.sidecarClient = sidecarClient; this.errorFormatter = errorFormatter; this.objectMapper = objectMapper; this.authMiddleware = authMiddleware; @@ -102,17 +113,26 @@ public class AppSyncExecutionController { return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage()); } - var graphQLOpt = schemaRegistry.getGraphQL(apiId); - if (graphQLOpt.isEmpty()) { + Optional sdlOpt = schemaRegistry.getSdl(apiId); + if (sdlOpt.isEmpty()) { return graphqlError(502, "GraphQLSchemaException", AppSyncErrorFormatter.MSG_NO_SCHEMA); } try { - Map result = queryExecutor.execute( - graphQLOpt.get(), parsed.query(), parsed.variables(), parsed.operationName(), - graphQlContext(authContext)); - return Response.ok(result).type(MediaType.APPLICATION_JSON).build(); + String preparedSdl = schemaCompiler.withDirectivesAndScalars(sdlOpt.get()); + Map scalars = schemaCompiler.scalarKindMapping(); + PlanResult plan = sidecarClient.plan(preparedSdl, scalars, parsed.query(), parsed.operationName()); + if ("SUBSCRIPTION".equals(plan.operationType())) { + // Real AppSync serves subscriptions over its separate realtime endpoint, not + // this plain-HTTP one; graphql-java itself has no opinion on that, so Floci + // rejects it before ever calling /v1/execute. + return Response.ok(errorFormatter.format(operationNotSupported())).type(MediaType.APPLICATION_JSON).build(); + } + List denyFields = fieldAuthorizationPlanner.planDenyFields(plan, authContext); + Map rawResult = sidecarClient.execute( + preparedSdl, scalars, parsed.query(), parsed.variables(), parsed.operationName(), denyFields); + return Response.ok(errorFormatter.format(rawResult)).type(MediaType.APPLICATION_JSON).build(); } catch (AppSyncTransportException e) { return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage()); } @@ -238,15 +258,11 @@ public class AppSyncExecutionController { return ips; } - private static Map graphQlContext(AppSyncAuthContext authContext) { - Map context = new HashMap<>(); - context.put(AppSyncAuthContext.KEY, authContext); - if (authContext.identity() != null) { - context.put("identity", authContext.identity()); - } - context.put("authType", authContext.authType()); - context.put("deniedFields", authContext.deniedFieldsList()); - return context; + private static Map operationNotSupported() { + Map error = new HashMap<>(); + error.put("message", "Subscriptions are not supported over HTTP"); + error.put("extensions", Map.of("classification", "OperationNotSupported")); + return Map.of("errors", List.of(error)); } private Response graphqlError(int status, String errorType, String message) { 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 deleted file mode 100644 index 189155775a..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java +++ /dev/null @@ -1,139 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql; - -import graphql.GraphQLError; -import graphql.language.SourceLocation; -import graphql.parser.InvalidSyntaxException; -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 graphql.schema.idl.errors.SchemaProblem; -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.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -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 (SchemaProblem e) { - List> codeErrors = new ArrayList<>(); - for (GraphQLError ge : e.getErrors()) { - codeErrors.add(toCodeErrorFromGraphQL("PARSER_ERROR", ge)); - } - throw new AwsException("BadRequestException", - "Invalid schema: " + e.getMessage(), 400, - buildExtendedData(codeErrors)); - } catch (InvalidSyntaxException e) { - throw new AwsException("BadRequestException", - "Invalid schema: " + e.getMessage(), 400, - buildExtendedData(List.of(toCodeError("PARSER_ERROR", e.getMessage(), 0, 0)))); - } - - 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 (SchemaProblem e) { - List> codeErrors = new ArrayList<>(); - for (GraphQLError ge : e.getErrors()) { - codeErrors.add(toCodeErrorFromGraphQL("VALIDATION_ERROR", ge)); - } - throw new AwsException("BadRequestException", - "Invalid schema: " + e.getMessage(), 400, - buildExtendedData(codeErrors)); - } 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, - buildExtendedData(List.of( - toCodeError("VALIDATION_ERROR", "Unknown directive: @" + name, 0, 0)))); - } - } - } - - private Map toCodeErrorFromGraphQL(String errorType, GraphQLError ge) { - List locs = ge.getLocations(); - if (locs != null && !locs.isEmpty()) { - SourceLocation first = locs.get(0); - return toCodeError(errorType, ge.getMessage(), first.getLine(), first.getColumn()); - } - return toCodeError(errorType, ge.getMessage(), 0, 0); - } - - private Map toCodeError(String errorType, String value, int line, int column) { - Map codeError = new LinkedHashMap<>(); - codeError.put("errorType", errorType); - codeError.put("value", value); - Map location = new LinkedHashMap<>(); - location.put("line", line); - location.put("column", column); - location.put("span", -1); - codeError.put("location", location); - return codeError; - } - - private Map buildExtendedData(List> codeErrors) { - Map detail = new LinkedHashMap<>(); - detail.put("codeErrors", codeErrors); - Map extendedData = new LinkedHashMap<>(); - extendedData.put("reason", "CODE_ERROR"); - extendedData.put("detail", detail); - return extendedData; - } - - 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/QueryExecutor.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutor.java deleted file mode 100644 index 09a7dbb454..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutor.java +++ /dev/null @@ -1,105 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql; - -import graphql.ErrorType; -import graphql.ExecutionInput; -import graphql.ExecutionResult; -import graphql.ExecutionResultImpl; -import graphql.GraphQL; -import graphql.GraphqlErrorBuilder; -import graphql.language.Document; -import graphql.language.OperationDefinition; -import graphql.parser.InvalidSyntaxException; -import graphql.parser.Parser; -import graphql.schema.GraphQLSchema; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -@ApplicationScoped -public class QueryExecutor { - - private final AppSyncErrorFormatter formatter; - - @Inject - public QueryExecutor(AppSyncErrorFormatter formatter) { - this.formatter = formatter; - } - - public Map execute(GraphQLSchema schema, String query, - Map variables, String operationName) { - return execute(SchemaRegistry.buildGraphQL(schema), query, variables, operationName, Map.of()); - } - - public Map execute(GraphQL graphQL, String query, - Map variables, String operationName) { - return execute(graphQL, query, variables, operationName, Map.of()); - } - - public Map execute(GraphQL graphQL, String query, - Map variables, String operationName, - Map graphQLContext) { - List operations = parseOperations(query); - if (operations.size() > 1 && (operationName == null || operationName.isBlank())) { - throw new AppSyncTransportException(400, "BadRequestException", - AppSyncErrorFormatter.MSG_MISSING_OPERATION_NAME); - } - - OperationDefinition selected = selectOperation(operations, operationName); - if (selected != null && selected.getOperation() == OperationDefinition.Operation.SUBSCRIPTION) { - ExecutionResult rejected = ExecutionResultImpl.newExecutionResult() - .addError(GraphqlErrorBuilder.newError() - .message("Subscriptions are not supported over HTTP") - .errorType(ErrorType.OperationNotSupported) - .build()) - .build(); - return formatter.format(rejected); - } - - ExecutionInput.Builder inputBuilder = ExecutionInput.newExecutionInput().query(query); - if (variables != null) { - inputBuilder.variables(variables); - } - if (operationName != null && !operationName.isBlank()) { - inputBuilder.operationName(operationName); - } - if (graphQLContext != null && !graphQLContext.isEmpty()) { - inputBuilder.graphQLContext(graphQLContext); - } - - ExecutionResult result = graphQL.execute(inputBuilder.build()); - return formatter.format(result); - } - - private List parseOperations(String query) { - try { - Document document = Parser.parse(query); - List ops = new ArrayList<>(); - for (var definition : document.getDefinitions()) { - if (definition instanceof OperationDefinition operationDefinition) { - ops.add(operationDefinition); - } - } - return ops; - } catch (InvalidSyntaxException e) { - return List.of(); - } - } - - private OperationDefinition selectOperation(List operations, String operationName) { - if (operations.isEmpty()) { - return null; - } - if (operationName == null || operationName.isBlank()) { - return operations.get(0); - } - for (OperationDefinition op : operations) { - if (operationName.equals(op.getName())) { - return op; - } - } - return null; - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java index 34c480a833..24898bf527 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java @@ -30,6 +30,7 @@ public class SchemaCreationWorker { private static final Logger LOG = Logger.getLogger(SchemaCreationWorker.class); private final SchemaRegistry schemaRegistry; + private final SidecarSchemaCompiler schemaCompiler; private final AccountAwareStorageBackend schemaStatusStore; private final AccountAwareStorageBackend schemaStore; private final EmulatorConfig config; @@ -39,11 +40,13 @@ public class SchemaCreationWorker { @Inject public SchemaCreationWorker(SchemaRegistry schemaRegistry, + SidecarSchemaCompiler schemaCompiler, AccountAwareStorageBackend schemaStatusStore, AccountAwareStorageBackend schemaStore, EmulatorConfig config, ObjectMapper objectMapper) { this.schemaRegistry = schemaRegistry; + this.schemaCompiler = schemaCompiler; this.schemaStatusStore = schemaStatusStore; this.schemaStore = schemaStore; this.config = config; @@ -85,6 +88,7 @@ public class SchemaCreationWorker { private void process(String apiId, String sdl, String accountId) { try { + schemaCompiler.validate(sdl); schemaRegistry.register(apiId, sdl); // Worker thread has no request context; write under the submitting account. schemaStore.putForAccount(accountId, apiId, sdl); @@ -150,30 +154,30 @@ public class SchemaCreationWorker { } /** - * Rehydrates executable schemas from persisted SDL into {@link SchemaRegistry} - * after storage load / orphan recovery so GraphQL execute works across restarts. - * Scans every account (startup has no request context); apiIds are globally unique. - * Parse failures are logged and skipped. + * Rehydrates persisted SDL into {@link SchemaRegistry} after storage load / orphan recovery + * so {@code POST /v1/apis/{apiId}/graphql} works across restarts. Scans every account + * (startup has no request context); apiIds are globally unique. + * + *

Doesn't re-validate against the sidecar: a persisted SDL already passed + * {@code StartSchemaCreation}'s validation once, and re-checking it here would mean every + * restart eagerly starts the GraphQL sidecar container even when nothing ever queries + * AppSync, the same "it was already good, no need to prove it again" call the old + * in-process registry made too (compiling that SDL again is what it *was* doing, this just + * no longer needs a network round trip to a sidecar to do it). */ public void rehydrateSchemas() { int loaded = 0; - int skipped = 0; for (Map.Entry entry : schemaStore.scanAllAccountsAsMap().entrySet()) { String apiId = entry.getKey(); String sdl = entry.getValue(); if (sdl == null || sdl.isBlank()) { continue; } - try { - schemaRegistry.register(apiId, sdl); - loaded++; - } catch (RuntimeException e) { - skipped++; - LOG.warnv(e, "Skipping rehydrate of schema for API {0}: {1}", apiId, e.getMessage()); - } + schemaRegistry.register(apiId, sdl); + loaded++; } - if (loaded > 0 || skipped > 0) { - LOG.infov("Rehydrated {0} schema(s) into registry ({1} skipped)", loaded, skipped); + if (loaded > 0) { + LOG.infov("Rehydrated {0} schema(s) into registry", loaded); } } } 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 index 7bb8c08511..7835e48394 100644 --- 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 @@ -1,62 +1,34 @@ package io.github.hectorvent.floci.services.appsync.graphql; -import graphql.GraphQL; -import graphql.execution.AsyncExecutionStrategy; -import graphql.execution.AsyncSerialExecutionStrategy; -import graphql.execution.SubscriptionExecutionStrategy; -import graphql.schema.GraphQLSchema; -import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthFieldWrapper; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +/** + * In-memory {@code apiId -> raw SDL} cache for the AppSync data-plane path (issue #2917). + * + *

Used to exist to hold a compiled {@code GraphQLSchema}/{@code GraphQL} engine per API: + * that compilation now happens inside the (stateless) GraphQL sidecar on every call, so there's + * nothing to compile or cache here beyond the raw SDL text itself. This still exists, rather + * than reading {@code schemaStore} directly, so the data-plane execute path has a simple + * non-account-scoped lookup by {@code apiId}, the same shape the durable store doesn't + * naturally give a single request. + */ @ApplicationScoped public class SchemaRegistry { - private final Map schemas = new ConcurrentHashMap<>(); - private final Map engines = new ConcurrentHashMap<>(); - private final AppSyncSchemaParser appSyncSchemaParser; - private final AuthFieldWrapper authFieldWrapper; - - public SchemaRegistry(AppSyncSchemaParser appSyncSchemaParser) { - this(appSyncSchemaParser, null); - } - - @Inject - public SchemaRegistry(AppSyncSchemaParser appSyncSchemaParser, AuthFieldWrapper authFieldWrapper) { - this.appSyncSchemaParser = appSyncSchemaParser; - this.authFieldWrapper = authFieldWrapper; - } + private final Map sdls = new ConcurrentHashMap<>(); public void register(String apiId, String sdl) { - GraphQLSchema schema = appSyncSchemaParser.parse(sdl); - if (authFieldWrapper != null) { - schema = authFieldWrapper.wrap(schema); - } - schemas.put(apiId, schema); - engines.put(apiId, buildGraphQL(schema)); + sdls.put(apiId, sdl); } - public Optional getSchema(String apiId) { - return Optional.ofNullable(schemas.get(apiId)); - } - - public Optional getGraphQL(String apiId) { - return Optional.ofNullable(engines.get(apiId)); + public Optional getSdl(String apiId) { + return Optional.ofNullable(sdls.get(apiId)); } public void remove(String apiId) { - schemas.remove(apiId); - engines.remove(apiId); - } - - public static GraphQL buildGraphQL(GraphQLSchema schema) { - return GraphQL.newGraphQL(schema) - .queryExecutionStrategy(new AsyncExecutionStrategy()) - .mutationExecutionStrategy(new AsyncSerialExecutionStrategy()) - .subscriptionExecutionStrategy(new SubscriptionExecutionStrategy()) - .build(); + sdls.remove(apiId); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SidecarSchemaCompiler.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SidecarSchemaCompiler.java new file mode 100644 index 0000000000..e500e3c24f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SidecarSchemaCompiler.java @@ -0,0 +1,146 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.SchemaIssue; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.SchemaValidationException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Prepares a customer's SDL for the (AWS-agnostic) GraphQL sidecar and validates it against it + * (issue #2917): what {@code AppSyncSchemaParser} used to do in-process. AppSync provides its + * directive declarations ({@code @aws_auth} etc.) and the 17 custom scalar type declarations + * implicitly: customers never write {@code scalar AWSDateTime} themselves. That injection is + * pure AWS-specific knowledge (which directives exist, their exact argument shapes) with no + * business living in the sidecar, so it happens here, before the SDL is ever sent anywhere. + */ +@ApplicationScoped +public class SidecarSchemaCompiler { + + /** Must match the scalar names {@code SCALAR_KIND_MAPPING} maps onto a sidecar coercion kind. */ + private static final List SCALAR_NAMES = List.of( + "AWSJSON", "AWSDateTime", "AWSDate", "AWSTime", "AWSTimestamp", "AWSEmail", "AWSURL", + "AWSPhone", "AWSIPAddress", "AWSBoolean", "AWSLong", "AWSInteger", "AWSShort", "AWSFloat", + "AWSBigDecimal", "AWSBigInt", "AWSByte"); + + /** + * The sidecar carries no AWS vocabulary: its scalars are generic named coercion kinds (see + * {@code floci-io/floci-sidecars/graphql/API.md}), and a caller maps its own scalar names onto + * them. This is that mapping for AppSync's 17 scalars, sent as the {@code scalars} field on + * every {@code /v1/schema/validate}, {@code /v1/plan} and {@code /v1/execute} call. Without it + * every AWS scalar would silently fall back to identity pass-through coercion in the sidecar. + */ + private static final Map SCALAR_KIND_MAPPING = Map.ofEntries( + Map.entry("AWSJSON", "json-string"), + Map.entry("AWSDateTime", "date-time"), + Map.entry("AWSDate", "date"), + Map.entry("AWSTime", "time"), + Map.entry("AWSTimestamp", "epoch-seconds"), + Map.entry("AWSEmail", "email"), + Map.entry("AWSURL", "url"), + Map.entry("AWSPhone", "phone"), + Map.entry("AWSIPAddress", "ip-address"), + Map.entry("AWSBoolean", "boolean"), + Map.entry("AWSLong", "long"), + Map.entry("AWSInteger", "integer"), + Map.entry("AWSShort", "short"), + Map.entry("AWSFloat", "float"), + Map.entry("AWSBigDecimal", "big-decimal"), + Map.entry("AWSBigInt", "big-integer"), + Map.entry("AWSByte", "base64")); + + private static final Pattern DIRECTIVE_USE = Pattern.compile("@(\\w+)"); + + private final GraphqlSidecarClient sidecarClient; + + @Inject + public SidecarSchemaCompiler(GraphqlSidecarClient sidecarClient) { + this.sidecarClient = sidecarClient; + } + + /** Validates the customer's raw {@code sdl} against the sidecar. Throws {@link AwsException} (400) if invalid. */ + public void validate(String sdl) { + validateNoUnknownDirectives(sdl); + try { + sidecarClient.validateSchema(withDirectivesAndScalars(sdl), SCALAR_KIND_MAPPING); + } catch (SchemaValidationException e) { + throw toAwsException(e); + } + } + + /** The scalar-name-to-kind mapping every sidecar call must send alongside the prepared SDL. */ + public Map scalarKindMapping() { + return SCALAR_KIND_MAPPING; + } + + /** The SDL to actually send the sidecar for plan/execute: same injection as at validation time. */ + public String withDirectivesAndScalars(String sdl) { + StringBuilder sb = new StringBuilder(); + for (AppSyncDirective directive : AppSyncDirective.values()) { + sb.append(directive.sdl()).append('\n'); + } + sb.append('\n'); + for (String scalarName : SCALAR_NAMES) { + sb.append("scalar ").append(scalarName).append('\n'); + } + sb.append('\n').append(sdl); + return sb.toString(); + } + + private void validateNoUnknownDirectives(String sdl) { + String clean = sdl + .replaceAll("\"\"\"[\\s\\S]*?\"\"\"", "") + .replaceAll("\"(?:[^\"\\\\]|\\\\.)*\"", "") + .replaceAll("#[^\n]*", ""); + Matcher matcher = DIRECTIVE_USE.matcher(clean); + while (matcher.find()) { + String name = matcher.group(1); + if (!AppSyncDirective.isKnown(name)) { + throw new AwsException("BadRequestException", "Unknown directive: @" + name, 400, + buildExtendedData(List.of( + toCodeError("VALIDATION_ERROR", "Unknown directive: @" + name, 0, 0)))); + } + } + } + + private AwsException toAwsException(SchemaValidationException e) { + List> codeErrors = new ArrayList<>(); + for (SchemaIssue issue : e.issues()) { + codeErrors.add(toCodeError(issue.category(), issue.message(), issue.line(), issue.column())); + } + if (codeErrors.isEmpty()) { + codeErrors.add(toCodeError("VALIDATION_ERROR", e.getMessage(), 0, 0)); + } + return new AwsException("BadRequestException", "Invalid schema: " + e.getMessage(), 400, + buildExtendedData(codeErrors)); + } + + private Map toCodeError(String errorType, String value, int line, int column) { + Map codeError = new LinkedHashMap<>(); + codeError.put("errorType", errorType); + codeError.put("value", value); + Map location = new LinkedHashMap<>(); + location.put("line", line); + location.put("column", column); + location.put("span", -1); + codeError.put("location", location); + return codeError; + } + + private Map buildExtendedData(List> codeErrors) { + Map detail = new LinkedHashMap<>(); + detail.put("codeErrors", codeErrors); + Map extendedData = new LinkedHashMap<>(); + extendedData.put("reason", "CODE_ERROR"); + extendedData.put("detail", detail); + return extendedData; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuthRequirements.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuthRequirements.java new file mode 100644 index 0000000000..78f428ee5f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuthRequirements.java @@ -0,0 +1,73 @@ +package io.github.hectorvent.floci.services.appsync.graphql.auth; + +import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; +import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; + +import java.util.ArrayList; +import java.util.List; + +/** + * What {@code @aws_auth}/{@code @aws_iam}/{@code @aws_cognito_user_pools}/etc. mean for a field, + * the actual AWS-specific interpretation, shared by {@link SidecarFieldAuthorizationPlanner} + * (issue #2917). Used to live as part of the live in-process {@code DataFetcher} wrapper this + * class was originally named for; that wrapper is gone now that execution happens in the + * (AWS-agnostic) GraphQL sidecar, but the directive-name-to-{@link AuthenticationType} mapping + * itself didn't change, so it's kept here rather than duplicated. + */ +final class AppSyncAuthRequirements { + + private AppSyncAuthRequirements() { + } + + record AuthRequirement(AuthenticationType mode, List groups) { + } + + /** A directive application reduced to just what {@link #requirementsFrom} needs. */ + record DirectiveUse(String name, List cognitoGroups) { + } + + static List requirementsFrom(List directives, GraphqlApi api) { + List requirements = new ArrayList<>(); + boolean ignoreAwsAuth = AuthMiddleware.hasAdditionalModes(api); + for (DirectiveUse directive : directives) { + switch (directive.name()) { + case "aws_api_key" -> requirements.add(new AuthRequirement(AuthenticationType.API_KEY, null)); + case "aws_iam" -> requirements.add(new AuthRequirement(AuthenticationType.AWS_IAM, null)); + case "aws_oidc" -> requirements.add(new AuthRequirement(AuthenticationType.OPENID_CONNECT, null)); + case "aws_lambda" -> requirements.add(new AuthRequirement(AuthenticationType.AWS_LAMBDA, null)); + case "aws_cognito_user_pools" -> requirements.add( + new AuthRequirement(AuthenticationType.AMAZON_COGNITO_USER_POOLS, directive.cognitoGroups())); + case "aws_auth" -> { + if (!ignoreAwsAuth && api.getAuthenticationType() == AuthenticationType.AMAZON_COGNITO_USER_POOLS) { + requirements.add(new AuthRequirement( + AuthenticationType.AMAZON_COGNITO_USER_POOLS, directive.cognitoGroups())); + } + } + default -> { + } + } + } + return requirements; + } + + static boolean groupsAllowed(AuthRequirement requirement, AppSyncAuthContext auth) { + if (requirement.groups() == null || requirement.groups().isEmpty()) { + return true; + } + if (auth.authenticationType() != AuthenticationType.AMAZON_COGNITO_USER_POOLS) { + return true; + } + Object groups = auth.identity() == null ? null : auth.identity().get("groups"); + if (!(groups instanceof List callerGroups)) { + return false; + } + for (String required : requirement.groups()) { + for (Object caller : callerGroups) { + if (required.equals(String.valueOf(caller))) { + return true; + } + } + } + return false; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncFieldUnauthorizedException.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncFieldUnauthorizedException.java deleted file mode 100644 index 06475b95bb..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncFieldUnauthorizedException.java +++ /dev/null @@ -1,57 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql.auth; - -import graphql.ErrorClassification; -import graphql.GraphQLError; -import graphql.language.SourceLocation; -import graphql.schema.DataFetchingEnvironment; - -import java.util.List; -import java.util.Map; - -public class AppSyncFieldUnauthorizedException extends RuntimeException implements GraphQLError { - - private final List path; - - public AppSyncFieldUnauthorizedException(List path, String fieldName, String typeName) { - super(AppSyncAuth.fieldUnauthorizedMessage( - fieldName == null || fieldName.isBlank() ? "unknown" : fieldName, - typeName == null || typeName.isBlank() ? "Unknown" : typeName)); - this.path = path == null ? List.of() : List.copyOf(path); - } - - @Override - public List getPath() { - return path; - } - - @Override - public List getLocations() { - return null; - } - - @Override - public ErrorClassification getErrorType() { - return new ErrorClassification() { - @Override - public String toString() { - return AppSyncAuth.FIELD_UNAUTHORIZED_TYPE; - } - }; - } - - @Override - public Map getExtensions() { - return null; - } - - public static AppSyncFieldUnauthorizedException from( - DataFetchingEnvironment environment, String fieldName, String typeName) { - if (environment == null - || environment.getExecutionStepInfo() == null - || environment.getExecutionStepInfo().getPath() == null) { - return new AppSyncFieldUnauthorizedException(List.of(), fieldName, typeName); - } - return new AppSyncFieldUnauthorizedException( - environment.getExecutionStepInfo().getPath().toList(), fieldName, typeName); - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthFieldWrapper.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthFieldWrapper.java deleted file mode 100644 index 2fe3b30576..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthFieldWrapper.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql.auth; - -import graphql.schema.DataFetcher; -import graphql.schema.FieldCoordinates; -import graphql.schema.GraphQLCodeRegistry; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLNamedType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; - -@ApplicationScoped -public class AuthFieldWrapper { - - private final IamAuthValidator iamAuthValidator; - - @Inject - public AuthFieldWrapper(IamAuthValidator iamAuthValidator) { - this.iamAuthValidator = iamAuthValidator; - } - - public GraphQLSchema wrap(GraphQLSchema schema) { - GraphQLCodeRegistry.Builder code = GraphQLCodeRegistry.newCodeRegistry(schema.getCodeRegistry()); - for (GraphQLNamedType type : schema.getAllTypesAsList()) { - if (!(type instanceof GraphQLObjectType objectType)) { - continue; - } - String typeName = objectType.getName(); - if (typeName.startsWith("__")) { - continue; - } - for (GraphQLFieldDefinition field : objectType.getFieldDefinitions()) { - String fieldName = field.getName(); - if (fieldName.startsWith("__")) { - continue; - } - FieldCoordinates coords = FieldCoordinates.coordinates(typeName, fieldName); - DataFetcher existing = schema.getCodeRegistry().getDataFetcher(coords, field); - if (existing instanceof AuthorizationDataFetcher) { - continue; - } - code.dataFetcher(coords, new AuthorizationDataFetcher(existing, typeName, fieldName, iamAuthValidator)); - } - } - GraphQLCodeRegistry registry = code.build(); - return schema.transform(builder -> builder.codeRegistry(registry)); - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthorizationDataFetcher.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthorizationDataFetcher.java deleted file mode 100644 index 4a613c2240..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthorizationDataFetcher.java +++ /dev/null @@ -1,191 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql.auth; - -import graphql.execution.DataFetcherResult; -import graphql.schema.DataFetcher; -import graphql.schema.DataFetchingEnvironment; -import graphql.schema.GraphQLAppliedDirective; -import graphql.schema.GraphQLAppliedDirectiveArgument; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLObjectType; -import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; -import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class AuthorizationDataFetcher implements DataFetcher { - - private DataFetcher delegate; - private final String typeName; - private final String fieldName; - private final IamAuthValidator iamAuthValidator; - - public AuthorizationDataFetcher(DataFetcher delegate, String typeName, String fieldName, - IamAuthValidator iamAuthValidator) { - this.delegate = delegate; - this.typeName = typeName; - this.fieldName = fieldName; - this.iamAuthValidator = iamAuthValidator; - } - - public void setDelegate(DataFetcher delegate) { - this.delegate = delegate; - } - - public DataFetcher getDelegate() { - return delegate; - } - - @Override - public Object get(DataFetchingEnvironment environment) throws Exception { - if (!authorize(environment)) { - return DataFetcherResult.newResult() - .data(null) - .error(AppSyncFieldUnauthorizedException.from(environment, fieldName, typeName)) - .build(); - } - return delegate == null ? null : delegate.get(environment); - } - - boolean authorize(DataFetchingEnvironment environment) { - AppSyncAuthContext auth = environment.getGraphQlContext().get(AppSyncAuthContext.KEY); - if (auth == null || auth.graphqlApi() == null) { - return true; - } - if (isDeniedField(auth)) { - return false; - } - if (!modeAllowed(environment, auth)) { - return false; - } - if (auth.authenticationType() == AuthenticationType.AWS_IAM && iamAuthValidator != null) { - String fieldArn = IamAuthValidator.fieldArn( - auth.region(), auth.accountId(), auth.graphqlApi().getApiId(), typeName, fieldName); - if (iamAuthValidator.isFieldDenied(auth.accessKeyId(), fieldArn)) { - return false; - } - } - return true; - } - - private boolean isDeniedField(AppSyncAuthContext auth) { - Set denied = auth.deniedFields(); - if (denied.isEmpty()) { - return false; - } - String shortForm = typeName + "." + fieldName; - if (denied.contains(shortForm)) { - return true; - } - String thisArn = IamAuthValidator.fieldArn( - auth.region(), auth.accountId(), auth.graphqlApi().getApiId(), typeName, fieldName); - for (String entry : denied) { - if (thisArn.equals(entry)) { - return true; - } - } - return false; - } - - private boolean modeAllowed(DataFetchingEnvironment environment, AppSyncAuthContext auth) { - GraphqlApi api = auth.graphqlApi(); - List requirements = effectiveRequirements(environment, api); - if (requirements.isEmpty()) { - return auth.authenticationType() == api.getAuthenticationType(); - } - for (AuthRequirement requirement : requirements) { - if (requirement.mode() == auth.authenticationType() && groupsAllowed(requirement, auth)) { - return true; - } - } - return false; - } - - private List effectiveRequirements(DataFetchingEnvironment environment, GraphqlApi api) { - GraphQLFieldDefinition field = environment.getFieldDefinition(); - GraphQLObjectType parent = parentObjectType(environment); - List fieldReqs = requirementsFrom(field == null ? List.of() : field.getAppliedDirectives(), api); - if (!fieldReqs.isEmpty()) { - return fieldReqs; - } - return requirementsFrom(parent == null ? List.of() : parent.getAppliedDirectives(), api); - } - - private static GraphQLObjectType parentObjectType(DataFetchingEnvironment environment) { - Object parentType = environment.getParentType(); - if (parentType instanceof GraphQLObjectType objectType) { - return objectType; - } - return null; - } - - static List requirementsFrom(List directives, GraphqlApi api) { - List requirements = new ArrayList<>(); - boolean ignoreAwsAuth = AuthMiddleware.hasAdditionalModes(api); - for (GraphQLAppliedDirective directive : directives) { - String name = directive.getName(); - switch (name) { - case "aws_api_key" -> requirements.add(new AuthRequirement(AuthenticationType.API_KEY, null)); - case "aws_iam" -> requirements.add(new AuthRequirement(AuthenticationType.AWS_IAM, null)); - case "aws_oidc" -> requirements.add(new AuthRequirement(AuthenticationType.OPENID_CONNECT, null)); - case "aws_lambda" -> requirements.add(new AuthRequirement(AuthenticationType.AWS_LAMBDA, null)); - case "aws_cognito_user_pools" -> requirements.add( - new AuthRequirement(AuthenticationType.AMAZON_COGNITO_USER_POOLS, groupsArg(directive))); - case "aws_auth" -> { - if (!ignoreAwsAuth && api.getAuthenticationType() == AuthenticationType.AMAZON_COGNITO_USER_POOLS) { - requirements.add(new AuthRequirement( - AuthenticationType.AMAZON_COGNITO_USER_POOLS, groupsArg(directive))); - } - } - default -> { - } - } - } - return requirements; - } - - @SuppressWarnings("unchecked") - static List groupsArg(GraphQLAppliedDirective directive) { - GraphQLAppliedDirectiveArgument arg = directive.getArgument("cognito_groups"); - if (arg == null) { - return List.of(); - } - Object value = arg.getValue(); - if (value instanceof List list) { - List groups = new ArrayList<>(); - for (Object item : list) { - if (item != null) { - groups.add(String.valueOf(item)); - } - } - return groups; - } - return List.of(); - } - - static boolean groupsAllowed(AuthRequirement requirement, AppSyncAuthContext auth) { - if (requirement.groups() == null || requirement.groups().isEmpty()) { - return true; - } - if (auth.authenticationType() != AuthenticationType.AMAZON_COGNITO_USER_POOLS) { - return true; - } - Object groups = auth.identity() == null ? null : auth.identity().get("groups"); - if (!(groups instanceof List callerGroups)) { - return false; - } - for (String required : requirement.groups()) { - for (Object caller : callerGroups) { - if (required.equals(String.valueOf(caller))) { - return true; - } - } - } - return false; - } - - record AuthRequirement(AuthenticationType mode, List groups) { - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/SidecarFieldAuthorizationPlanner.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/SidecarFieldAuthorizationPlanner.java new file mode 100644 index 0000000000..987f3f347d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/SidecarFieldAuthorizationPlanner.java @@ -0,0 +1,115 @@ +package io.github.hectorvent.floci.services.appsync.graphql.auth; + +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.DenyField; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedDirective; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedField; +import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Precomputes which {@code (typeName, fieldName)} coordinates a query must have redacted + * before it reaches the (AWS-agnostic) GraphQL sidecar's {@code /v1/execute}, what used to be + * live per-field checks made during in-process execution, back when execution happened in + * Floci's own process (issue #2917). Takes the {@link PlanResult} from {@code + * GraphqlSidecarClient#plan} (the caller fetches it once and reuses it for the subscription + * check too) and hands its fields to {@link AppSyncAuthRequirements} for the actual "what does + * {@code @aws_auth} mean" interpretation. + */ +@ApplicationScoped +public class SidecarFieldAuthorizationPlanner { + + private final IamAuthValidator iamAuthValidator; + + @Inject + public SidecarFieldAuthorizationPlanner(IamAuthValidator iamAuthValidator) { + this.iamAuthValidator = iamAuthValidator; + } + + /** Empty when nothing needs redacting (including when {@code auth} carries no API context, same as the live path). */ + public List planDenyFields(PlanResult plan, AppSyncAuthContext auth) { + if (auth == null || auth.graphqlApi() == null) { + return List.of(); + } + List denied = new ArrayList<>(); + for (PlannedField field : plan.fields()) { + if (isDenied(field, auth)) { + denied.add(new DenyField(field.typeName(), field.fieldName(), + AppSyncAuth.FIELD_UNAUTHORIZED_TYPE, + AppSyncAuth.fieldUnauthorizedMessage(field.fieldName(), field.typeName()))); + } + } + return denied; + } + + private boolean isDenied(PlannedField field, AppSyncAuthContext auth) { + if (isDeniedField(field, auth)) { + return true; + } + if (!modeAllowed(field, auth)) { + return true; + } + if (auth.authenticationType() == AuthenticationType.AWS_IAM) { + String fieldArn = IamAuthValidator.fieldArn( + auth.region(), auth.accountId(), auth.graphqlApi().getApiId(), field.typeName(), field.fieldName()); + if (iamAuthValidator.isFieldDenied(auth.accessKeyId(), fieldArn)) { + return true; + } + } + return false; + } + + private boolean isDeniedField(PlannedField field, AppSyncAuthContext auth) { + Set denied = auth.deniedFields(); + if (denied.isEmpty()) { + return false; + } + if (denied.contains(field.typeName() + "." + field.fieldName())) { + return true; + } + String arn = IamAuthValidator.fieldArn( + auth.region(), auth.accountId(), auth.graphqlApi().getApiId(), field.typeName(), field.fieldName()); + return denied.contains(arn); + } + + private boolean modeAllowed(PlannedField field, AppSyncAuthContext auth) { + List requirements = + AppSyncAuthRequirements.requirementsFrom(toDirectiveUse(field.directives()), auth.graphqlApi()); + if (requirements.isEmpty()) { + requirements = + AppSyncAuthRequirements.requirementsFrom(toDirectiveUse(field.typeDirectives()), auth.graphqlApi()); + } + if (requirements.isEmpty()) { + return auth.authenticationType() == auth.graphqlApi().getAuthenticationType(); + } + for (AppSyncAuthRequirements.AuthRequirement requirement : requirements) { + if (requirement.mode() == auth.authenticationType() + && AppSyncAuthRequirements.groupsAllowed(requirement, auth)) { + return true; + } + } + return false; + } + + @SuppressWarnings("unchecked") + private static List toDirectiveUse(List directives) { + List uses = new ArrayList<>(); + for (PlannedDirective directive : directives) { + List groups = List.of(); + if (directive.args() instanceof Map args) { + Object raw = args.get("cognito_groups"); + if (raw instanceof List list) { + groups = list.stream().map(String::valueOf).toList(); + } + } + uses.add(new AppSyncAuthRequirements.DirectiveUse(directive.name(), groups)); + } + return uses; + } +} 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 deleted file mode 100644 index 7bb0f770e2..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarRegistry.java +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index c4276df4d8..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalars.java +++ /dev/null @@ -1,470 +0,0 @@ -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/resources/application.yml b/src/main/resources/application.yml index d31c6b03ba..6cfb985867 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -101,7 +101,6 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkService - --initialize-at-run-time=io.github.hectorvent.floci.services.elb.ElbClassicService - --initialize-at-run-time=io.github.hectorvent.floci.services.datasync.DataSyncService - - --initialize-at-run-time=graphql.util.IdGenerator - --initialize-at-run-time=io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials - --initialize-at-run-time=io.github.hectorvent.floci.services.ssoportal.SsoPortalService # snappy-java (Firehose Snappy/HADOOP_SNAPPY delivery) extracts and loads a @@ -688,6 +687,9 @@ floci: vtl-max-loops: 10000 # Maximum #foreach iterations a VTL resolver template may execute (truncates the loop, does not fail the template) vtl-max-output-chars: 1048576 # Maximum characters a VTL resolver template may render before it fails vtl-timeout-millis: 5000 # Maximum wall-clock time a VTL resolver template may spend evaluating before it fails + # graphql-url: http://floci-graphql:8181 # set to skip sidecar container management + # Exact version on purpose: a cached :latest is never re-pulled. Published from floci-io/floci-sidecars. + graphql-image: "floci/floci-sidecar-graphql:0.2.0" s3vectors: enabled: true s3tables: diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java index c2ef2c2b3b..17a9c3a6cb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.github.hectorvent.floci.testutil.AppSyncRequestSigner; import io.restassured.RestAssured; import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -23,7 +24,9 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertTrue; +/** Runs against the real GraphQL sidecar image, started by {@link GraphqlSidecarManager}. */ @QuarkusTest +@TestProfile(AppSyncGraphqlSidecarProfile.class) class AppSyncAuthIntegrationTest { private static final String MGMT_AUTH = @@ -34,6 +37,7 @@ class AppSyncAuthIntegrationTest { @BeforeAll static void configureRestAssured() { + AppSyncGraphqlSidecarProfile.requireDockerAndTheSidecarImage(); RestAssuredJsonUtils.configureAwsContentTypes(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java index e7625a8a34..0d55b9a700 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.appsync.graphql.AppSyncErrorFormatter import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -20,7 +21,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertTrue; +/** Runs against the real GraphQL sidecar image, started by {@link GraphqlSidecarManager}. */ @QuarkusTest +@TestProfile(AppSyncGraphqlSidecarProfile.class) class AppSyncExecutionIntegrationTest { private static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request"; @@ -33,6 +36,7 @@ class AppSyncExecutionIntegrationTest { @BeforeAll static void configureRestAssured() { + AppSyncGraphqlSidecarProfile.requireDockerAndTheSidecarImage(); RestAssuredJsonUtils.configureAwsContentTypes(); } @@ -280,6 +284,99 @@ class AppSyncExecutionIntegrationTest { .body("errors[0].errorType", equalTo("OperationNotSupported")); } + @Test + void awsDateTimeLiteralCoercionRejectsInvalidValueAsValidationErrorNotServerError() { + // graphql-java only catches CoercingParseLiteralException while validating a literal + // argument, and every AppSyncScalars parseLiteral() used to delegate to parseValue(), + // which throws CoercingParseValueException instead: uncaught, that escaped as an HTTP + // 500 rather than becoming a spec-correct ValidationError. Fixed in AppSyncScalars. + String scalarApi = createApi("scalar-lit-" + UUID.randomUUID().toString().substring(0, 8)); + String scalarKey = createApiKey(scalarApi); + startSchema(scalarApi, "type Query { echo(t: AWSDateTime): AWSDateTime }"); + awaitSchemaSuccess(scalarApi); + + given() + .header("x-api-key", scalarKey) + .contentType("application/json") + .body("{\"query\":\"{ echo(t: \\\"not-a-date\\\") }\"}") + .when() + .post("/v1/apis/" + scalarApi + "/graphql") + .then() + .statusCode(200) + .body("errors[0].errorType", equalTo("ValidationError")) + .body("errors[0].message", containsString("Invalid AWSDateTime")); + + given() + .header("x-api-key", scalarKey) + .contentType("application/json") + .body("{\"query\":\"{ echo(t: \\\"2026-01-01T00:00:00Z\\\") }\"}") + .when() + .post("/v1/apis/" + scalarApi + "/graphql") + .then() + .statusCode(200) + .body("errors", nullValue()); + } + + @Test + void awsDateTimeVariableCoercionRejectsInvalidValueAndAcceptsValid() { + // Proves the real AWSDateTime Coercing actually runs through the sidecar's schema + // build, not just that StartSchemaCreation accepts the type name (issue #2917). + String scalarApi = createApi("scalar-" + UUID.randomUUID().toString().substring(0, 8)); + String scalarKey = createApiKey(scalarApi); + startSchema(scalarApi, "type Query { echo(t: AWSDateTime): AWSDateTime }"); + awaitSchemaSuccess(scalarApi); + + given() + .header("x-api-key", scalarKey) + .contentType("application/json") + .body(""" + { + "query": "query($t: AWSDateTime) { echo(t: $t) }", + "variables": {"t": "not-a-date"} + } + """) + .when() + .post("/v1/apis/" + scalarApi + "/graphql") + .then() + .statusCode(200) + .body("errors[0].errorType", equalTo("ValidationError")) + .body("errors[0].message", containsString("Invalid AWSDateTime")); + + given() + .header("x-api-key", scalarKey) + .contentType("application/json") + .body(""" + { + "query": "query($t: AWSDateTime) { echo(t: $t) }", + "variables": {"t": "2026-01-01T00:00:00Z"} + } + """) + .when() + .post("/v1/apis/" + scalarApi + "/graphql") + .then() + .statusCode(200) + .body("errors", nullValue()); + } + + @Test + void fragmentCycleAgainstProtectedFieldNeverLeaksRealData() { + // Proves the sidecar's fail-closed /v1/plan behavior: a query the planner can't + // analyze must never fall back to "nothing to authorize, run it anyway." + String protectedApi = createApi("protected-" + UUID.randomUUID().toString().substring(0, 8)); + String protectedKey = createApiKey(protectedApi); + startSchema(protectedApi, "type Query { hello: String secret: String @aws_iam }"); + awaitSchemaSuccess(protectedApi); + + given() + .header("x-api-key", protectedKey) + .contentType("application/json") + .body("{\"query\":\"{ hello secret ...a } fragment a on Query { ...a }\"}") + .when() + .post("/v1/apis/" + protectedApi + "/graphql") + .then() + .body("data.secret", nullValue()); + } + @Test void whitespaceOnlyQueryReturns200SyntaxError() { given() @@ -301,7 +398,7 @@ class AppSyncExecutionIntegrationTest { awaitSchemaSuccess(hydrateApi); schemaRegistry.remove(hydrateApi); - assertTrue(schemaRegistry.getSchema(hydrateApi).isEmpty()); + assertTrue(schemaRegistry.getSdl(hydrateApi).isEmpty()); given() .header("x-api-key", hydrateKey) diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncGraphqlSidecarProfile.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncGraphqlSidecarProfile.java new file mode 100644 index 0000000000..7038ebf11d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncGraphqlSidecarProfile.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.appsync; + +import io.quarkus.test.junit.QuarkusTestProfile; +import org.eclipse.microprofile.config.ConfigProvider; +import org.junit.jupiter.api.Assumptions; + +import java.util.Map; + +/** + * Shared by every AppSync integration test that needs the real GraphQL sidecar container, started + * by {@link GraphqlSidecarManager} exactly as in production. Namespaces the container as + * {@code floci-appsync-test-graphql} so the manager's remove-before-start never touches a + * developer's real running Floci. Needs Docker; skipped without it. Locally it is also skipped + * when the pinned image is not present, so a developer without registry access is not stuck; in CI + * a missing image is a failure, since a vanished tag must not pass silently. + * + *

Every test class that uses this profile shares one Quarkus test application instance (and + * one running sidecar container) rather than paying a restart for each, since Quarkus keys its + * test-application cache by the profile class identity. + */ +public class AppSyncGraphqlSidecarProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Map.of("floci.docker.resource-namespace", "appsync-test"); + } + + public static void requireDockerAndTheSidecarImage() { + Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for AppSync integration tests"); + String image = ConfigProvider.getConfig().getValue("floci.services.appsync.graphql-image", String.class); + Assumptions.assumeTrue(imageUsable(image), "GraphQL sidecar image " + image + " is not present locally"); + } + + private static boolean isDockerAvailable() { + return run("docker", "version", "--format", "{{.Server.Version}}"); + } + + private static boolean imageUsable(String image) { + if ("true".equals(System.getenv("CI"))) { + return true; + } + return run("docker", "image", "inspect", image); + } + + private static boolean run(String... command) { + try { + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + return process.waitFor() == 0; + } catch (Exception e) { + return false; + } + } +} 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 afa88dedac..a7afd6ee7d 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 @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -18,7 +19,12 @@ import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; +/** + * Runs against the real GraphQL sidecar image, started by {@link GraphqlSidecarManager}: + * {@code StartSchemaCreation} validates against it, so it needs to be up. + */ @QuarkusTest +@TestProfile(AppSyncGraphqlSidecarProfile.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class AppSyncIntegrationTest { @@ -31,6 +37,7 @@ class AppSyncIntegrationTest { @BeforeAll static void configureRestAssured() { + AppSyncGraphqlSidecarProfile.requireDockerAndTheSidecarImage(); RestAssuredJsonUtils.configureAwsContentTypes(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java new file mode 100644 index 0000000000..f30f977262 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.appsync; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.DenyField; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult; +import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The wire contract Floci owns towards the GraphQL sidecar: request shapes for each endpoint, + * including the {@code scalars} mapping the sidecar's generic coercion kinds require, and how the + * sidecar's 200 / 400 / other answers become AppSync transport errors. graphql-java behavior lives + * in the sidecar's own repository. + */ +class GraphqlSidecarClientTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final AtomicReference lastPath = new AtomicReference<>(); + private final AtomicReference lastBody = new AtomicReference<>(); + private HttpServer server; + private GraphqlSidecarClient client; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.start(); + GraphqlSidecarManager manager = mock(GraphqlSidecarManager.class); + when(manager.ensureReady()).thenReturn("http://127.0.0.1:" + server.getAddress().getPort()); + client = new GraphqlSidecarClient(manager, mapper); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void validateSchemaPostsTheSdlAndScalarMapping() { + answer("/v1/schema/validate", 200, "{\"valid\":true}"); + + client.validateSchema("type Query { hello: String }", Map.of("AWSDateTime", "date-time")); + + assertThat(lastPath.get(), equalTo("/v1/schema/validate")); + assertThat(lastBody.get().get("sdl").asText(), equalTo("type Query { hello: String }")); + assertThat(lastBody.get().get("scalars").get("AWSDateTime").asText(), equalTo("date-time")); + } + + @Test + void planPostsTheQueryAndScalarMappingAndReadsFieldsAndDirectives() { + answer("/v1/plan", 200, "{\"operationType\":\"QUERY\",\"fields\":[" + + "{\"typeName\":\"Query\",\"fieldName\":\"hello\"," + + "\"directives\":[{\"name\":\"aws_iam\",\"args\":{}}],\"typeDirectives\":[]}]}"); + + PlanResult result = client.plan("type Query { hello: String }", Map.of("AWSJSON", "json-string"), + "{ hello }", null); + + assertThat(lastBody.get().get("scalars").get("AWSJSON").asText(), equalTo("json-string")); + assertThat(lastBody.get().has("operationName"), is(false)); + assertThat(result.operationType(), equalTo("QUERY")); + assertThat(result.fields().get(0).typeName(), equalTo("Query")); + assertThat(result.fields().get(0).fieldName(), equalTo("hello")); + assertThat(result.fields().get(0).directives().get(0).name(), equalTo("aws_iam")); + } + + @Test + void executePostsSdlScalarsVariablesAndDenyFields() { + answer("/v1/execute", 200, "{\"data\":{\"hello\":null},\"errors\":[]}"); + + Map result = client.execute("type Query { hello: String }", Map.of("AWSJSON", "json-string"), + "{ hello }", Map.of("x", 1), "GetHello", + List.of(new DenyField("Query", "secret", "Unauthorized", "nope"))); + + assertThat(lastBody.get().get("scalars").get("AWSJSON").asText(), equalTo("json-string")); + assertThat(lastBody.get().get("variables").get("x").asInt(), equalTo(1)); + assertThat(lastBody.get().get("operationName").asText(), equalTo("GetHello")); + assertThat(lastBody.get().get("denyFields").get(0).get("typeName").asText(), equalTo("Query")); + assertThat(lastBody.get().get("denyFields").get(0).get("errorType").asText(), equalTo("Unauthorized")); + assertThat(result.get("data"), is(Collections.singletonMap("hello", null))); + } + + @Test + void schemaValidationBadRequestBecomesSchemaValidationExceptionWithIssues() { + answer("/v1/schema/validate", 400, "{\"error\":\"bad schema\",\"issues\":[" + + "{\"category\":\"PARSER_ERROR\",\"message\":\"unexpected token\",\"line\":1,\"column\":5}]}"); + + GraphqlSidecarClient.SchemaValidationException error = assertThrows( + GraphqlSidecarClient.SchemaValidationException.class, + () -> client.validateSchema("type Query {", Map.of())); + + assertThat(error.getMessage(), equalTo("bad schema")); + assertThat(error.issues().get(0).category(), equalTo("PARSER_ERROR")); + assertThat(error.issues().get(0).line(), equalTo(1)); + } + + @Test + void otherSidecarFailuresBecomeInternalFailureException() { + answer("/v1/execute", 500, "{\"error\":\"boom\"}"); + + AppSyncTransportException error = assertThrows(AppSyncTransportException.class, + () -> client.execute("type Query { hello: String }", Map.of(), "{ hello }", Map.of(), null, List.of())); + + assertThat(error.getErrorType(), equalTo("InternalFailureException")); + assertThat(error.getHttpStatus(), equalTo(500)); + } + + @Test + void unreachableSidecarBecomesInternalFailureException() { + GraphqlSidecarManager down = mock(GraphqlSidecarManager.class); + when(down.ensureReady()).thenThrow(new IllegalStateException("speaks sidecar contract 2")); + GraphqlSidecarClient offline = new GraphqlSidecarClient(down, mapper); + + AppSyncTransportException error = assertThrows(AppSyncTransportException.class, + () -> offline.validateSchema("type Query { hello: String }", Map.of())); + + assertThat(error.getErrorType(), equalTo("InternalFailureException")); + assertThat(error.getMessage(), equalTo("Failed to call GraphQL sidecar for schema validation: speaks sidecar contract 2")); + } + + private void answer(String path, int status, String body) { + server.createContext(path, exchange -> { + lastPath.set(exchange.getRequestURI().getPath()); + lastBody.set(mapper.readTree(exchange.getRequestBody())); + respond(exchange, status, body); + }); + } + + private static void respond(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManagerTest.java new file mode 100644 index 0000000000..e91b3aae23 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManagerTest.java @@ -0,0 +1,162 @@ +package io.github.hectorvent.floci.services.appsync; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Optional; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class GraphqlSidecarManagerTest { + + private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class); + private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); + private final EmulatorConfig.AppSyncServiceConfig appsync = mock(EmulatorConfig.AppSyncServiceConfig.class); + private final EmulatorConfig config = config(appsync); + private HttpServer fakeSidecar; + + @AfterEach + void stopFakeSidecar() { + if (fakeSidecar != null) { + fakeSidecar.stop(0); + } + } + + @Test + void configuredUrlSkipsContainerManagement() { + when(appsync.graphqlUrl()).thenReturn(Optional.of("http://graphql.internal:8181/")); + + GraphqlSidecarManager manager = manager(); + + assertEquals("http://graphql.internal:8181", manager.ensureReady()); + verifyNoInteractions(containerBuilder, lifecycleManager); + } + + @Test + void staleManagedEndpointIsDiscarded() throws Exception { + when(appsync.graphqlUrl()).thenReturn(Optional.empty()); + + GraphqlSidecarManager manager = manager(); + setField(manager, "resolvedUrl", "http://127.0.0.1:1"); + setField(manager, "containerId", "stale-graphql"); + + assertFalse(manager.isAvailable()); + verify(lifecycleManager).stopAndRemove("stale-graphql", null); + assertNull(getField(manager, "resolvedUrl")); + assertNull(getField(manager, "containerId")); + } + + @Test + void contractOneSidecarIsAvailable() throws Exception { + String url = startFakeSidecar(200, "{\"status\":\"ok\",\"name\":\"graphql\",\"version\":\"0.2.0\",\"contract\":\"1\"}"); + when(appsync.graphqlUrl()).thenReturn(Optional.of(url)); + + GraphqlSidecarManager manager = manager(); + + assertTrue(manager.isAvailable()); + assertEquals(url, manager.ensureReady()); + verifyNoInteractions(containerBuilder, lifecycleManager); + } + + @Test + void otherContractMajorFailsFastNamingTheFix() throws Exception { + String url = startFakeSidecar(200, "{\"status\":\"ok\",\"name\":\"graphql\",\"version\":\"1.3.0\",\"contract\":\"2\"}"); + when(appsync.graphqlUrl()).thenReturn(Optional.of(url)); + when(appsync.graphqlImage()).thenReturn("floci/floci-sidecar-graphql:0.2.0"); + + GraphqlSidecarManager manager = manager(); + + IllegalStateException available = assertThrows(IllegalStateException.class, manager::isAvailable); + IllegalStateException ready = assertThrows(IllegalStateException.class, manager::ensureReady); + assertThat(available.getMessage(), containsString("speaks sidecar contract 2")); + assertThat(available.getMessage(), containsString("requires contract 1")); + assertThat(available.getMessage(), containsString("graphql 1.3.0")); + assertThat(ready.getMessage(), containsString(GraphqlSidecarManager.IMAGE_ENV)); + assertThat(ready.getMessage(), containsString("floci/floci-sidecar-graphql:0.2.0")); + assertThat(ready.getMessage(), containsString(GraphqlSidecarManager.URL_ENV)); + assertNull(getField(manager, "resolvedUrl")); + } + + @Test + void preContractSidecarWithTextHealthIsAccepted() throws Exception { + String url = startFakeSidecar(200, "ok"); + when(appsync.graphqlUrl()).thenReturn(Optional.of(url)); + + GraphqlSidecarManager manager = manager(); + + assertTrue(manager.isAvailable()); + assertEquals(url, manager.ensureReady()); + } + + @Test + void unhealthySidecarIsNotReadyRatherThanWrong() throws Exception { + String url = startFakeSidecar(503, "{\"status\":\"starting\",\"contract\":\"2\"}"); + when(appsync.graphqlUrl()).thenReturn(Optional.of(url)); + + GraphqlSidecarManager manager = manager(); + + assertFalse(manager.isAvailable()); + assertEquals(url, manager.ensureReady()); + } + + private GraphqlSidecarManager manager() { + return new GraphqlSidecarManager(containerBuilder, lifecycleManager, config, new ObjectMapper()); + } + + private static EmulatorConfig config(EmulatorConfig.AppSyncServiceConfig appsync) { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + when(config.services()).thenReturn(services); + when(services.appsync()).thenReturn(appsync); + return config; + } + + private String startFakeSidecar(int status, String healthBody) { + try { + fakeSidecar = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + } catch (IOException e) { + throw new IllegalStateException(e); + } + fakeSidecar.createContext("/health", exchange -> { + byte[] bytes = healthBody.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + fakeSidecar.start(); + return "http://127.0.0.1:" + fakeSidecar.getAddress().getPort(); + } + + private static void setField(Object target, String name, Object value) throws Exception { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + + private static Object getField(Object target, String name) throws Exception { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java index b69b7c3866..e955277ae7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java @@ -1,14 +1,8 @@ package io.github.hectorvent.floci.services.appsync.graphql; -import graphql.ErrorType; -import graphql.ExecutionResult; -import graphql.ExecutionResultImpl; -import graphql.GraphQLError; -import graphql.GraphqlErrorBuilder; -import graphql.language.SourceLocation; -import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncFieldUnauthorizedException; import org.junit.jupiter.api.Test; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -17,22 +11,22 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +/** + * {@link AppSyncErrorFormatter} now formats the plain {@code Map}/{@code List} JSON the GraphQL + * sidecar's {@code /v1/execute} returns (graphql-java's own {@code toSpecification()} shape), + * not a live graphql-java {@code ExecutionResult} (issue #2917); these build that shape by hand. + */ class AppSyncErrorFormatterTest { private final AppSyncErrorFormatter formatter = new AppSyncErrorFormatter(); @Test void invalidSyntaxMapsToTopLevelSyntaxError() { - GraphQLError syntaxError = GraphqlErrorBuilder.newError() - .message("Invalid syntax near '{'") - .errorType(ErrorType.InvalidSyntax) - .location(new SourceLocation(1, 1)) - .build(); - ExecutionResult result = ExecutionResultImpl.newExecutionResult() - .addError(syntaxError) - .build(); + Map sidecarResult = Map.of( + "errors", List.of(sidecarError("Invalid syntax near '{'", List.of(Map.of("line", 1, "column", 1)), + null, "InvalidSyntax"))); - Map response = formatter.format(result); + Map response = formatter.format(sidecarResult); assertFalse(response.containsKey("data")); @SuppressWarnings("unchecked") @@ -48,18 +42,14 @@ class AppSyncErrorFormatterTest { @Test void validationErrorUsesTopLevelErrorTypeNotExtensionsOnly() { - GraphQLError validationError = GraphqlErrorBuilder.newError() - .message("Validation error of type FieldUndefined: Field 'nope' is undefined") - .errorType(ErrorType.ValidationError) - .location(new SourceLocation(1, 3)) - .path(List.of("nope")) - .build(); - ExecutionResult result = ExecutionResultImpl.newExecutionResult() - .data(null) - .addError(validationError) - .build(); + Map data = new LinkedHashMap<>(); + data.put("nope", null); + Map sidecarResult = Map.of( + "data", data, + "errors", List.of(sidecarError("Validation error of type FieldUndefined: Field 'nope' is undefined", + List.of(Map.of("line", 1, "column", 3)), List.of("nope"), "ValidationError"))); - Map response = formatter.format(result); + Map response = formatter.format(sidecarResult); @SuppressWarnings("unchecked") List> errors = (List>) response.get("errors"); @@ -90,26 +80,18 @@ class AppSyncErrorFormatterTest { Map forBraces = formatter.transportError( "MalformedHttpRequestException", AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE); - Map forArray = formatter.transportError( - "MalformedHttpRequestException", - AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE); assertEquals("Unable to parse GraphQL query.", - ((List) forBraces.get("errors")).isEmpty() ? null - : ((Map) ((List) forBraces.get("errors")).get(0)).get("message")); - assertEquals("Unable to parse GraphQL query.", - ((Map) ((List) forArray.get("errors")).get(0)).get("message")); + ((Map) ((List) forBraces.get("errors")).get(0)).get("message")); } @Test void successfulDataIncludedWithoutErrors() { - Map data = new java.util.LinkedHashMap<>(); + Map data = new LinkedHashMap<>(); data.put("hello", null); - ExecutionResult result = ExecutionResultImpl.newExecutionResult() - .data(data) - .build(); + Map sidecarResult = Map.of("data", data); - Map response = formatter.format(result); + Map response = formatter.format(sidecarResult); @SuppressWarnings("unchecked") Map responseData = (Map) response.get("data"); @@ -120,15 +102,14 @@ class AppSyncErrorFormatterTest { @Test void unauthorizedClassificationMapsToUnauthorized() { - GraphQLError error = new AppSyncFieldUnauthorizedException(List.of("hello"), "hello", "Query"); - Map data = new java.util.LinkedHashMap<>(); + Map data = new LinkedHashMap<>(); data.put("hello", null); - ExecutionResult result = ExecutionResultImpl.newExecutionResult() - .data(data) - .addError(error) - .build(); + Map sidecarResult = Map.of( + "data", data, + "errors", List.of(sidecarError("Not Authorized to access hello on type Query", + null, List.of("hello"), "Unauthorized"))); - Map response = formatter.format(result); + Map response = formatter.format(sidecarResult); @SuppressWarnings("unchecked") List> errors = (List>) response.get("errors"); @@ -137,4 +118,20 @@ class AppSyncErrorFormatterTest { assertEquals(List.of("hello"), errors.get(0).get("path")); assertNull(errors.get(0).get("errorInfo")); } + + private static Map sidecarError(String message, List> locations, + List path, String classification) { + Map error = new LinkedHashMap<>(); + error.put("message", message); + if (locations != null) { + error.put("locations", locations); + } + if (path != null) { + error.put("path", path); + } + if (classification != null) { + error.put("extensions", Map.of("classification", classification)); + } + return error; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java index dbbaa9c58b..f8d508c5b4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java @@ -1,13 +1,14 @@ package io.github.hectorvent.floci.services.appsync.graphql; import com.fasterxml.jackson.databind.ObjectMapper; -import graphql.GraphQL; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.services.appsync.AppSyncService; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient; import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuth; import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuthContext; import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthMiddleware; +import io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuthorizationPlanner; import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; import jakarta.ws.rs.core.HttpHeaders; @@ -27,8 +28,6 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,7 +40,11 @@ class AppSyncExecutionControllerTest { @Mock SchemaRegistry schemaRegistry; @Mock - QueryExecutor queryExecutor; + SidecarSchemaCompiler schemaCompiler; + @Mock + SidecarFieldAuthorizationPlanner fieldAuthorizationPlanner; + @Mock + GraphqlSidecarClient sidecarClient; @Mock AuthMiddleware authMiddleware; @Mock @@ -55,7 +58,9 @@ class AppSyncExecutionControllerTest { controller = new AppSyncExecutionController( appSyncService, schemaRegistry, - queryExecutor, + schemaCompiler, + fieldAuthorizationPlanner, + sidecarClient, new AppSyncErrorFormatter(), new ObjectMapper(), authMiddleware, @@ -67,14 +72,17 @@ class AppSyncExecutionControllerTest { } @Test - void unexpectedExecutorFailureReturns500InternalFailure() { + void unexpectedSidecarFailureReturns500InternalFailure() { GraphqlApi api = new GraphqlApi(); api.setApiId("api-1"); when(appSyncService.getGraphqlApi("api-1")).thenReturn(api); when(authMiddleware.authenticate(any(), any(), any())).thenReturn(authContext(api)); - when(schemaRegistry.getGraphQL("api-1")).thenReturn(Optional.of(mock(GraphQL.class))); - when(queryExecutor.execute(any(GraphQL.class), eq("{ hello }"), isNull(), isNull(), any())) - .thenThrow(new RuntimeException("boom")); + when(schemaRegistry.getSdl("api-1")).thenReturn(Optional.of("type Query { hello: String }")); + when(schemaCompiler.withDirectivesAndScalars(any())).thenReturn("prepared-sdl"); + when(schemaCompiler.scalarKindMapping()).thenReturn(Map.of()); + when(sidecarClient.plan(any(), any(), any(), any())).thenReturn(new GraphqlSidecarClient.PlanResult("QUERY", List.of())); + when(fieldAuthorizationPlanner.planDenyFields(any(), any())).thenReturn(List.of()); + when(sidecarClient.execute(any(), any(), any(), any(), any(), any())).thenThrow(new RuntimeException("boom")); Response response = controller.execute("api-1", jsonHeaders, "{\"query\":\"{ hello }\"}"); @@ -138,7 +146,7 @@ class AppSyncExecutionControllerTest { } @Test - void authFailureReturns401WithoutCallingExecutor() { + void authFailureReturns401WithoutCallingSidecar() { GraphqlApi api = new GraphqlApi(); api.setApiId("api-1"); when(appSyncService.getGraphqlApi("api-1")).thenReturn(api); diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutorTest.java deleted file mode 100644 index ab90d9f9c7..0000000000 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutorTest.java +++ /dev/null @@ -1,151 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql; - -import graphql.schema.DataFetcher; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; - -import static graphql.Scalars.GraphQLString; -import static graphql.schema.FieldCoordinates.coordinates; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class QueryExecutorTest { - - private QueryExecutor executor; - private GraphQLSchema helloSchema; - private GraphQLSchema subscriptionSchema; - private GraphQLSchema multiOpSchema; - - @BeforeEach - void setUp() { - AppSyncErrorFormatter formatter = new AppSyncErrorFormatter(); - executor = new QueryExecutor(formatter); - AppSyncSchemaParser parser = new AppSyncSchemaParser(new AppSyncScalarRegistry()); - helloSchema = parser.parse("type Query { hello: String }"); - subscriptionSchema = parser.parse(""" - type Query { hello: String } - type Subscription { onHello: String } - """); - multiOpSchema = parser.parse(""" - type Query { - hello: String - bye: String - } - """); - } - - @Test - void nullableFieldReturnsNullWithoutDataFetcher() { - Map response = executor.execute(helloSchema, "{ hello }", null, null); - - @SuppressWarnings("unchecked") - Map data = (Map) response.get("data"); - assertTrue(data.containsKey("hello")); - assertNull(data.get("hello")); - assertTrue(!response.containsKey("errors") || ((List) response.get("errors")).isEmpty()); - } - - @Test - void usesAsyncStrategiesAndSupportsSimpleQuery() { - Map response = executor.execute(helloSchema, "query Q { hello }", Map.of(), "Q"); - - @SuppressWarnings("unchecked") - Map data = (Map) response.get("data"); - assertNull(data.get("hello")); - } - - @Test - void httpSubscriptionReturnsOperationNotSupported() { - Map response = executor.execute( - subscriptionSchema, - "subscription { onHello }", - null, - null); - - assertTrue(response.containsKey("errors")); - @SuppressWarnings("unchecked") - List> errors = (List>) response.get("errors"); - assertEquals(1, errors.size()); - assertEquals("OperationNotSupported", errors.get(0).get("errorType")); - Object data = response.get("data"); - if (data != null) { - assertTrue(!(data instanceof org.reactivestreams.Publisher), - "Must not return Publisher JSON for HTTP subscriptions"); - } - } - - @Test - void missingOperationNameWithMultipleOpsThrowsBadRequest() { - AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, () -> - executor.execute(multiOpSchema, """ - query A { hello } - query B { bye } - """, null, null)); - - assertEquals(400, ex.getHttpStatus()); - assertEquals("BadRequestException", ex.getErrorType()); - assertEquals("Missing operation name.", ex.getMessage()); - } - - @Test - void operationNameSelectsAmongMultipleOps() { - Map response = executor.execute(multiOpSchema, """ - query A { hello } - query B { bye } - """, null, "B"); - - @SuppressWarnings("unchecked") - Map data = (Map) response.get("data"); - assertTrue(data.containsKey("bye")); - assertNull(data.get("bye")); - } - - @Test - void syntaxErrorFormattedAsSyntaxError() { - Map response = executor.execute(helloSchema, "{ hello", null, null); - - @SuppressWarnings("unchecked") - List> errors = (List>) response.get("errors"); - assertEquals("SyntaxError", errors.get(0).get("errorType")); - } - - @Test - void executePassesGraphQlContextKeys() { - DataFetcher fetcher = env -> { - assertEquals("IAM Authorization", env.getGraphQlContext().get("authType")); - Object identity = env.getGraphQlContext().get("identity"); - assertTrue(identity instanceof Map); - assertTrue(((Map) identity).get("sourceIp") instanceof List); - return env.getGraphQlContext().get("authType"); - }; - GraphQLObjectType query = GraphQLObjectType.newObject() - .name("Query") - .field(f -> f.name("hello").type(GraphQLString)) - .build(); - GraphQLSchema schema = GraphQLSchema.newSchema() - .query(query) - .codeRegistry(graphql.schema.GraphQLCodeRegistry.newCodeRegistry() - .dataFetcher(coordinates("Query", "hello"), fetcher) - .build()) - .build(); - Map ctx = Map.of( - "identity", Map.of("sourceIp", List.of("127.0.0.1")), - "authType", "IAM Authorization", - "deniedFields", List.of()); - - Map response = executor.execute( - SchemaRegistry.buildGraphQL(schema), "{ hello }", null, null, ctx); - - @SuppressWarnings("unchecked") - Map data = (Map) response.get("data"); - assertEquals("IAM Authorization", data.get("hello")); - } -} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java index 18cc295bae..cd8eba0fee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java @@ -3,7 +3,6 @@ package io.github.hectorvent.floci.services.appsync.graphql; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; -import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -23,6 +22,8 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class SchemaCreationWorkerRehydrateTest { + @Mock + SidecarSchemaCompiler schemaCompiler; @Mock AccountAwareStorageBackend schemaStatusStore; @Mock @@ -35,9 +36,9 @@ class SchemaCreationWorkerRehydrateTest { @BeforeEach void setUp() { - schemaRegistry = new SchemaRegistry(new AppSyncSchemaParser(new AppSyncScalarRegistry())); + schemaRegistry = new SchemaRegistry(); worker = new SchemaCreationWorker( - schemaRegistry, schemaStatusStore, schemaStore, config, new ObjectMapper()); + schemaRegistry, schemaCompiler, schemaStatusStore, schemaStore, config, new ObjectMapper()); } @Test @@ -47,8 +48,7 @@ class SchemaCreationWorkerRehydrateTest { worker.rehydrateSchemas(); - assertTrue(schemaRegistry.getSchema("api-1").isPresent()); - assertTrue(schemaRegistry.getGraphQL("api-1").isPresent()); + assertTrue(schemaRegistry.getSdl("api-1").isPresent()); } @Test @@ -62,21 +62,27 @@ class SchemaCreationWorkerRehydrateTest { worker.rehydrateSchemas(); - assertTrue(schemaRegistry.getSchema("default-api").isPresent()); - assertTrue(schemaRegistry.getSchema("other-acct-api").isPresent()); - assertTrue(schemaRegistry.getGraphQL("other-acct-api").isPresent()); + assertTrue(schemaRegistry.getSdl("default-api").isPresent()); + assertTrue(schemaRegistry.getSdl("other-acct-api").isPresent()); verify(schemaStore, never()).keys(); verify(schemaStore, never()).get(anyString()); } + /** + * Rehydrate doesn't re-validate against the sidecar (see {@link SchemaCreationWorker#rehydrateSchemas}'s + * javadoc): a persisted SDL already passed validation once. So unlike the old in-process + * registry, a garbage SDL here is still registered as raw text; the old + * "skip unparseable SDL" behavior no longer applies. + */ @Test - void rehydrateSkipsUnparseableSdl() { + void rehydrateDoesNotValidateAgainstTheSidecar() { when(schemaStore.scanAllAccountsAsMap()) .thenReturn(Map.of("bad-api", "not valid sdl {{{")); worker.rehydrateSchemas(); - assertTrue(schemaRegistry.getSchema("bad-api").isEmpty()); + assertTrue(schemaRegistry.getSdl("bad-api").isPresent()); + verify(schemaCompiler, never()).validate(anyString()); } @Test @@ -85,7 +91,7 @@ class SchemaCreationWorkerRehydrateTest { worker.rehydrateSchemas(); - assertTrue(schemaRegistry.getSchema("empty").isEmpty()); + assertTrue(schemaRegistry.getSdl("empty").isEmpty()); verify(schemaStore, never()).put(anyString(), anyString()); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java index 7d9fe20387..645d1e51b9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java @@ -1,17 +1,15 @@ package io.github.hectorvent.floci.services.appsync.graphql; -import graphql.GraphQL; -import graphql.schema.GraphQLAppliedDirective; -import graphql.schema.GraphQLFieldDefinition; -import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +/** + * {@link SchemaRegistry} is now just an {@code apiId -> raw SDL} cache: schema compilation + * happens in the GraphQL sidecar, not here (issue #2917). + */ class SchemaRegistryTest { private static final String SDL = "type Query { hello: String }"; @@ -20,48 +18,34 @@ class SchemaRegistryTest { @BeforeEach void setUp() { - registry = new SchemaRegistry(new AppSyncSchemaParser(new AppSyncScalarRegistry())); + registry = new SchemaRegistry(); } @Test - void getGraphQLReturnsSameInstanceAcrossCalls() { + void getSdlReturnsWhatWasRegistered() { registry.register("api-1", SDL); - GraphQL first = registry.getGraphQL("api-1").orElseThrow(); - GraphQL second = registry.getGraphQL("api-1").orElseThrow(); - - assertSame(first, second); + assertEquals(SDL, registry.getSdl("api-1").orElseThrow()); } @Test - void removeClearsCachedGraphQL() { - registry.register("api-1", SDL); - assertTrue(registry.getGraphQL("api-1").isPresent()); + void unknownApiIdIsAbsent() { + assertTrue(registry.getSdl("nope").isEmpty()); + } + @Test + void removeClearsTheEntry() { + registry.register("api-1", SDL); registry.remove("api-1"); - assertTrue(registry.getGraphQL("api-1").isEmpty()); - assertTrue(registry.getSchema("api-1").isEmpty()); + assertTrue(registry.getSdl("api-1").isEmpty()); } @Test - void reregisterReplacesCachedGraphQL() { + void reregisterReplacesTheStoredSdl() { registry.register("api-1", SDL); - GraphQL original = registry.getGraphQL("api-1").orElseThrow(); - registry.register("api-1", "type Query { bye: String }"); - GraphQL replaced = registry.getGraphQL("api-1").orElseThrow(); - assertNotSame(original, replaced); - assertSame(replaced, registry.getGraphQL("api-1").orElseThrow()); - } - - @Test - void awsAuthOnFieldDefinitionParses() { - var schema = new AppSyncSchemaParser(new AppSyncScalarRegistry()) - .parse("type Query { secret: String @aws_auth(cognito_groups: [\"Admins\"]) }"); - GraphQLFieldDefinition field = schema.getQueryType().getFieldDefinition("secret"); - GraphQLAppliedDirective directive = field.getAppliedDirective("aws_auth"); - assertNotNull(directive); + assertEquals("type Query { bye: String }", registry.getSdl("api-1").orElseThrow()); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthorizationDataFetcherTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthorizationDataFetcherTest.java deleted file mode 100644 index 6321cd85b6..0000000000 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthorizationDataFetcherTest.java +++ /dev/null @@ -1,265 +0,0 @@ -package io.github.hectorvent.floci.services.appsync.graphql.auth; - -import graphql.GraphQL; -import graphql.schema.DataFetcher; -import graphql.schema.FieldCoordinates; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import io.github.hectorvent.floci.services.appsync.graphql.AppSyncErrorFormatter; -import io.github.hectorvent.floci.services.appsync.graphql.AppSyncSchemaParser; -import io.github.hectorvent.floci.services.appsync.graphql.QueryExecutor; -import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; -import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; -import io.github.hectorvent.floci.services.appsync.model.AdditionalAuthenticationProvider; -import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; -import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class AuthorizationDataFetcherTest { - - private AppSyncSchemaParser parser; - private AuthFieldWrapper wrapper; - private QueryExecutor executor; - - @BeforeEach - void setUp() { - parser = new AppSyncSchemaParser(new AppSyncScalarRegistry()); - wrapper = new AuthFieldWrapper(null); - executor = new QueryExecutor(new AppSyncErrorFormatter()); - } - - @Test - void iamCallerOnApiKeyFieldReturnsUnauthorizedError() { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String @aws_api_key }")); - GraphqlApi api = api(AuthenticationType.AWS_IAM); - AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); - extra.setAuthenticationType(AuthenticationType.API_KEY); - api.setAdditionalAuthenticationProviders(List.of(extra)); - - Map response = execute(schema, "{ hello }", iamContext(api)); - - assertEquals(null, dataHello(response)); - @SuppressWarnings("unchecked") - Map error = ((List>) response.get("errors")).get(0); - assertEquals("Unauthorized", error.get("errorType")); - assertEquals("Not Authorized to access hello on type Query", error.get("message")); - assertEquals(List.of("hello"), error.get("path")); - assertNull(error.get("errorInfo")); - } - - @Test - void unmarkedFieldRequiresDefaultMode() { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String }")); - GraphqlApi api = api(AuthenticationType.API_KEY); - AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); - extra.setAuthenticationType(AuthenticationType.AWS_IAM); - api.setAdditionalAuthenticationProviders(List.of(extra)); - - Map response = execute(schema, "{ hello }", iamContext(api)); - assertEquals("Unauthorized", firstErrorType(response)); - } - - @Test - void orDirectivesAllowApiKey() { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String @aws_api_key @aws_iam }")); - GraphqlApi api = api(AuthenticationType.API_KEY); - AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); - extra.setAuthenticationType(AuthenticationType.AWS_IAM); - api.setAdditionalAuthenticationProviders(List.of(extra)); - - Map response = execute(schema, "{ hello }", apiKeyContext(api)); - assertNull(response.get("errors")); - assertTrue(((Map) response.get("data")).containsKey("hello")); - } - - @Test - void fieldOverridesType() { - GraphQLSchema schema = wrapper.wrap(parser.parse(""" - type Query @aws_api_key { - hello: String @aws_iam - } - """)); - GraphqlApi api = api(AuthenticationType.API_KEY); - AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); - extra.setAuthenticationType(AuthenticationType.AWS_IAM); - api.setAdditionalAuthenticationProviders(List.of(extra)); - - assertEquals("Unauthorized", firstErrorType(execute(schema, "{ hello }", apiKeyContext(api)))); - assertNull(execute(schema, "{ hello }", iamContext(api)).get("errors")); - } - - @Test - void typeLevelGrantsField() { - GraphQLSchema schema = wrapper.wrap(parser.parse(""" - type Query @aws_iam { - hello: String - } - """)); - GraphqlApi api = api(AuthenticationType.AWS_IAM); - Map response = execute(schema, "{ hello }", iamContext(api)); - assertNull(response.get("errors")); - } - - @Test - void awsAuthIgnoredWhenAdditionalModesExist() { - GraphQLSchema schema = wrapper.wrap(parser.parse( - "type Query { secret: String @aws_auth(cognito_groups: [\"admin\"]) }")); - GraphqlApi api = api(AuthenticationType.AMAZON_COGNITO_USER_POOLS); - AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); - extra.setAuthenticationType(AuthenticationType.API_KEY); - api.setAdditionalAuthenticationProviders(List.of(extra)); - Map identity = IdentityBuilder.cognito( - Map.of("sub", "s", "iss", "https://iss"), List.of(), "ALLOW"); - AppSyncAuthContext ctx = new AppSyncAuthContext( - identity, AppSyncAuth.AUTH_TYPE_COGNITO, AuthenticationType.AMAZON_COGNITO_USER_POOLS, - Set.of(), api, null, "us-east-1", "000000000000"); - Map response = execute(schema, "{ secret }", ctx); - assertNull(response.get("errors")); - } - - @Test - void awsAuthEnforcedWhenCognitoSole() { - GraphQLSchema schema = wrapper.wrap(parser.parse( - "type Query { secret: String @aws_auth(cognito_groups: [\"admin\"]) }")); - GraphqlApi api = api(AuthenticationType.AMAZON_COGNITO_USER_POOLS); - Map identity = IdentityBuilder.cognito( - Map.of("sub", "s", "iss", "https://iss", "cognito:groups", List.of("users")), List.of(), "ALLOW"); - AppSyncAuthContext ctx = new AppSyncAuthContext( - identity, AppSyncAuth.AUTH_TYPE_COGNITO, AuthenticationType.AMAZON_COGNITO_USER_POOLS, - Set.of(), api, null, "us-east-1", "000000000000"); - assertEquals("Unauthorized", firstErrorType(execute(schema, "{ secret }", ctx))); - } - - @Test - void deniedFieldsShortForm() { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String }")); - GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); - AppSyncAuthContext ctx = new AppSyncAuthContext( - IdentityBuilder.lambda(Map.of()), AppSyncAuth.AUTH_TYPE_LAMBDA, AuthenticationType.AWS_LAMBDA, - Set.of("Query.hello"), api, null, "us-east-1", "000000000000"); - Map response = execute(schema, "{ hello }", ctx); - assertNull(dataHello(response)); - assertEquals(List.of("hello"), firstErrorPath(response)); - } - - @Test - void deniedFieldsArnOtherApiDoesNotDeny() { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String }")); - GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); - String otherArn = IamAuthValidator.fieldArn("us-east-1", "000000000000", "other-api", "Query", "hello"); - AppSyncAuthContext ctx = new AppSyncAuthContext( - IdentityBuilder.lambda(Map.of()), AppSyncAuth.AUTH_TYPE_LAMBDA, AuthenticationType.AWS_LAMBDA, - Set.of(otherArn), api, null, "us-east-1", "000000000000"); - Map response = execute(schema, "{ hello }", ctx); - assertNull(response.get("errors")); - } - - @Test - void deniedFieldsArnThisApiDenies() { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String }")); - GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); - String arn = IamAuthValidator.fieldArn("us-east-1", "000000000000", "api-1", "Query", "hello"); - AppSyncAuthContext ctx = new AppSyncAuthContext( - IdentityBuilder.lambda(Map.of()), AppSyncAuth.AUTH_TYPE_LAMBDA, AuthenticationType.AWS_LAMBDA, - Set.of(arn), api, null, "us-east-1", "000000000000"); - assertEquals("Unauthorized", firstErrorType(execute(schema, "{ hello }", ctx))); - } - - @Test - void wrapperSurvivesInnerDelegateSwap() throws Exception { - GraphQLSchema schema = wrapper.wrap(parser.parse("type Query { hello: String @aws_iam }")); - GraphQLObjectType query = schema.getQueryType(); - GraphQLFieldDefinition field = query.getFieldDefinition("hello"); - DataFetcher fetcher = schema.getCodeRegistry().getDataFetcher( - FieldCoordinates.coordinates("Query", "hello"), field); - assertInstanceOf(AuthorizationDataFetcher.class, fetcher); - AuthorizationDataFetcher wrapperFetcher = (AuthorizationDataFetcher) fetcher; - AtomicBoolean innerRan = new AtomicBoolean(false); - wrapperFetcher.setDelegate(env -> { - innerRan.set(true); - return "secret"; - }); - - GraphqlApi api = api(AuthenticationType.API_KEY); - AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); - extra.setAuthenticationType(AuthenticationType.AWS_IAM); - api.setAdditionalAuthenticationProviders(List.of(extra)); - Map response = execute(schema, "{ hello }", apiKeyContext(api)); - assertEquals("Unauthorized", firstErrorType(response)); - assertTrue(!innerRan.get()); - } - - @Test - void registerWrapsUserFields() { - SchemaRegistry registry = new SchemaRegistry(parser, wrapper); - registry.register("api-1", "type Query { hello: String @aws_iam }"); - GraphQLSchema schema = registry.getSchema("api-1").orElseThrow(); - GraphQLFieldDefinition field = schema.getQueryType().getFieldDefinition("hello"); - DataFetcher fetcher = schema.getCodeRegistry().getDataFetcher( - FieldCoordinates.coordinates("Query", "hello"), field); - assertInstanceOf(AuthorizationDataFetcher.class, fetcher); - } - - private Map execute(GraphQLSchema schema, String query, AppSyncAuthContext ctx) { - Map graphqlContext = new HashMap<>(); - graphqlContext.put(AppSyncAuthContext.KEY, ctx); - if (ctx.identity() != null) { - graphqlContext.put("identity", ctx.identity()); - } - graphqlContext.put("authType", ctx.authType()); - graphqlContext.put("deniedFields", ctx.deniedFieldsList()); - GraphQL graphQL = SchemaRegistry.buildGraphQL(schema); - return executor.execute(graphQL, query, null, null, graphqlContext); - } - - private static GraphqlApi api(AuthenticationType type) { - GraphqlApi api = new GraphqlApi(); - api.setApiId("api-1"); - api.setAuthenticationType(type); - return api; - } - - private static AppSyncAuthContext iamContext(GraphqlApi api) { - return new AppSyncAuthContext( - IdentityBuilder.iam("000000000000", "test", "test", "arn:aws:iam::000000000000:root", List.of()), - AppSyncAuth.AUTH_TYPE_IAM, AuthenticationType.AWS_IAM, Set.of(), api, "test", - "us-east-1", "000000000000"); - } - - private static AppSyncAuthContext apiKeyContext(GraphqlApi api) { - return new AppSyncAuthContext( - null, AppSyncAuth.AUTH_TYPE_API_KEY, AuthenticationType.API_KEY, Set.of(), api, null, - "us-east-1", "000000000000"); - } - - private static Object dataHello(Map response) { - Object data = response.get("data"); - if (!(data instanceof Map map)) { - return null; - } - return map.get("hello"); - } - - @SuppressWarnings("unchecked") - private static String firstErrorType(Map response) { - return (String) ((List>) response.get("errors")).get(0).get("errorType"); - } - - @SuppressWarnings("unchecked") - private static Object firstErrorPath(Map response) { - return ((List>) response.get("errors")).get(0).get("path"); - } -} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/SidecarFieldAuthorizationPlannerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/SidecarFieldAuthorizationPlannerTest.java new file mode 100644 index 0000000000..2d87e842ec --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/SidecarFieldAuthorizationPlannerTest.java @@ -0,0 +1,209 @@ +package io.github.hectorvent.floci.services.appsync.graphql.auth; + +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.DenyField; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedDirective; +import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedField; +import io.github.hectorvent.floci.services.appsync.model.AdditionalAuthenticationProvider; +import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; +import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Same scenarios {@code AuthorizationDataFetcherTest} used to exercise against a live in-process + * {@code DataFetcher} wrapper, now against {@link SidecarFieldAuthorizationPlanner}'s decision + * logic directly: a hand-built {@link PlanResult} stands in for what {@code + * GraphqlSidecarClient#plan} would have returned (no live sidecar needed for this), and the + * assertion is whether {@code planDenyFields} redacts the field or not (issue #2917). The actual + * "null the field out" behavior these decisions drive is now the GraphQL sidecar's own generic + * {@code denyFields} handling, not something this class needs to re-verify. + */ +class SidecarFieldAuthorizationPlannerTest { + + private IamAuthValidator iamAuthValidator; + private SidecarFieldAuthorizationPlanner planner; + + @BeforeEach + void setUp() { + iamAuthValidator = mock(IamAuthValidator.class); + when(iamAuthValidator.isFieldDenied(anyString(), anyString())).thenReturn(false); + planner = new SidecarFieldAuthorizationPlanner(iamAuthValidator); + } + + @Test + void iamCallerOnApiKeyFieldIsDenied() { + PlanResult plan = plan(field("Query", "hello", List.of(directive("aws_api_key")), List.of())); + GraphqlApi api = api(AuthenticationType.AWS_IAM); + withAdditional(api, AuthenticationType.API_KEY); + + List denied = planner.planDenyFields(plan, iamContext(api)); + + assertEquals(1, denied.size()); + assertEquals("Query", denied.get(0).typeName()); + assertEquals("hello", denied.get(0).fieldName()); + assertEquals(AppSyncAuth.FIELD_UNAUTHORIZED_TYPE, denied.get(0).errorType()); + assertEquals("Not Authorized to access hello on type Query", denied.get(0).message()); + } + + @Test + void unmarkedFieldRequiresDefaultMode() { + PlanResult plan = plan(field("Query", "hello", List.of(), List.of())); + GraphqlApi api = api(AuthenticationType.API_KEY); + withAdditional(api, AuthenticationType.AWS_IAM); + + assertDenied(planner.planDenyFields(plan, iamContext(api))); + } + + @Test + void orDirectivesAllowApiKey() { + PlanResult plan = plan(field("Query", "hello", List.of(directive("aws_api_key"), directive("aws_iam")), List.of())); + GraphqlApi api = api(AuthenticationType.API_KEY); + withAdditional(api, AuthenticationType.AWS_IAM); + + assertAllowed(planner.planDenyFields(plan, apiKeyContext(api))); + } + + @Test + void fieldDirectivesOverrideType() { + PlanResult plan = plan(field("Query", "hello", List.of(directive("aws_iam")), List.of(directive("aws_api_key")))); + GraphqlApi api = api(AuthenticationType.API_KEY); + withAdditional(api, AuthenticationType.AWS_IAM); + + assertDenied(planner.planDenyFields(plan, apiKeyContext(api))); + assertAllowed(planner.planDenyFields(plan, iamContext(api))); + } + + @Test + void typeLevelGrantsFieldWithNoOwnDirectives() { + PlanResult plan = plan(field("Query", "hello", List.of(), List.of(directive("aws_iam")))); + GraphqlApi api = api(AuthenticationType.AWS_IAM); + + assertAllowed(planner.planDenyFields(plan, iamContext(api))); + } + + @Test + void awsAuthIgnoredWhenAdditionalModesExist() { + PlanResult plan = plan(field("Query", "secret", + List.of(directive("aws_auth", Map.of("cognito_groups", List.of("admin")))), List.of())); + GraphqlApi api = api(AuthenticationType.AMAZON_COGNITO_USER_POOLS); + withAdditional(api, AuthenticationType.API_KEY); + Map identity = IdentityBuilder.cognito(Map.of("sub", "s", "iss", "https://iss"), List.of(), "ALLOW"); + AppSyncAuthContext ctx = new AppSyncAuthContext(identity, AppSyncAuth.AUTH_TYPE_COGNITO, + AuthenticationType.AMAZON_COGNITO_USER_POOLS, Set.of(), api, null, "us-east-1", "000000000000"); + + assertAllowed(planner.planDenyFields(plan, ctx)); + } + + @Test + void awsAuthEnforcedWhenCognitoSole() { + PlanResult plan = plan(field("Query", "secret", + List.of(directive("aws_auth", Map.of("cognito_groups", List.of("admin")))), List.of())); + GraphqlApi api = api(AuthenticationType.AMAZON_COGNITO_USER_POOLS); + Map identity = IdentityBuilder.cognito( + Map.of("sub", "s", "iss", "https://iss", "cognito:groups", List.of("users")), List.of(), "ALLOW"); + AppSyncAuthContext ctx = new AppSyncAuthContext(identity, AppSyncAuth.AUTH_TYPE_COGNITO, + AuthenticationType.AMAZON_COGNITO_USER_POOLS, Set.of(), api, null, "us-east-1", "000000000000"); + + assertDenied(planner.planDenyFields(plan, ctx)); + } + + @Test + void deniedFieldsShortFormDenies() { + PlanResult plan = plan(field("Query", "hello", List.of(), List.of())); + GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); + AppSyncAuthContext ctx = new AppSyncAuthContext(IdentityBuilder.lambda(Map.of()), AppSyncAuth.AUTH_TYPE_LAMBDA, + AuthenticationType.AWS_LAMBDA, Set.of("Query.hello"), api, null, "us-east-1", "000000000000"); + + assertDenied(planner.planDenyFields(plan, ctx)); + } + + @Test + void deniedFieldsArnForOtherApiDoesNotDeny() { + PlanResult plan = plan(field("Query", "hello", List.of(), List.of())); + GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); + String otherArn = IamAuthValidator.fieldArn("us-east-1", "000000000000", "other-api", "Query", "hello"); + AppSyncAuthContext ctx = new AppSyncAuthContext(IdentityBuilder.lambda(Map.of()), AppSyncAuth.AUTH_TYPE_LAMBDA, + AuthenticationType.AWS_LAMBDA, Set.of(otherArn), api, null, "us-east-1", "000000000000"); + + assertAllowed(planner.planDenyFields(plan, ctx)); + } + + @Test + void deniedFieldsArnForThisApiDenies() { + PlanResult plan = plan(field("Query", "hello", List.of(), List.of())); + GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); + String arn = IamAuthValidator.fieldArn("us-east-1", "000000000000", "api-1", "Query", "hello"); + AppSyncAuthContext ctx = new AppSyncAuthContext(IdentityBuilder.lambda(Map.of()), AppSyncAuth.AUTH_TYPE_LAMBDA, + AuthenticationType.AWS_LAMBDA, Set.of(arn), api, null, "us-east-1", "000000000000"); + + assertDenied(planner.planDenyFields(plan, ctx)); + } + + @Test + void noAuthContextAllowsEverything() { + PlanResult plan = plan(field("Query", "hello", List.of(), List.of())); + assertTrue(planner.planDenyFields(plan, null).isEmpty()); + } + + private static PlanResult plan(PlannedField field) { + return new PlanResult("QUERY", List.of(field)); + } + + private static void assertDenied(List denied) { + assertEquals(1, denied.size()); + } + + private static void assertAllowed(List denied) { + assertTrue(denied.isEmpty()); + } + + private static PlannedField field(String typeName, String fieldName, List directives, + List typeDirectives) { + return new PlannedField(typeName, fieldName, directives, typeDirectives); + } + + private static PlannedDirective directive(String name) { + return new PlannedDirective(name, Map.of()); + } + + private static PlannedDirective directive(String name, Map args) { + return new PlannedDirective(name, args); + } + + private static GraphqlApi api(AuthenticationType type) { + GraphqlApi api = new GraphqlApi(); + api.setApiId("api-1"); + api.setAuthenticationType(type); + return api; + } + + private static void withAdditional(GraphqlApi api, AuthenticationType type) { + AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider(); + extra.setAuthenticationType(type); + api.setAdditionalAuthenticationProviders(List.of(extra)); + } + + private static AppSyncAuthContext iamContext(GraphqlApi api) { + return new AppSyncAuthContext( + IdentityBuilder.iam("000000000000", "test", "test", "arn:aws:iam::000000000000:root", List.of()), + AppSyncAuth.AUTH_TYPE_IAM, AuthenticationType.AWS_IAM, Set.of(), api, "test", + "us-east-1", "000000000000"); + } + + private static AppSyncAuthContext apiKeyContext(GraphqlApi api) { + return new AppSyncAuthContext( + null, AppSyncAuth.AUTH_TYPE_API_KEY, AuthenticationType.API_KEY, Set.of(), api, null, + "us-east-1", "000000000000"); + } +} 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 deleted file mode 100644 index 4d8f70c2d8..0000000000 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarsTest.java +++ /dev/null @@ -1,152 +0,0 @@ -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)); - } -} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java index 15c839e071..2d49f1fa32 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java @@ -1,9 +1,12 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.services.appsync.AppSyncGraphqlSidecarProfile; import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.Map; @@ -29,10 +32,20 @@ import static org.junit.jupiter.api.Assertions.fail; * built on, {@code GraphQlApi.ApiId} and {@code FunctionConfiguration.FunctionId}: an unset * attribute resolves to the literal string {@code "LogicalId.Attr"} and every dependent resource * would then be wired to that text instead of an id. + * + *

Runs against the real GraphQL sidecar image, started by {@code GraphqlSidecarManager}: the + * schema deploy above needs it, and the shared profile namespaces the container so a local run + * never touches a developer's own running sidecar, and skips (rather than fails) without Docker. */ @QuarkusTest +@TestProfile(AppSyncGraphqlSidecarProfile.class) class AppSyncCfnIntegrationTest { + @BeforeAll + static void requireDockerAndTheSidecarImage() { + AppSyncGraphqlSidecarProfile.requireDockerAndTheSidecarImage(); + } + private static final String CFN_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request"; private static final String APPSYNC_AUTH =