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

@@ -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();
}
@@ -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)
@@ -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.
*
* <p>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<String, String> 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;
}
}
}
@@ -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();
}
@@ -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<String> lastPath = new AtomicReference<>();
private final AtomicReference<JsonNode> 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<String, Object> 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);
}
}
}
@@ -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);
}
}
@@ -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<String, Object> sidecarResult = Map.of(
"errors", List.of(sidecarError("Invalid syntax near '{'", List.of(Map.of("line", 1, "column", 1)),
null, "InvalidSyntax")));
Map<String, Object> response = formatter.format(result);
Map<String, Object> 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<String, Object> data = new LinkedHashMap<>();
data.put("nope", null);
Map<String, Object> 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<String, Object> response = formatter.format(result);
Map<String, Object> response = formatter.format(sidecarResult);
@SuppressWarnings("unchecked")
List<Map<String, Object>> errors = (List<Map<String, Object>>) response.get("errors");
@@ -90,26 +80,18 @@ class AppSyncErrorFormatterTest {
Map<String, Object> forBraces = formatter.transportError(
"MalformedHttpRequestException",
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
Map<String, Object> 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<String, Object> data = new java.util.LinkedHashMap<>();
Map<String, Object> data = new LinkedHashMap<>();
data.put("hello", null);
ExecutionResult result = ExecutionResultImpl.newExecutionResult()
.data(data)
.build();
Map<String, Object> sidecarResult = Map.of("data", data);
Map<String, Object> response = formatter.format(result);
Map<String, Object> response = formatter.format(sidecarResult);
@SuppressWarnings("unchecked")
Map<String, Object> responseData = (Map<String, Object>) response.get("data");
@@ -120,15 +102,14 @@ class AppSyncErrorFormatterTest {
@Test
void unauthorizedClassificationMapsToUnauthorized() {
GraphQLError error = new AppSyncFieldUnauthorizedException(List.of("hello"), "hello", "Query");
Map<String, Object> data = new java.util.LinkedHashMap<>();
Map<String, Object> data = new LinkedHashMap<>();
data.put("hello", null);
ExecutionResult result = ExecutionResultImpl.newExecutionResult()
.data(data)
.addError(error)
.build();
Map<String, Object> sidecarResult = Map.of(
"data", data,
"errors", List.of(sidecarError("Not Authorized to access hello on type Query",
null, List.of("hello"), "Unauthorized")));
Map<String, Object> response = formatter.format(result);
Map<String, Object> response = formatter.format(sidecarResult);
@SuppressWarnings("unchecked")
List<Map<String, Object>> errors = (List<Map<String, Object>>) 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<String, Object> sidecarError(String message, List<Map<String, Object>> locations,
List<String> path, String classification) {
Map<String, Object> 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;
}
}
@@ -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);
@@ -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<String, Object> response = executor.execute(helloSchema, "{ hello }", null, null);
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) response.get("data");
assertTrue(data.containsKey("hello"));
assertNull(data.get("hello"));
assertTrue(!response.containsKey("errors") || ((List<?>) response.get("errors")).isEmpty());
}
@Test
void usesAsyncStrategiesAndSupportsSimpleQuery() {
Map<String, Object> response = executor.execute(helloSchema, "query Q { hello }", Map.of(), "Q");
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) response.get("data");
assertNull(data.get("hello"));
}
@Test
void httpSubscriptionReturnsOperationNotSupported() {
Map<String, Object> response = executor.execute(
subscriptionSchema,
"subscription { onHello }",
null,
null);
assertTrue(response.containsKey("errors"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> errors = (List<Map<String, Object>>) 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<String, Object> response = executor.execute(multiOpSchema, """
query A { hello }
query B { bye }
""", null, "B");
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) response.get("data");
assertTrue(data.containsKey("bye"));
assertNull(data.get("bye"));
}
@Test
void syntaxErrorFormattedAsSyntaxError() {
Map<String, Object> response = executor.execute(helloSchema, "{ hello", null, null);
@SuppressWarnings("unchecked")
List<Map<String, Object>> errors = (List<Map<String, Object>>) response.get("errors");
assertEquals("SyntaxError", errors.get(0).get("errorType"));
}
@Test
void executePassesGraphQlContextKeys() {
DataFetcher<Object> 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<Object, Object> ctx = Map.of(
"identity", Map.of("sourceIp", List.of("127.0.0.1")),
"authType", "IAM Authorization",
"deniedFields", List.of());
Map<String, Object> response = executor.execute(
SchemaRegistry.buildGraphQL(schema), "{ hello }", null, null, ctx);
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) response.get("data");
assertEquals("IAM Authorization", data.get("hello"));
}
}
@@ -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<SchemaCreationStatus> 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());
}
}
@@ -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());
}
}
@@ -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<String, Object> response = execute(schema, "{ hello }", iamContext(api));
assertEquals(null, dataHello(response));
@SuppressWarnings("unchecked")
Map<String, Object> error = ((List<Map<String, Object>>) 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> execute(GraphQLSchema schema, String query, AppSyncAuthContext ctx) {
Map<Object, Object> 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<String, Object> response) {
Object data = response.get("data");
if (!(data instanceof Map<?, ?> map)) {
return null;
}
return map.get("hello");
}
@SuppressWarnings("unchecked")
private static String firstErrorType(Map<String, Object> response) {
return (String) ((List<Map<String, Object>>) response.get("errors")).get(0).get("errorType");
}
@SuppressWarnings("unchecked")
private static Object firstErrorPath(Map<String, Object> response) {
return ((List<Map<String, Object>>) response.get("errors")).get(0).get("path");
}
}
@@ -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<DenyField> 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<String, Object> 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<String, Object> 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<DenyField> denied) {
assertEquals(1, denied.size());
}
private static void assertAllowed(List<DenyField> denied) {
assertTrue(denied.isEmpty());
}
private static PlannedField field(String typeName, String fieldName, List<PlannedDirective> directives,
List<PlannedDirective> 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<String, Object> 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");
}
}
@@ -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<GraphQLScalarType> 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));
}
}
@@ -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.
*
* <p>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 =