fix(appsync): move the GraphQL engine to a sidecar, out of the native image (#3534)

graphql-java (~3.8MB with transitive deps) was an unconditional dependency,
so it and its schema/execution/parser classes were reachable in every
native image regardless of whether AppSync was ever used (issue #2917),
the same systemic pattern already fixed for Kubernetes (#2914) and Kafka
(#2916).

Schema parsing and query execution now run in floci/floci-sidecar-graphql,
published from floci-io/floci-sidecars, the same model #3799 already moved
Cedar onto: GraphqlSidecarManager lazily starts the pinned image and checks
the contract version it reports on /health, refusing a sidecar speaking
another contract major with a message naming the image and the variable to
change. GraphqlSidecarClient talks to it over plain HTTP. graphql-java is
no longer a dependency of this repository at all, not even test-scoped:
its schema/execution/parser classes, the query planner, and the 17 AWS
scalar coercions now live entirely in the sidecar's own repository.

The sidecar itself carries zero AppSync-specific knowledge, and zero AWS
vocabulary: its scalars are generic named coercion kinds a caller maps its
own scalar names onto, so SidecarSchemaCompiler now sends a scalars mapping
(AWSDateTime -> date-time, and so on for all 17) alongside every SDL, or
AWS scalar validation would silently degrade to pass-through coercion. It
exposes three endpoints: schema validate/compile, a query planner that
lists every (typeName, fieldName) coordinate a query would visit plus the
directives on each (with zero interpretation of what they mean), and
execute, which accepts an opaque denyFields list and nulls those
coordinates out with the caller-supplied error. All @aws_auth/IAM/
Cognito/Lambda-authorizer interpretation stays in Floci
(SidecarFieldAuthorizationPlanner, AppSyncAuthRequirements), computed from
the planner's output before /v1/execute is ever called, so a query the
planner can't fully analyze fails closed (refuses the request) instead of
silently running unauthorized. SidecarSchemaCompiler replaces
AppSyncSchemaParser: it still injects AppSync's directive declarations and
the 17 scalar type declarations into the customer's SDL (pure string work)
before handing the SDL to the sidecar.

While the scalar coercion logic was still being ported to the sidecar's
repository, testing surfaced a real bug: every scalar's parseLiteral()
delegated to parseValue(), which throws CoercingParseValueException;
graphql-java's literal validator only catches CoercingParseLiteralException,
so an invalid literal argument (as opposed to an invalid variable) escaped
as an unhandled exception instead of a spec-correct GraphQL
ValidationError. Fixed in the sidecar before it was ever published.

QueryRegistry, QueryExecutor, AuthFieldWrapper, AuthorizationDataFetcher's
live DataFetcher wrapper, and AppSyncFieldUnauthorizedException are
deleted: their in-process execution role no longer exists. The directive
interpretation half of AuthorizationDataFetcher survives as
AppSyncAuthRequirements, now taking generic data instead of live
graphql-java objects, shared rather than duplicated.

Verified end to end against the published image: pulled
floci/floci-sidecar-graphql:0.2.0 fresh and ran the full AppSync suite
(190 integration tests across schema lifecycle, auth, and execution)
through the real GraphqlSidecarManager, including the sidecar starting
and stopping as a real sibling container over the mounted Docker socket.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-18 07:57:15 -05:00
1 parent 6f87973649
commit 918a09f54a
37 files changed
+1739 -1868

No files matched your search

@@ -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<String> graphqlUrl();
@WithDefault("floci/floci-sidecar-graphql:0.2.0")
String graphqlImage();
}
interface OamServiceConfig {
@@ -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.
*
* <p>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<SchemaIssue> issues;
public SchemaValidationException(String message, List<SchemaIssue> issues) {
super(400, "BadRequestException", message);
this.issues = issues;
}
public List<SchemaIssue> issues() {
return issues;
}
}
/** Validates/compiles an SDL document. Throws {@link SchemaValidationException} if the schema is invalid. */
public void validateSchema(String sdl, Map<String, String> 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<SchemaIssue> issuesFrom(JsonNode array) {
List<SchemaIssue> 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<PlannedDirective> directives,
List<PlannedDirective> 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<PlannedField> 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<String, String> 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<PlannedField> 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<PlannedDirective> directivesFrom(JsonNode array) {
List<PlannedDirective> 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<String, Object> execute(String sdl, Map<String, String> scalars, String query,
Map<String, Object> variables, String operationName,
List<DenyField> 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<String> 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;
}
}
@@ -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).
*
* <p>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<String> 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<String> 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;
}
}
@@ -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 <a href="https://docs.aws.amazon.com/appsync/latest/devguide/built-in-util-js.html">AppSync DG {@code $util.error} ({@code errorType}/{@code errorInfo})</a>
* @see <a href="https://github.com/graphql/graphql-over-http/issues/81">AppSync HTTP behavior (AppSync team / @robzhu)</a>
@@ -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<String, Object> format(ExecutionResult result) {
/** {@code sidecarResult} is exactly what {@link io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient#execute} returned. */
@SuppressWarnings("unchecked")
public Map<String, Object> format(Map<String, Object> sidecarResult) {
Map<String, Object> response = new LinkedHashMap<>();
if (result.isDataPresent()) {
response.put("data", result.getData());
if (sidecarResult.containsKey("data")) {
response.put("data", sidecarResult.get("data"));
}
List<GraphQLError> errors = result.getErrors();
if (errors != null && !errors.isEmpty()) {
List<Map<String, Object>> 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<Map<String, Object>> formatted = new ArrayList<>(list.size());
for (Object error : list) {
if (error instanceof Map<?, ?> map) {
formatted.add(formatError((Map<String, Object>) map));
}
}
response.put("errors", formatted);
}
@@ -56,48 +57,36 @@ public class AppSyncErrorFormatter {
return response;
}
private Map<String, Object> formatError(GraphQLError error) {
@SuppressWarnings("unchecked")
private Map<String, Object> formatError(Map<String, Object> error) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("message", error.getMessage());
List<SourceLocation> locations = error.getLocations();
if (locations != null && !locations.isEmpty()) {
List<Map<String, Object>> locationMaps = new ArrayList<>(locations.size());
for (SourceLocation location : locations) {
Map<String, Object> 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<Object> 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;
}
}
@@ -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<String> sdlOpt = schemaRegistry.getSdl(apiId);
if (sdlOpt.isEmpty()) {
return graphqlError(502, "GraphQLSchemaException",
AppSyncErrorFormatter.MSG_NO_SCHEMA);
}
try {
Map<String, Object> 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<String, String> 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<DenyField> denyFields = fieldAuthorizationPlanner.planDenyFields(plan, authContext);
Map<String, Object> 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<Object, Object> graphQlContext(AppSyncAuthContext authContext) {
Map<Object, Object> 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<String, Object> operationNotSupported() {
Map<String, Object> 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) {
@@ -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<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> toCodeErrorFromGraphQL(String errorType, GraphQLError ge) {
List<SourceLocation> 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<String, Object> toCodeError(String errorType, String value, int line, int column) {
Map<String, Object> codeError = new LinkedHashMap<>();
codeError.put("errorType", errorType);
codeError.put("value", value);
Map<String, Object> location = new LinkedHashMap<>();
location.put("line", line);
location.put("column", column);
location.put("span", -1);
codeError.put("location", location);
return codeError;
}
private Map<String, Object> buildExtendedData(List<Map<String, Object>> codeErrors) {
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("codeErrors", codeErrors);
Map<String, Object> 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();
}
}
@@ -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<String, Object> execute(GraphQLSchema schema, String query,
Map<String, Object> variables, String operationName) {
return execute(SchemaRegistry.buildGraphQL(schema), query, variables, operationName, Map.of());
}
public Map<String, Object> execute(GraphQL graphQL, String query,
Map<String, Object> variables, String operationName) {
return execute(graphQL, query, variables, operationName, Map.of());
}
public Map<String, Object> execute(GraphQL graphQL, String query,
Map<String, Object> variables, String operationName,
Map<Object, Object> graphQLContext) {
List<OperationDefinition> 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<OperationDefinition> parseOperations(String query) {
try {
Document document = Parser.parse(query);
List<OperationDefinition> 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<OperationDefinition> 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;
}
}
@@ -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<SchemaCreationStatus> schemaStatusStore;
private final AccountAwareStorageBackend<String> schemaStore;
private final EmulatorConfig config;
@@ -39,11 +40,13 @@ public class SchemaCreationWorker {
@Inject
public SchemaCreationWorker(SchemaRegistry schemaRegistry,
SidecarSchemaCompiler schemaCompiler,
AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore,
AccountAwareStorageBackend<String> 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.
*
* <p>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<String, String> 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);
}
}
}
@@ -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).
*
* <p>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<String, GraphQLSchema> schemas = new ConcurrentHashMap<>();
private final Map<String, GraphQL> 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<String, String> 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<GraphQLSchema> getSchema(String apiId) {
return Optional.ofNullable(schemas.get(apiId));
}
public Optional<GraphQL> getGraphQL(String apiId) {
return Optional.ofNullable(engines.get(apiId));
public Optional<String> 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);
}
}
@@ -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<String> 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<String, String> 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<String, String> 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<Map<String, Object>> 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<String, Object> toCodeError(String errorType, String value, int line, int column) {
Map<String, Object> codeError = new LinkedHashMap<>();
codeError.put("errorType", errorType);
codeError.put("value", value);
Map<String, Object> location = new LinkedHashMap<>();
location.put("line", line);
location.put("column", column);
location.put("span", -1);
codeError.put("location", location);
return codeError;
}
private Map<String, Object> buildExtendedData(List<Map<String, Object>> codeErrors) {
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("codeErrors", codeErrors);
Map<String, Object> extendedData = new LinkedHashMap<>();
extendedData.put("reason", "CODE_ERROR");
extendedData.put("detail", detail);
return extendedData;
}
}
@@ -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<String> groups) {
}
/** A directive application reduced to just what {@link #requirementsFrom} needs. */
record DirectiveUse(String name, List<String> cognitoGroups) {
}
static List<AuthRequirement> requirementsFrom(List<DirectiveUse> directives, GraphqlApi api) {
List<AuthRequirement> 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;
}
}
@@ -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<Object> path;
public AppSyncFieldUnauthorizedException(List<Object> 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<Object> getPath() {
return path;
}
@Override
public List<SourceLocation> getLocations() {
return null;
}
@Override
public ErrorClassification getErrorType() {
return new ErrorClassification() {
@Override
public String toString() {
return AppSyncAuth.FIELD_UNAUTHORIZED_TYPE;
}
};
}
@Override
public Map<String, Object> 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);
}
}
@@ -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));
}
}
@@ -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<Object> {
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<String> 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<AuthRequirement> 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<AuthRequirement> effectiveRequirements(DataFetchingEnvironment environment, GraphqlApi api) {
GraphQLFieldDefinition field = environment.getFieldDefinition();
GraphQLObjectType parent = parentObjectType(environment);
List<AuthRequirement> 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<AuthRequirement> requirementsFrom(List<GraphQLAppliedDirective> directives, GraphqlApi api) {
List<AuthRequirement> 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<String> 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<String> 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<String> groups) {
}
}
@@ -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<DenyField> planDenyFields(PlanResult plan, AppSyncAuthContext auth) {
if (auth == null || auth.graphqlApi() == null) {
return List.of();
}
List<DenyField> 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<String> 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<AppSyncAuthRequirements.AuthRequirement> 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<AppSyncAuthRequirements.DirectiveUse> toDirectiveUse(List<PlannedDirective> directives) {
List<AppSyncAuthRequirements.DirectiveUse> uses = new ArrayList<>();
for (PlannedDirective directive : directives) {
List<String> 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;
}
}
@@ -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<GraphQLScalarType> scalars;
private final Map<String, GraphQLScalarType> 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<GraphQLScalarType> allScalars() {
return scalars;
}
public Optional<GraphQLScalarType> getScalar(String name) {
return Optional.ofNullable(scalarMap.get(name));
}
public Map<String, GraphQLScalarType> scalarMap() {
return scalarMap;
}
}
@@ -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<String, String>() {
@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<String, String>() {
@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<String, String>() {
@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<String, String>() {
@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<Long, Long>() {
@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<String, String>() {
@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<String, String>() {
@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<String, String>() {
@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<String, String>() {
@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<Boolean, Boolean>() {
@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<Long, Long>() {
@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<Integer, Integer>() {
@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<Integer, Integer>() {
@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<Double, Double>() {
@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<String, String>() {
@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<String, String>() {
@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<String, String>() {
@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() {}
}