feat(appsync): Phase 7 — GraphQL execute authentication (#2380)

* feat(appsync): register GraphQL execute controller in the service catalog

Unsigned POST /v1/apis/{apiId}/graphql was not a registered AppSync resource, so the data-plane path could be claimed by other catch-all routes.

* feat(appsync): default API key expiry and reject duplicate auth providers

CreateApiKey now expires in seven days when omitted, caps expiry at 365 days, and looks keys up by value. Create/UpdateGraphqlApi reject duplicate API_KEY, IAM, and Lambda providers.

* feat(appsync): authenticate GraphQL execute requests

Classify credentials by header shape and require a configured provider before GraphQL runs. Request failures return HTTP 401 UnauthorizedException on the data-plane envelope.

* feat(appsync): enforce SDL field authorization on GraphQL execute

Wrap registered fields with AuthorizationDataFetcher so directive mismatch, Cognito groups, IAM field DENY, and Lambda deniedFields stay HTTP 200 with null data and errors[].

* test(appsync): execute GraphQL over HTTP with an SDK-created API key

Cover data-plane success with x-api-key and 401 without credentials after management CreateGraphqlApi/CreateApiKey.

* fix(appsync): match missing-header 401 text and SigV4 precedence

AWS returns Missing authorization header when credentials are absent, evaluates auth before schema, and routes SigV4 Authorization ahead of x-api-key without falling back to the API key.

* fix(appsync): emit field-level Unauthorized GraphQL errors

AWS AppSync returns HTTP 200 with errorType Unauthorized and
Not Authorized to access {field} on type {type}, not UnauthorizedException.

* fix(appsync): omit sourceIp from OIDC identity

Official AppSync OIDC identity is only sub, issuer, and claims.

* fix(appsync): round API key expiry down to the hour

CreateApiKey and UpdateApiKey store expires as epoch seconds rounded
down to the nearest hour, matching the AWS API Reference.

* fix(appsync): match duplicate auth provider BadRequestException text

AWS names the 1-based additional provider index and the repeated type.

* fix(appsync): reject API key expiry outside 1-365 days

CreateApiKey and UpdateApiKey now raise ApiKeyValidityOutOfBoundsException
when expires is not between 1 and 365 days from now.

* fix(appsync): set ApiKey deletes to expires plus 60 days

AWS keeps expired da2 keys for 60 days and returns deletes as epoch
seconds rounded down to the hour.
This commit is contained in:
AgustinBertagna authored and GitHub committed 2026-08-19 11:46:11 -04:00
1 parent 74da157681
commit 3f12428d97
46 files changed
+3564 -64

No files matched your search

@@ -117,10 +117,11 @@ class AppSyncTest {
// ── API Keys ────────────────────────────────────────────────────────
private static String keyId;
private static String apiKeyValue;
@Test
@Order(20)
void createApiKey() {
void createApiKey() throws Exception {
long expiresEpoch = Instant.parse("2027-01-01T00:00:00Z").getEpochSecond();
CreateApiKeyResponse resp = client.createApiKey(CreateApiKeyRequest.builder()
.apiId(apiId)
@@ -132,6 +133,9 @@ class AppSyncTest {
keyId = resp.apiKey().id();
assertThat(keyId).isNotBlank();
assertThat(resp.apiKey().description()).isEqualTo("sdk-test-key");
// AWS SDK v2 ApiKey has no apiKey() accessor; Floci returns the da2- secret on the wire.
apiKeyValue = fetchApiKeyValue(apiId, keyId);
assertThat(apiKeyValue).startsWith("da2-");
}
@Test
@@ -173,6 +177,50 @@ class AppSyncTest {
assertThat(resp).isNotNull();
}
@Test
@Order(24)
void httpExecuteWithApiKeyReturns200() throws Exception {
String url = TestFixtures.endpoint() + "/v1/apis/" + apiId + "/graphql";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("x-api-key", apiKeyValue)
.POST(HttpRequest.BodyPublishers.ofString("{\"query\":\"{ hello }\"}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
assertThat(resp.statusCode()).isEqualTo(200);
@SuppressWarnings("unchecked")
Map<String, Object> body = mapper.readValue(resp.body(), Map.class);
assertThat(body).containsKey("data");
assertThat(body.get("errors")).isNull();
}
@Test
@Order(25)
void httpExecuteWithoutApiKeyReturns401() throws Exception {
String url = TestFixtures.endpoint() + "/v1/apis/" + apiId + "/graphql";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"query\":\"{ hello }\"}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
assertThat(resp.statusCode()).isEqualTo(401);
assertThat(resp.headers().firstValue("x-amzn-errortype").orElse(""))
.contains("UnauthorizedException");
@SuppressWarnings("unchecked")
Map<String, Object> body = mapper.readValue(resp.body(), Map.class);
@SuppressWarnings("unchecked")
List<Map<String, Object>> errors = (List<Map<String, Object>>) body.get("errors");
assertThat(errors).isNotEmpty();
assertThat(errors.get(0).get("errorType")).isEqualTo("UnauthorizedException");
assertThat(errors.get(0).get("message")).isEqualTo("Missing authorization header");
assertThat(body.get("data")).isNull();
assertThat(body.get("__type")).isNull();
}
// ── Data Sources ────────────────────────────────────────────────────
@Test
@@ -1265,4 +1313,24 @@ class AppSyncTest {
assertThat(location.get("column")).isNotNull();
assertThat(location.get("span")).isEqualTo(-1);
}
@SuppressWarnings("unchecked")
private static String fetchApiKeyValue(String apiId, String keyId) throws Exception {
String url = TestFixtures.endpoint() + "/v1/apis/" + apiId + "/apikeys";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request")
.GET()
.build();
HttpResponse<String> resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
Map<String, Object> body = mapper.readValue(resp.body(), Map.class);
List<Map<String, Object>> keys = (List<Map<String, Object>>) body.get("apiKeys");
assertThat(keys).isNotEmpty();
for (Map<String, Object> key : keys) {
if (keyId.equals(key.get("id"))) {
return String.valueOf(key.get("apiKey"));
}
}
throw new IllegalStateException("API key not listed for id " + keyId);
}
}
+32 -4
View File
@@ -169,7 +169,7 @@ The following **AppSync directives** are pre-defined and recognized in schemas:
| `@aws_oidc` | OBJECT, FIELD_DEFINITION | Require OIDC auth |
| `@aws_lambda` | OBJECT, FIELD_DEFINITION | Require Lambda auth |
| `@aws_subscribe(mutations: [String!]!)` | FIELD_DEFINITION | Link subscription to mutation |
| `@aws_auth(cognito_groups: [String!]!)` | OBJECT | Require Cognito groups |
| `@aws_auth(cognito_groups: [String!]!)` | OBJECT, FIELD_DEFINITION | Require Cognito groups (ignored when additional auth modes exist) |
| `@aws_delta_sync` | OBJECT | Delta sync configuration |
Unknown directives are rejected during schema registration.
@@ -195,10 +195,38 @@ Responses are `application/json` with AWS AppSync wire shapes (`data` / `errors[
| Unknown `apiId` | 404 | `NotFoundException` |
| API exists but no executable schema (incl. PROCESSING) | **502** | `GraphQLSchemaException` — `No schema definition exists.` + `x-amzn-errortype` |
| Unexpected failure | 500 | `InternalFailure` |
| Missing/invalid/expired credentials, unconfigured mode, Lambda deny | **401** | `UnauthorizedException` — GraphQL does not run; `x-amzn-errortype` is set. Missing headers use message `Missing authorization header`. |
| Field directive mismatch, Cognito group miss, Lambda `deniedFields`, IAM field DENY | **200** | Field is `null` and `errors[]` contains `Unauthorized` — `Not Authorized to access {field} on type {type}` (no `x-amzn-errortype`) |
**Evidence for data-plane statuses** (empty/`[]`/`{}` → 400; missing schema → 502): AppSync team sample in [graphql/graphql-over-http#81](https://github.com/graphql/graphql-over-http/issues/81) (@robzhu). The management API Reference lists `GraphQLSchemaException` as HTTP 400 for “schema not valid” on management operations — a different surface than the GraphQL execute data plane.
Auth on the execute endpoint, DataFetcher/resolver dispatch, data-source adapters, guardrails, and WebSocket subscriptions are later phases.
### Execute authentication
Request auth runs after Content-Type and body parse and after API lookup (unknown `apiId` is still 404). It runs before schema lookup, so a missing schema with no credentials is 401, not 502.
Headers are classified by **shape** (not primary-then-fallback). If both `x-api-key` and SigV4 `Authorization` are present, **SigV4 wins**. AppSync does not fall back to the API key when IAM validation fails.
Missing required auth headers return HTTP **401** `UnauthorizedException` with message `Missing authorization header`. Invalid or expired credentials that are present still return 401 with `You are not authorized to make this call.`
| Header shape | Mode |
|---|---|
| `Authorization` starts with `AWS4-HMAC-SHA256` | `AWS_IAM` (wins over `x-api-key` if both are present) |
| `x-api-key` present | `API_KEY` |
| `Authorization: Bearer <jwt>` | Cognito and/or OIDC (matched by `iss` / `aud` or `azp`) |
| Other `Authorization` | `AWS_LAMBDA` |
Configured modes are the API default `authenticationType` plus `additionalAuthenticationProviders`. A classified mode that is not configured returns 401.
| Mode | Emulator notes |
|---|---|
| API_KEY | Lookup by key value (`da2-…`). Identity is absent (not `{}`). Default key expiry is 7 days when `expires` is omitted; stored `expires` is rounded down to the nearest hour. Create/UpdateApiKey require `expires` between 1 and 365 days from now (`ApiKeyValidityOutOfBoundsException`, 400). `deletes` is `expires` plus 60 days. |
| AWS_IAM | Parses `Credential=` access key; no HMAC. Known keys evaluate `appsync:GraphQL`. Unknown/`test` keys are emulator ALLOW. |
| Cognito / OIDC | JWT payload decode only (no JWKS). OIDC as the sole mode skips the `iss` check. OIDC identity is `{sub, issuer, claims}` (no `sourceIp`). |
| Lambda | AppSync `isAuthorized` contract via `LambdaService.invoke` (not an API Gateway policy document). |
SDL field auth: unmarked fields require the API **default** mode. Additional modes unlock fields tagged `@aws_api_key` / `@aws_iam` / `@aws_oidc` / `@aws_cognito_user_pools` / `@aws_lambda`. Multiple directives on a field are OR. Field-level directives override type-level. `@aws_auth` is allowed on `OBJECT \| FIELD_DEFINITION` and is ignored when additional modes exist.
Duplicate `API_KEY` / `AWS_IAM` / `AWS_LAMBDA` (and the same Cognito pool or OIDC issuer) between default and additional providers is rejected on create/update with management 400 `BadRequestException`: `Authentication type {TYPE} for additional authentication provider {N} already specified on the API. It can only be specified once.` (`N` is 1-based in `additionalAuthenticationProviders`).
## Pagination
@@ -243,7 +271,6 @@ This matches AWS behavior where deleting an API removes its entire configuration
These AWS AppSync capabilities are not yet implemented and are tracked in future phases:
- **Authentication on execute** (Phase 7): API key / IAM / Cognito validation on the GraphQL endpoint
- **DataFetcher / resolver dispatch** (Phase 8): resolver mapping templates and field resolution with non-null values
- **Data source adapters** (Phase 9): DynamoDB, Lambda, HTTP, EventBridge, OpenSearch, RDS connectors
- **Guardrails** (Phase 10): query depth / complexity limits and related errors
@@ -312,9 +339,10 @@ aws appsync associate-api \
--api-id API_ID \
--endpoint-url $AWS_ENDPOINT_URL
# Execute a GraphQL query (data-plane; null fields OK until resolvers)
# Execute a GraphQL query (data-plane; send credentials for the API auth mode)
curl -s -X POST "$AWS_ENDPOINT_URL/v1/apis/API_ID/graphql" \
-H "Content-Type: application/json" \
-H "x-api-key: da2-YOUR_API_KEY" \
-d '{"query":"{ hello }"}'
# Create a channel namespace
@@ -431,7 +431,8 @@ public class ResolvedServiceCatalog {
"appsync", storageMode(config.storage().services().appsync().mode(), config.storage().mode()),
config.storage().services().appsync().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("appsync"), Set.of(), Set.of(AppSyncController.class)),
Set.of(), Set.of("appsync"), Set.of(), Set.of(AppSyncController.class,
io.github.hectorvent.floci.services.appsync.graphql.AppSyncExecutionController.class)),
descriptor("s3vectors", "s3vectors", config.services().s3vectors().enabled(), true,
"s3vectors", storageMode(config.storage().services().s3vectors().mode(), config.storage().mode()),
config.storage().services().s3vectors().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
@@ -17,6 +17,8 @@ import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Duration;
import java.util.*;
import java.util.Base64;
@@ -41,13 +43,15 @@ public class AppSyncService {
private final SchemaCreationWorker schemaCreationWorker;
private final Instance<RequestContext> requestContextInstance;
private final ObjectMapper objectMapper;
private final Clock clock;
@Inject
public AppSyncService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
SchemaRegistry schemaRegistry, SchemaCreationWorker schemaCreationWorker,
Instance<RequestContext> requestContextInstance, ObjectMapper objectMapper,
AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore,
AccountAwareStorageBackend<String> schemaStore) {
AccountAwareStorageBackend<String> schemaStore,
Clock clock) {
this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {});
this.schemaStore = schemaStore;
this.schemaStatusStore = schemaStatusStore;
@@ -65,6 +69,7 @@ public class AppSyncService {
this.schemaCreationWorker = schemaCreationWorker;
this.requestContextInstance = requestContextInstance;
this.objectMapper = objectMapper;
this.clock = clock;
}
// ──────────────────────────── GraphQL API ────────────────────────────
@@ -115,6 +120,7 @@ public class AppSyncService {
additionalList, new TypeReference<List<AdditionalAuthenticationProvider>>() {});
api.setAdditionalAuthenticationProviders(providers);
}
assertUniqueAuthProviders(api);
api.setArn(buildApiArn(apiId, region));
@@ -190,6 +196,7 @@ public class AppSyncService {
objectMapper.convertValue(additionalList, new TypeReference<List<AdditionalAuthenticationProvider>>() {}));
}
}
assertUniqueAuthProviders(existing);
apiStore.put(apiId, existing);
return existing;
}
@@ -581,22 +588,10 @@ public class AppSyncService {
key.setApiId(apiId);
key.setDescription((String) request.get("description"));
Object expiresValue = request.get("expires");
if (expiresValue instanceof Long l) {
key.setExpires(l);
} else if (expiresValue instanceof Number n) {
key.setExpires(n.longValue());
} else if (expiresValue instanceof String s) {
try {
key.setExpires(Long.parseLong(s));
} catch (NumberFormatException e) {
try {
key.setExpires(java.time.Instant.parse(s).getEpochSecond());
} catch (java.time.format.DateTimeParseException ex) {
throw new AwsException("BadRequestException",
"Invalid expires value: " + s + ". Expected epoch seconds or ISO 8601.", 400);
}
}
}
long expires = expiresValue == null
? clock.instant().getEpochSecond() + Duration.ofDays(7).getSeconds()
: parseExpires(expiresValue);
applyApiKeyExpires(key, expires);
key.setApiKey("da2-" + generateShortId());
@@ -613,27 +608,29 @@ public class AppSyncService {
.orElseThrow(() -> new AwsException("NotFoundException", "API key not found: " + keyId, 404));
}
public Optional<ApiKey> validateApiKey(String apiId, String keyValue) {
if (apiId == null || keyValue == null || keyValue.isBlank()) {
return Optional.empty();
}
long now = clock.instant().getEpochSecond();
for (ApiKey key : apiKeyStore.scan(k -> k.startsWith(apiId + "::"))) {
if (keyValue.equals(key.getApiKey())) {
if (key.getExpires() != null && key.getExpires() <= now) {
return Optional.empty();
}
return Optional.of(key);
}
}
return Optional.empty();
}
public ApiKey updateApiKey(String apiId, String keyId, Map<String, Object> request) {
ApiKey existing = getApiKey(apiId, keyId);
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("description")) {
existing.setDescription((String) request.get("description"));
}
if (request.containsKey("expires")) {
Object expiresValue = request.get("expires");
if (expiresValue instanceof Long l) {
existing.setExpires(l);
} else if (expiresValue instanceof Number n) {
existing.setExpires(n.longValue());
} else if (expiresValue instanceof String s) {
try {
existing.setExpires(Long.parseLong(s));
} catch (NumberFormatException e) {
try {
existing.setExpires(java.time.Instant.parse(s).getEpochSecond());
} catch (java.time.format.DateTimeParseException ex) {
throw new AwsException("BadRequestException",
"Invalid expires value: " + s + ". Expected epoch seconds or ISO 8601.", 400);
}
}
}
applyApiKeyExpires(existing, parseExpires(request.get("expires")));
}
apiKeyStore.put(apiKey(apiId, keyId), existing);
return existing;
@@ -969,6 +966,126 @@ public class AppSyncService {
// ──────────────────────────── Helpers ────────────────────────────
void assertUniqueAuthProviders(GraphqlApi api) {
Set<AuthenticationType> singletonSeen = EnumSet.noneOf(AuthenticationType.class);
Set<String> cognitoPools = new HashSet<>();
Set<String> oidcIssuers = new HashSet<>();
rememberProvider(api.getAuthenticationType(), configForDefault(api), 0, singletonSeen, cognitoPools, oidcIssuers);
if (api.getAdditionalAuthenticationProviders() == null) {
return;
}
List<AdditionalAuthenticationProvider> additional = api.getAdditionalAuthenticationProviders();
for (int i = 0; i < additional.size(); i++) {
AdditionalAuthenticationProvider provider = additional.get(i);
if (provider == null || provider.getAuthenticationType() == null) {
continue;
}
rememberProvider(provider.getAuthenticationType(), configForAdditional(provider),
i + 1, singletonSeen, cognitoPools, oidcIssuers);
}
}
private void rememberProvider(
AuthenticationType type,
Map<String, Object> config,
int additionalIndex,
Set<AuthenticationType> singletonSeen,
Set<String> cognitoPools,
Set<String> oidcIssuers
) {
if (type == null) {
return;
}
if (type == AuthenticationType.API_KEY || type == AuthenticationType.AWS_IAM
|| type == AuthenticationType.AWS_LAMBDA) {
if (!singletonSeen.add(type)) {
throw new AwsException("BadRequestException", duplicateProviderMessage(type, additionalIndex), 400);
}
return;
}
if (type == AuthenticationType.AMAZON_COGNITO_USER_POOLS) {
String poolId = config == null ? null : coerceString(config.get("userPoolId"));
String key = poolId == null ? UUID.randomUUID().toString() : poolId;
if (!cognitoPools.add(key) && poolId != null) {
throw new AwsException("BadRequestException",
duplicateProviderMessage(AuthenticationType.AMAZON_COGNITO_USER_POOLS, additionalIndex), 400);
}
return;
}
if (type == AuthenticationType.OPENID_CONNECT) {
String issuer = config == null ? null : coerceString(config.get("issuer"));
String key = issuer == null ? UUID.randomUUID().toString() : issuer;
if (!oidcIssuers.add(key) && issuer != null) {
throw new AwsException("BadRequestException",
duplicateProviderMessage(AuthenticationType.OPENID_CONNECT, additionalIndex), 400);
}
}
}
static String duplicateProviderMessage(AuthenticationType type, int additionalIndex) {
return "Authentication type " + type + " for additional authentication provider "
+ additionalIndex + " already specified on the API. It can only be specified once.";
}
private static Map<String, Object> configForDefault(GraphqlApi api) {
if (api.getAuthenticationType() == AuthenticationType.AMAZON_COGNITO_USER_POOLS) {
return api.getUserPoolConfig();
}
if (api.getAuthenticationType() == AuthenticationType.OPENID_CONNECT) {
return api.getOpenIDConnectConfig();
}
return api.getLambdaAuthorizerConfig();
}
private static Map<String, Object> configForAdditional(AdditionalAuthenticationProvider provider) {
return switch (provider.getAuthenticationType()) {
case AMAZON_COGNITO_USER_POOLS -> provider.getUserPoolConfig();
case OPENID_CONNECT -> provider.getOpenIDConnectConfig();
case AWS_LAMBDA -> provider.getLambdaAuthorizerConfig();
default -> Map.of();
};
}
private long parseExpires(Object expiresValue) {
if (expiresValue instanceof Long l) {
return l;
}
if (expiresValue instanceof Number n) {
return n.longValue();
}
if (expiresValue instanceof String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
try {
return java.time.Instant.parse(s).getEpochSecond();
} catch (java.time.format.DateTimeParseException ex) {
throw new AwsException("BadRequestException",
"Invalid expires value: " + s + ". Expected epoch seconds or ISO 8601.", 400);
}
}
}
throw new AwsException("BadRequestException", "Invalid expires value.", 400);
}
private void applyApiKeyExpires(ApiKey key, long expires) {
long rounded = roundDownToHour(expires);
long now = clock.instant().getEpochSecond();
long minExpires = now + Duration.ofDays(1).getSeconds();
long maxExpires = now + Duration.ofDays(365).getSeconds();
if (rounded < minExpires || rounded > maxExpires) {
throw new AwsException("ApiKeyValidityOutOfBoundsException",
"The API key expiration must be set to a value between 1 and 365 days from creation (for CreateApiKey) or from update (for UpdateApiKey).",
400);
}
key.setExpires(rounded);
key.setDeletes(roundDownToHour(rounded + Duration.ofDays(60).getSeconds()));
}
static long roundDownToHour(long epochSeconds) {
return Math.floorDiv(epochSeconds, 3600) * 3600;
}
private String generateApiId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 26);
}
@@ -10,7 +10,7 @@ public enum AppSyncDirective {
AWS_OIDC("aws_oidc", "directive @aws_oidc on OBJECT | FIELD_DEFINITION"),
AWS_LAMBDA("aws_lambda", "directive @aws_lambda on OBJECT | FIELD_DEFINITION"),
AWS_SUBSCRIBE("aws_subscribe", "directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION"),
AWS_AUTH("aws_auth", "directive @aws_auth(cognito_groups: [String!]!) on OBJECT"),
AWS_AUTH("aws_auth", "directive @aws_auth(cognito_groups: [String!]!) on OBJECT | FIELD_DEFINITION"),
AWS_DELTA_SYNC("aws_delta_sync",
"directive @aws_delta_sync(tableName: String!, deltaSyncTableTTL: Int!, baseTableTTL: Int!) on OBJECT");
@@ -4,7 +4,12 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
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.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.model.GraphqlApi;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
@@ -16,8 +21,12 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
/**
* AppSync GraphQL data-plane HTTP endpoint (separate from management {@code AppSyncController}).
@@ -35,18 +44,24 @@ public class AppSyncExecutionController {
private final QueryExecutor queryExecutor;
private final AppSyncErrorFormatter errorFormatter;
private final ObjectMapper objectMapper;
private final AuthMiddleware authMiddleware;
private final RequestContext requestContext;
@Inject
public AppSyncExecutionController(AppSyncService appSyncService,
SchemaRegistry schemaRegistry,
QueryExecutor queryExecutor,
AppSyncErrorFormatter errorFormatter,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
AuthMiddleware authMiddleware,
RequestContext requestContext) {
this.appSyncService = appSyncService;
this.schemaRegistry = schemaRegistry;
this.queryExecutor = queryExecutor;
this.errorFormatter = errorFormatter;
this.objectMapper = objectMapper;
this.authMiddleware = authMiddleware;
this.requestContext = requestContext;
}
@POST
@@ -67,8 +82,9 @@ public class AppSyncExecutionController {
return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage());
}
GraphqlApi api;
try {
appSyncService.getGraphqlApi(apiId);
api = appSyncService.getGraphqlApi(apiId);
} catch (AwsException e) {
if (e.getHttpStatus() == 404) {
return graphqlError(404, "NotFoundException", e.getMessage());
@@ -78,6 +94,14 @@ public class AppSyncExecutionController {
return graphqlError(500, "InternalFailure", "InternalFailure");
}
AppSyncAuthContext authContext;
try {
authContext = authMiddleware.authenticate(
headerMap(headers), api, authRequestInfo(parsed, headers));
} catch (AppSyncTransportException e) {
return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage());
}
var graphQLOpt = schemaRegistry.getGraphQL(apiId);
if (graphQLOpt.isEmpty()) {
return graphqlError(502, "GraphQLSchemaException",
@@ -86,7 +110,8 @@ public class AppSyncExecutionController {
try {
Map<String, Object> result = queryExecutor.execute(
graphQLOpt.get(), parsed.query(), parsed.variables(), parsed.operationName());
graphQLOpt.get(), parsed.query(), parsed.variables(), parsed.operationName(),
graphQlContext(authContext));
return Response.ok(result).type(MediaType.APPLICATION_JSON).build();
} catch (AppSyncTransportException e) {
return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage());
@@ -165,6 +190,64 @@ public class AppSyncExecutionController {
return new ParsedRequest(query, variables, operationName);
}
private Map<String, String> headerMap(HttpHeaders headers) {
Map<String, String> map = new HashMap<>();
if (headers == null || headers.getRequestHeaders() == null) {
return map;
}
for (String name : headers.getRequestHeaders().keySet()) {
if (name != null) {
map.put(name, headers.getHeaderString(name));
}
}
return map;
}
private AuthRequestInfo authRequestInfo(ParsedRequest parsed, HttpHeaders headers) {
String accountId = requestContext.getAccountId() != null ? requestContext.getAccountId() : "000000000000";
String region = requestContext.getRegion() != null ? requestContext.getRegion() : "us-east-1";
String requestId = headers.getHeaderString("x-amzn-RequestId");
if (requestId == null || requestId.isBlank()) {
requestId = UUID.randomUUID().toString();
}
return new AuthRequestInfo(
parsed.query(),
parsed.operationName(),
parsed.variables() == null ? Map.of() : parsed.variables(),
sourceIp(headers),
requestId,
accountId,
region,
headerMap(headers));
}
private static List<String> sourceIp(HttpHeaders headers) {
List<String> ips = new ArrayList<>();
String forwarded = headers.getHeaderString("X-Forwarded-For");
if (forwarded != null && !forwarded.isBlank()) {
for (String part : forwarded.split(",")) {
if (!part.isBlank()) {
ips.add(part.trim());
}
}
}
if (ips.isEmpty()) {
ips.add("127.0.0.1");
}
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 Response graphqlError(int status, String errorType, String message) {
return Response.status(status)
.header(HEADER_ERROR_TYPE, errorType)
@@ -53,7 +53,7 @@ public class AppSyncVtlContext {
map.put("arguments", arguments != null ? arguments : Map.of());
map.put("source", source != null ? source : Map.of());
map.put("result", result);
map.put("identity", identity != null ? identity : Map.of());
map.put("identity", identity);
map.put("request", request != null ? request : Map.of("headers", Map.of()));
map.put("stash", stash != null ? stash : new HashMap<>());
map.put("prev", prev);
@@ -30,11 +30,17 @@ public class QueryExecutor {
public Map<String, Object> execute(GraphQLSchema schema, String query,
Map<String, Object> variables, String operationName) {
return execute(SchemaRegistry.buildGraphQL(schema), query, variables, 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",
@@ -59,6 +65,9 @@ public class QueryExecutor {
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);
@@ -5,6 +5,7 @@ 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;
@@ -17,14 +18,23 @@ 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) {
public SchemaRegistry(AppSyncSchemaParser appSyncSchemaParser, AuthFieldWrapper authFieldWrapper) {
this.appSyncSchemaParser = appSyncSchemaParser;
this.authFieldWrapper = authFieldWrapper;
}
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));
}
@@ -42,7 +52,7 @@ public class SchemaRegistry {
engines.remove(apiId);
}
static GraphQL buildGraphQL(GraphQLSchema schema) {
public static GraphQL buildGraphQL(GraphQLSchema schema) {
return GraphQL.newGraphQL(schema)
.queryExecutionStrategy(new AsyncExecutionStrategy())
.mutationExecutionStrategy(new AsyncSerialExecutionStrategy())
@@ -0,0 +1,22 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
public class ApiKeyAuthValidator {
private final AppSyncService appSyncService;
@Inject
public ApiKeyAuthValidator(AppSyncService appSyncService) {
this.appSyncService = appSyncService;
}
public ApiKey validate(String apiId, String keyValue) {
return appSyncService.validateApiKey(apiId, keyValue)
.orElseThrow(AppSyncAuth::unauthorized);
}
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
public final class AppSyncAuth {
public static final String UNAUTHORIZED_TYPE = "UnauthorizedException";
public static final String UNAUTHORIZED_MESSAGE = "You are not authorized to make this call.";
public static final String MISSING_AUTHORIZATION_HEADER = "Missing authorization header";
public static final String FIELD_UNAUTHORIZED_TYPE = "Unauthorized";
public static String fieldUnauthorizedMessage(String fieldName, String typeName) {
return "Not Authorized to access " + fieldName + " on type " + typeName;
}
public static final String AUTH_TYPE_API_KEY = "API Key Authorization";
public static final String AUTH_TYPE_IAM = "IAM Authorization";
public static final String AUTH_TYPE_COGNITO = "User Pool Authorization";
public static final String AUTH_TYPE_OIDC = "Open ID Connect Authorization";
public static final String AUTH_TYPE_LAMBDA = "Lambda Authorization";
private AppSyncAuth() {
}
public static AppSyncTransportException unauthorized() {
return new AppSyncTransportException(401, UNAUTHORIZED_TYPE, UNAUTHORIZED_MESSAGE);
}
public static AppSyncTransportException missingAuthorizationHeader() {
return new AppSyncTransportException(401, UNAUTHORIZED_TYPE, MISSING_AUTHORIZATION_HEADER);
}
}
@@ -0,0 +1,29 @@
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.List;
import java.util.Map;
import java.util.Set;
public record AppSyncAuthContext(
Map<String, Object> identity,
String authType,
AuthenticationType authenticationType,
Set<String> deniedFields,
GraphqlApi graphqlApi,
String accessKeyId,
String region,
String accountId
) {
public static final String KEY = "appsyncAuthContext";
public AppSyncAuthContext {
deniedFields = deniedFields == null ? Set.of() : Set.copyOf(deniedFields);
}
public List<String> deniedFieldsList() {
return List.copyOf(deniedFields);
}
}
@@ -0,0 +1,57 @@
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);
}
}
@@ -0,0 +1,49 @@
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));
}
}
@@ -0,0 +1,197 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ApplicationScoped
public class AuthMiddleware {
private final ApiKeyAuthValidator apiKeyAuthValidator;
private final IamAuthValidator iamAuthValidator;
private final CognitoAuthValidator cognitoAuthValidator;
private final OidcAuthValidator oidcAuthValidator;
private final LambdaAuthorizerValidator lambdaAuthorizerValidator;
private final JwtClaimsDecoder jwtClaimsDecoder;
@Inject
public AuthMiddleware(ApiKeyAuthValidator apiKeyAuthValidator,
IamAuthValidator iamAuthValidator,
CognitoAuthValidator cognitoAuthValidator,
OidcAuthValidator oidcAuthValidator,
LambdaAuthorizerValidator lambdaAuthorizerValidator,
JwtClaimsDecoder jwtClaimsDecoder) {
this.apiKeyAuthValidator = apiKeyAuthValidator;
this.iamAuthValidator = iamAuthValidator;
this.cognitoAuthValidator = cognitoAuthValidator;
this.oidcAuthValidator = oidcAuthValidator;
this.lambdaAuthorizerValidator = lambdaAuthorizerValidator;
this.jwtClaimsDecoder = jwtClaimsDecoder;
}
public AppSyncAuthContext authenticate(Map<String, String> headers, GraphqlApi api, AuthRequestInfo info) {
ClassifiedMode classified = CredentialClassifier.classify(headers);
Set<AuthenticationType> configured = configuredModes(api);
return switch (classified) {
case NONE -> throw AppSyncAuth.missingAuthorizationHeader();
case API_KEY -> authenticateApiKey(headers, api, configured, info);
case AWS_IAM -> authenticateIam(headers, api, configured, info);
case BEARER_JWT -> authenticateBearer(headers, api, configured, info);
case AWS_LAMBDA -> authenticateLambda(headers, api, configured, info);
};
}
private AppSyncAuthContext authenticateApiKey(
Map<String, String> headers, GraphqlApi api, Set<AuthenticationType> configured, AuthRequestInfo info) {
if (!configured.contains(AuthenticationType.API_KEY)) {
throw AppSyncAuth.unauthorized();
}
String key = CredentialClassifier.header(headers, "x-api-key");
apiKeyAuthValidator.validate(api.getApiId(), key);
return context(null, AppSyncAuth.AUTH_TYPE_API_KEY, AuthenticationType.API_KEY, Set.of(), api, null, info);
}
private AppSyncAuthContext authenticateIam(
Map<String, String> headers, GraphqlApi api, Set<AuthenticationType> configured, AuthRequestInfo info) {
if (!configured.contains(AuthenticationType.AWS_IAM)) {
throw AppSyncAuth.unauthorized();
}
String authorization = CredentialClassifier.header(headers, "authorization");
Map<String, Object> identity = iamAuthValidator.validateRequest(authorization, api.getApiId(), info);
String accessKeyId = String.valueOf(identity.get("user"));
return context(identity, AppSyncAuth.AUTH_TYPE_IAM, AuthenticationType.AWS_IAM, Set.of(), api, accessKeyId, info);
}
private AppSyncAuthContext authenticateBearer(
Map<String, String> headers, GraphqlApi api, Set<AuthenticationType> configured, AuthRequestInfo info) {
String authorization = CredentialClassifier.header(headers, "authorization");
Map<String, Object> claims = jwtClaimsDecoder.decode(authorization).orElseThrow(AppSyncAuth::unauthorized);
List<ProviderConfig> cognito = providersOf(api, AuthenticationType.AMAZON_COGNITO_USER_POOLS);
List<ProviderConfig> oidc = providersOf(api, AuthenticationType.OPENID_CONNECT);
for (ProviderConfig provider : cognito) {
if (cognitoAuthValidator.matchesProvider(claims, provider.config())) {
Map<String, Object> identity = cognitoAuthValidator.validate(authorization, provider.config(), info.sourceIp());
return context(identity, AppSyncAuth.AUTH_TYPE_COGNITO, AuthenticationType.AMAZON_COGNITO_USER_POOLS,
Set.of(), api, null, info);
}
}
boolean skipIssuer = oidc.size() == 1 && configured.size() == 1
&& configured.contains(AuthenticationType.OPENID_CONNECT);
for (ProviderConfig provider : oidc) {
if (oidcAuthValidator.matchesProvider(claims, provider.config(), skipIssuer)) {
Map<String, Object> identity = oidcAuthValidator.validate(
authorization, provider.config(), skipIssuer);
return context(identity, AppSyncAuth.AUTH_TYPE_OIDC, AuthenticationType.OPENID_CONNECT,
Set.of(), api, null, info);
}
}
throw AppSyncAuth.unauthorized();
}
private AppSyncAuthContext authenticateLambda(
Map<String, String> headers, GraphqlApi api, Set<AuthenticationType> configured, AuthRequestInfo info) {
if (!configured.contains(AuthenticationType.AWS_LAMBDA)) {
throw AppSyncAuth.unauthorized();
}
String token = CredentialClassifier.header(headers, "authorization");
Map<String, Object> lambdaConfig = lambdaConfig(api);
LambdaAuthorizerResult result = lambdaAuthorizerValidator.authorize(api.getApiId(), token, lambdaConfig, info);
Map<String, Object> identity = IdentityBuilder.lambda(result.resolverContext());
return context(identity, AppSyncAuth.AUTH_TYPE_LAMBDA, AuthenticationType.AWS_LAMBDA,
new HashSet<>(result.deniedFields()), api, null, info);
}
private static AppSyncAuthContext context(
Map<String, Object> identity,
String authType,
AuthenticationType authenticationType,
Set<String> deniedFields,
GraphqlApi api,
String accessKeyId,
AuthRequestInfo info
) {
return new AppSyncAuthContext(
identity, authType, authenticationType, deniedFields, api, accessKeyId, info.region(), info.accountId());
}
static Set<AuthenticationType> configuredModes(GraphqlApi api) {
Set<AuthenticationType> modes = new HashSet<>();
if (api.getAuthenticationType() != null) {
modes.add(api.getAuthenticationType());
}
if (api.getAdditionalAuthenticationProviders() != null) {
for (AdditionalAuthenticationProvider provider : api.getAdditionalAuthenticationProviders()) {
if (provider != null && provider.getAuthenticationType() != null) {
modes.add(provider.getAuthenticationType());
}
}
}
return modes;
}
static boolean hasAdditionalModes(GraphqlApi api) {
return api.getAdditionalAuthenticationProviders() != null
&& !api.getAdditionalAuthenticationProviders().isEmpty();
}
private static List<ProviderConfig> providersOf(GraphqlApi api, AuthenticationType type) {
List<ProviderConfig> result = new ArrayList<>();
if (api.getAuthenticationType() == type) {
result.add(new ProviderConfig(configFor(api, type, null)));
}
if (api.getAdditionalAuthenticationProviders() != null) {
for (AdditionalAuthenticationProvider provider : api.getAdditionalAuthenticationProviders()) {
if (provider != null && provider.getAuthenticationType() == type) {
result.add(new ProviderConfig(configFor(api, type, provider)));
}
}
}
return result;
}
private static Map<String, Object> configFor(
GraphqlApi api, AuthenticationType type, AdditionalAuthenticationProvider additional) {
if (additional != null) {
return switch (type) {
case AMAZON_COGNITO_USER_POOLS -> additional.getUserPoolConfig();
case OPENID_CONNECT -> additional.getOpenIDConnectConfig();
case AWS_LAMBDA -> additional.getLambdaAuthorizerConfig();
default -> Map.of();
};
}
return switch (type) {
case AMAZON_COGNITO_USER_POOLS -> api.getUserPoolConfig();
case OPENID_CONNECT -> api.getOpenIDConnectConfig();
case AWS_LAMBDA -> api.getLambdaAuthorizerConfig();
default -> Map.of();
};
}
private static Map<String, Object> lambdaConfig(GraphqlApi api) {
if (api.getAuthenticationType() == AuthenticationType.AWS_LAMBDA) {
return api.getLambdaAuthorizerConfig();
}
if (api.getAdditionalAuthenticationProviders() != null) {
for (AdditionalAuthenticationProvider provider : api.getAdditionalAuthenticationProviders()) {
if (provider != null && provider.getAuthenticationType() == AuthenticationType.AWS_LAMBDA) {
return provider.getLambdaAuthorizerConfig();
}
}
}
return api.getLambdaAuthorizerConfig();
}
private record ProviderConfig(Map<String, Object> config) {
private ProviderConfig {
config = config == null ? Map.of() : config;
}
}
}
@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import java.util.List;
import java.util.Map;
public record AuthRequestInfo(
String query,
String operationName,
Map<String, Object> variables,
List<String> sourceIp,
String requestId,
String accountId,
String region,
Map<String, String> requestHeaders
) {
public AuthRequestInfo {
sourceIp = sourceIp == null ? List.of() : List.copyOf(sourceIp);
variables = variables == null ? Map.of() : Map.copyOf(variables);
requestHeaders = requestHeaders == null ? Map.of() : Map.copyOf(requestHeaders);
}
}
@@ -0,0 +1,191 @@
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,9 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
public enum ClassifiedMode {
API_KEY,
AWS_IAM,
BEARER_JWT,
AWS_LAMBDA,
NONE
}
@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
@ApplicationScoped
public class CognitoAuthValidator {
private final JwtClaimsDecoder jwtClaimsDecoder;
private final Clock clock;
@Inject
public CognitoAuthValidator(JwtClaimsDecoder jwtClaimsDecoder, Clock clock) {
this.jwtClaimsDecoder = jwtClaimsDecoder;
this.clock = clock;
}
public Map<String, Object> validate(String authorization, Map<String, Object> userPoolConfig, List<String> sourceIp) {
Map<String, Object> claims = jwtClaimsDecoder.decode(authorization)
.orElseThrow(AppSyncAuth::unauthorized);
if (claims.get("sub") == null || String.valueOf(claims.get("sub")).isBlank()) {
throw AppSyncAuth.unauthorized();
}
if (!unexpired(claims)) {
throw AppSyncAuth.unauthorized();
}
if (!issuerMatches(claims, userPoolConfig)) {
throw AppSyncAuth.unauthorized();
}
if (!audienceMatches(claims, userPoolConfig)) {
throw AppSyncAuth.unauthorized();
}
String defaultAction = coerceString(userPoolConfig == null ? null : userPoolConfig.get("defaultAction"), "ALLOW");
return IdentityBuilder.cognito(claims, sourceIp, defaultAction);
}
boolean matchesProvider(Map<String, Object> claims, Map<String, Object> userPoolConfig) {
return claims.get("sub") != null
&& unexpired(claims)
&& issuerMatches(claims, userPoolConfig)
&& audienceMatches(claims, userPoolConfig);
}
private boolean unexpired(Map<String, Object> claims) {
Long exp = asLong(claims.get("exp"));
if (exp == null) {
return false;
}
return exp > clock.instant().getEpochSecond();
}
private boolean issuerMatches(Map<String, Object> claims, Map<String, Object> config) {
String iss = coerceString(claims.get("iss"), null);
if (iss == null) {
return false;
}
String expected = expectedIssuer(config);
return expected != null && expected.equals(iss);
}
static String expectedIssuer(Map<String, Object> config) {
if (config == null) {
return null;
}
String issuer = coerceString(config.get("issuer"), null);
if (issuer != null) {
return issuer;
}
String poolId = coerceString(config.get("userPoolId"), null);
String region = coerceString(config.get("awsRegion"), null);
if (poolId == null || region == null) {
return null;
}
return "https://cognito-idp." + region + ".amazonaws.com/" + poolId;
}
private boolean audienceMatches(Map<String, Object> claims, Map<String, Object> config) {
if (config == null) {
return true;
}
String regex = coerceString(config.get("appIdClientRegex"), null);
String clientId = coerceString(config.get("clientId"), null);
if (regex == null && clientId == null) {
return true;
}
if (regex != null && clientMatches(claims, value -> Pattern.compile(regex).matcher(value).matches())) {
return true;
}
return clientId != null && clientMatches(claims, clientId::equals);
}
static boolean clientMatches(Map<String, Object> claims, java.util.function.Predicate<String> matcher) {
Object aud = claims.get("aud");
if (aud instanceof String s && matcher.test(s)) {
return true;
}
if (aud instanceof List<?> list) {
for (Object item : list) {
if (item != null && matcher.test(String.valueOf(item))) {
return true;
}
}
}
Object clientId = claims.get("client_id");
return clientId != null && matcher.test(String.valueOf(clientId));
}
static Long asLong(Object value) {
if (value instanceof Number n) {
return n.longValue();
}
if (value instanceof String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
static String coerceString(Object value, String fallback) {
if (value == null) {
return fallback;
}
String text = String.valueOf(value);
return text.isBlank() ? fallback : text;
}
}
@@ -0,0 +1,63 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import java.util.Locale;
import java.util.Map;
public final class CredentialClassifier {
private CredentialClassifier() {
}
public static ClassifiedMode classify(Map<String, String> headers) {
String authorization = header(headers, "authorization");
if (authorization != null && !authorization.isBlank()
&& authorization.startsWith("AWS4-HMAC-SHA256")) {
return ClassifiedMode.AWS_IAM;
}
String apiKey = header(headers, "x-api-key");
if (apiKey != null && !apiKey.isBlank()) {
return ClassifiedMode.API_KEY;
}
if (authorization == null || authorization.isBlank()) {
return ClassifiedMode.NONE;
}
if (isBearerJwt(authorization)) {
return ClassifiedMode.BEARER_JWT;
}
return ClassifiedMode.AWS_LAMBDA;
}
static String header(Map<String, String> headers, String name) {
if (headers == null || headers.isEmpty()) {
return null;
}
String direct = headers.get(name);
if (direct != null) {
return direct;
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey() != null && entry.getKey().equalsIgnoreCase(name)) {
return entry.getValue();
}
}
return null;
}
private static boolean isBearerJwt(String authorization) {
if (authorization.length() < 7 || !authorization.regionMatches(true, 0, "Bearer ", 0, 7)) {
return false;
}
String token = authorization.substring(7).trim();
int first = token.indexOf('.');
int second = token.indexOf('.', first + 1);
if (first <= 0 || second <= first + 1) {
return false;
}
int third = token.indexOf('.', second + 1);
return third < 0 && second < token.length() - 1;
}
static String normalizeKey(String name) {
return name == null ? "" : name.toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Map;
@ApplicationScoped
public class IamAuthValidator {
private final AccountResolver accountResolver;
private final IamService iamService;
private final IamPolicyEvaluator iamPolicyEvaluator;
@Inject
public IamAuthValidator(AccountResolver accountResolver,
IamService iamService,
IamPolicyEvaluator iamPolicyEvaluator) {
this.accountResolver = accountResolver;
this.iamService = iamService;
this.iamPolicyEvaluator = iamPolicyEvaluator;
}
public Map<String, Object> validateRequest(String authorization, String apiId, AuthRequestInfo info) {
String accessKeyId = accountResolver.extractAccessKeyId(authorization);
if (accessKeyId == null || accessKeyId.isBlank()) {
throw AppSyncAuth.unauthorized();
}
if (!isEmulatorAllow(accessKeyId)) {
CallerContext caller = iamService.resolveCallerContext(accessKeyId);
if (caller != null) {
String resource = requestArn(info.region(), info.accountId(), apiId);
IamPolicyEvaluator.Decision decision = iamPolicyEvaluator.evaluate(
caller, null, "appsync:GraphQL", resource, null);
if (decision == IamPolicyEvaluator.Decision.DENY) {
throw AppSyncAuth.unauthorized();
}
}
}
String userArn = iamService.resolveCallerArn(accessKeyId).orElseGet(
() -> "arn:aws:iam::" + nullToEmpty(info.accountId()) + ":root");
String username = usernameFromArn(userArn, accessKeyId);
return IdentityBuilder.iam(info.accountId(), accessKeyId, username, userArn, info.sourceIp());
}
public boolean isFieldDenied(String accessKeyId, String fieldArn) {
if (accessKeyId == null || isEmulatorAllow(accessKeyId)) {
return false;
}
CallerContext caller = iamService.resolveCallerContext(accessKeyId);
if (caller == null) {
return false;
}
return iamPolicyEvaluator.evaluate(caller, null, "appsync:GraphQL", fieldArn, null)
== IamPolicyEvaluator.Decision.DENY;
}
static boolean isEmulatorAllow(String accessKeyId) {
return "test".equals(accessKeyId);
}
static String requestArn(String region, String accountId, String apiId) {
return "arn:aws:appsync:" + nullToEmpty(region) + ":" + nullToEmpty(accountId)
+ ":apis/" + apiId + "/*";
}
static String fieldArn(String region, String accountId, String apiId, String typeName, String fieldName) {
return "arn:aws:appsync:" + nullToEmpty(region) + ":" + nullToEmpty(accountId)
+ ":apis/" + apiId + "/types/" + typeName + "/fields/" + fieldName;
}
static String usernameFromArn(String userArn, String accessKeyId) {
if (userArn == null) {
return accessKeyId;
}
int slash = userArn.lastIndexOf('/');
if (slash >= 0 && slash < userArn.length() - 1) {
return userArn.substring(slash + 1);
}
return accessKeyId;
}
private static String nullToEmpty(String value) {
return value == null ? "" : value;
}
}
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class IdentityBuilder {
private IdentityBuilder() {
}
public static Map<String, Object> iam(
String accountId,
String accessKeyId,
String username,
String userArn,
List<String> sourceIp
) {
Map<String, Object> identity = new LinkedHashMap<>();
identity.put("accountId", nullToEmpty(accountId));
identity.put("cognitoIdentityPoolId", "");
identity.put("cognitoIdentityId", "");
identity.put("sourceIp", sourceIpArray(sourceIp));
identity.put("username", username != null ? username : accessKeyId);
identity.put("userArn", nullToEmpty(userArn));
identity.put("cognitoIdentityAuthType", "");
identity.put("cognitoIdentityAuthProvider", "");
identity.put("user", accessKeyId);
return identity;
}
public static Map<String, Object> cognito(
Map<String, Object> claims,
List<String> sourceIp,
String defaultAuthStrategy
) {
Map<String, Object> identity = new LinkedHashMap<>();
identity.put("sub", claims.get("sub"));
identity.put("issuer", claims.get("iss"));
Object username = claims.get("cognito:username");
identity.put("username", username != null ? username : claims.get("username"));
identity.put("claims", claims);
identity.put("sourceIp", sourceIpArray(sourceIp));
identity.put("defaultAuthStrategy", defaultAuthStrategy);
identity.put("groups", groups(claims));
return identity;
}
public static Map<String, Object> oidc(Map<String, Object> claims) {
Map<String, Object> identity = new LinkedHashMap<>();
identity.put("sub", claims.get("sub"));
identity.put("issuer", claims.get("iss"));
identity.put("claims", claims);
return identity;
}
public static Map<String, Object> lambda(Map<String, Object> resolverContext) {
Map<String, Object> identity = new LinkedHashMap<>();
identity.put("resolverContext", resolverContext == null ? Map.of() : resolverContext);
return identity;
}
static Object groups(Map<String, Object> claims) {
if (!claims.containsKey("cognito:groups")) {
return null;
}
Object value = claims.get("cognito:groups");
if (value == null) {
return null;
}
if (value instanceof List<?> list) {
return List.copyOf(list);
}
return value;
}
static List<String> sourceIpArray(List<String> sourceIp) {
if (sourceIp == null || sourceIp.isEmpty()) {
return List.of();
}
List<String> copy = new ArrayList<>();
for (String ip : sourceIp) {
if (ip != null && !ip.isBlank()) {
copy.add(ip.trim());
}
}
return List.copyOf(copy);
}
private static String nullToEmpty(String value) {
return value == null ? "" : value;
}
}
@@ -0,0 +1,63 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
@ApplicationScoped
public class JwtClaimsDecoder {
private final ObjectMapper objectMapper;
@Inject
public JwtClaimsDecoder(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public Optional<Map<String, Object>> decode(String authorization) {
if (authorization == null || authorization.isBlank()) {
return Optional.empty();
}
String token = authorization;
if (authorization.regionMatches(true, 0, "Bearer ", 0, 7)) {
token = authorization.substring(7).trim();
}
String[] parts = token.split("\\.", -1);
if (parts.length != 3) {
return Optional.empty();
}
try {
byte[] json = Base64.getUrlDecoder().decode(pad(parts[1]));
Map<String, Object> claims = objectMapper.readValue(json, new TypeReference<>() {});
return Optional.of(claims);
} catch (Exception e) {
return Optional.empty();
}
}
private static String pad(String value) {
int rem = value.length() % 4;
if (rem == 0) {
return value;
}
return value + "=".repeat(4 - rem);
}
static String encode(Map<String, Object> claims, ObjectMapper objectMapper) {
try {
String header = Base64.getUrlEncoder().withoutPadding()
.encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
String payload = Base64.getUrlEncoder().withoutPadding()
.encodeToString(objectMapper.writeValueAsBytes(claims));
return header + "." + payload + ".sig";
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import jakarta.enterprise.context.ApplicationScoped;
import java.time.Clock;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class LambdaAuthorizerCache {
static final int MAX_CACHEABLE_BYTES = 1_048_576;
private final ConcurrentHashMap<String, Entry> cache = new ConcurrentHashMap<>();
private final Clock clock;
public LambdaAuthorizerCache() {
this(Clock.systemUTC());
}
LambdaAuthorizerCache(Clock clock) {
this.clock = clock;
}
public Optional<LambdaAuthorizerResult> get(String apiId, String token) {
Entry entry = cache.get(key(apiId, token));
if (entry == null) {
return Optional.empty();
}
if (entry.expiresAt.isBefore(clock.instant()) || entry.expiresAt.equals(clock.instant())) {
cache.remove(key(apiId, token), entry);
return Optional.empty();
}
return Optional.of(entry.result);
}
public void put(String apiId, String token, LambdaAuthorizerResult result, int ttlSeconds) {
if (result == null || ttlSeconds <= 0 || result.responseSizeBytes() >= MAX_CACHEABLE_BYTES) {
return;
}
Instant expiresAt = clock.instant().plusSeconds(ttlSeconds);
cache.put(key(apiId, token), new Entry(result, expiresAt));
}
static String key(String apiId, String token) {
return apiId + "\0" + token;
}
private record Entry(LambdaAuthorizerResult result, Instant expiresAt) {
}
}
@@ -0,0 +1,17 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import java.util.List;
import java.util.Map;
public record LambdaAuthorizerResult(
boolean authorized,
List<String> deniedFields,
Map<String, Object> resolverContext,
Integer ttlOverride,
int responseSizeBytes
) {
public LambdaAuthorizerResult {
deniedFields = deniedFields == null ? List.of() : List.copyOf(deniedFields);
resolverContext = resolverContext == null ? Map.of() : Map.copyOf(resolverContext);
}
}
@@ -0,0 +1,174 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
@ApplicationScoped
public class LambdaAuthorizerValidator {
private static final Logger LOG = Logger.getLogger(LambdaAuthorizerValidator.class);
static final int MAX_RESOLVER_CONTEXT_BYTES = 5 * 1024 * 1024;
private static final int TIMEOUT_SECONDS = 10;
private final LambdaService lambdaService;
private final LambdaAuthorizerCache cache;
private final ObjectMapper objectMapper;
@Inject
public LambdaAuthorizerValidator(LambdaService lambdaService,
LambdaAuthorizerCache cache,
ObjectMapper objectMapper) {
this.lambdaService = lambdaService;
this.cache = cache;
this.objectMapper = objectMapper;
}
public LambdaAuthorizerResult authorize(
String apiId,
String authorizationToken,
Map<String, Object> lambdaConfig,
AuthRequestInfo info
) {
if (lambdaConfig == null) {
throw AppSyncAuth.unauthorized();
}
String expression = string(lambdaConfig.get("identityValidationExpression"));
if (expression != null && !Pattern.compile(expression).matcher(authorizationToken).matches()) {
throw AppSyncAuth.unauthorized();
}
var cached = cache.get(apiId, authorizationToken);
if (cached.isPresent()) {
return requireAuthorized(cached.get());
}
String uri = string(lambdaConfig.get("authorizerUri"));
if (uri == null) {
throw AppSyncAuth.unauthorized();
}
Map<String, Object> event = new LinkedHashMap<>();
event.put("authorizationToken", authorizationToken);
Map<String, Object> requestContext = new LinkedHashMap<>();
requestContext.put("apiId", apiId);
requestContext.put("accountId", info.accountId());
requestContext.put("requestId", info.requestId());
requestContext.put("queryString", info.query());
requestContext.put("operationName", info.operationName());
requestContext.put("variables", info.variables());
event.put("requestContext", requestContext);
event.put("requestHeaders", info.requestHeaders());
InvokeResult invokeResult;
try {
byte[] payload = objectMapper.writeValueAsBytes(event);
invokeResult = CompletableFuture.supplyAsync(() -> lambdaService.invoke(
info.region(), uri, payload, InvocationType.RequestResponse))
.orTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.join();
} catch (Exception e) {
LOG.debugv(e, "Lambda authorizer invoke failed for API {0}", apiId);
throw AppSyncAuth.unauthorized();
}
if (invokeResult == null || invokeResult.getFunctionError() != null || invokeResult.getPayload() == null) {
throw AppSyncAuth.unauthorized();
}
LambdaAuthorizerResult parsed = parse(invokeResult.getPayload());
int apiTtl = intValue(lambdaConfig.get("authorizerResultTtlInSeconds"), 0);
int ttl = effectiveTtl(parsed.ttlOverride(), apiTtl);
cache.put(apiId, authorizationToken, parsed, ttl);
return requireAuthorized(parsed);
}
static int effectiveTtl(Integer ttlOverride, int apiTtl) {
if (ttlOverride != null) {
return ttlOverride <= 0 ? 0 : ttlOverride;
}
return Math.max(apiTtl, 0);
}
private LambdaAuthorizerResult requireAuthorized(LambdaAuthorizerResult result) {
if (!result.authorized()) {
throw AppSyncAuth.unauthorized();
}
return result;
}
@SuppressWarnings("unchecked")
LambdaAuthorizerResult parse(byte[] payload) {
Map<String, Object> body;
try {
body = objectMapper.readValue(payload, Map.class);
} catch (Exception e) {
throw AppSyncAuth.unauthorized();
}
if (body == null || body.isEmpty() || !body.containsKey("isAuthorized")) {
throw AppSyncAuth.unauthorized();
}
Object authorizedValue = body.get("isAuthorized");
boolean authorized = Boolean.TRUE.equals(authorizedValue) || "true".equals(String.valueOf(authorizedValue));
List<String> denied = new ArrayList<>();
Object deniedFields = body.get("deniedFields");
if (deniedFields instanceof List<?> list) {
for (Object item : list) {
if (item != null) {
denied.add(String.valueOf(item));
}
}
}
Map<String, Object> resolverContext = flattenResolverContext(body.get("resolverContext"));
Integer ttlOverride = CognitoAuthValidator.asLong(body.get("ttlOverride")) == null
? null
: CognitoAuthValidator.asLong(body.get("ttlOverride")).intValue();
return new LambdaAuthorizerResult(authorized, denied, resolverContext, ttlOverride, payload.length);
}
Map<String, Object> flattenResolverContext(Object raw) {
if (!(raw instanceof Map<?, ?> map)) {
return Map.of();
}
Map<String, Object> flat = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object value = entry.getValue();
if (value instanceof Map || value instanceof List) {
continue;
}
if (entry.getKey() != null && value != null) {
flat.put(String.valueOf(entry.getKey()), value);
}
}
try {
int size = objectMapper.writeValueAsBytes(flat).length;
if (size > MAX_RESOLVER_CONTEXT_BYTES) {
throw AppSyncAuth.unauthorized();
}
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw AppSyncAuth.unauthorized();
}
return flat;
}
private static String string(Object value) {
return value == null ? null : String.valueOf(value);
}
private static int intValue(Object value, int fallback) {
Long parsed = CognitoAuthValidator.asLong(value);
return parsed == null ? fallback : parsed.intValue();
}
}
@@ -0,0 +1,99 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.util.Map;
import java.util.regex.Pattern;
@ApplicationScoped
public class OidcAuthValidator {
private final JwtClaimsDecoder jwtClaimsDecoder;
private final Clock clock;
@Inject
public OidcAuthValidator(JwtClaimsDecoder jwtClaimsDecoder, Clock clock) {
this.jwtClaimsDecoder = jwtClaimsDecoder;
this.clock = clock;
}
public Map<String, Object> validate(
String authorization,
Map<String, Object> oidcConfig,
boolean skipIssuer
) {
Map<String, Object> claims = jwtClaimsDecoder.decode(authorization)
.orElseThrow(AppSyncAuth::unauthorized);
if (claims.get("sub") == null || String.valueOf(claims.get("sub")).isBlank()) {
throw AppSyncAuth.unauthorized();
}
if (!timestampsValid(claims, oidcConfig)) {
throw AppSyncAuth.unauthorized();
}
if (!skipIssuer && !issuerMatches(claims, oidcConfig)) {
throw AppSyncAuth.unauthorized();
}
if (!clientIdMatches(claims, oidcConfig)) {
throw AppSyncAuth.unauthorized();
}
return IdentityBuilder.oidc(claims);
}
boolean matchesProvider(Map<String, Object> claims, Map<String, Object> oidcConfig, boolean skipIssuer) {
return claims.get("sub") != null
&& timestampsValid(claims, oidcConfig)
&& (skipIssuer || issuerMatches(claims, oidcConfig))
&& clientIdMatches(claims, oidcConfig);
}
private boolean timestampsValid(Map<String, Object> claims, Map<String, Object> config) {
long now = clock.instant().getEpochSecond();
Long exp = CognitoAuthValidator.asLong(claims.get("exp"));
Long iat = CognitoAuthValidator.asLong(claims.get("iat"));
if (exp == null || iat == null) {
return false;
}
if (exp <= now || iat > now) {
return false;
}
Long iatTtl = CognitoAuthValidator.asLong(config == null ? null : config.get("iatTTL"));
if (iatTtl != null && now - iat > iatTtl) {
return false;
}
Long authTtl = CognitoAuthValidator.asLong(config == null ? null : config.get("authTTL"));
if (authTtl != null) {
Long authTime = CognitoAuthValidator.asLong(claims.get("auth_time"));
long start = authTime != null ? authTime : iat;
if (now - start > authTtl) {
return false;
}
}
return true;
}
private boolean issuerMatches(Map<String, Object> claims, Map<String, Object> config) {
String iss = CognitoAuthValidator.coerceString(claims.get("iss"), null);
String expected = config == null ? null : CognitoAuthValidator.coerceString(config.get("issuer"), null);
return iss != null && expected != null && expected.equals(iss);
}
private boolean clientIdMatches(Map<String, Object> claims, Map<String, Object> config) {
if (config == null) {
return true;
}
String clientId = CognitoAuthValidator.coerceString(config.get("clientId"), null);
if (clientId == null) {
return true;
}
Pattern pattern = Pattern.compile(clientId);
return CognitoAuthValidator.clientMatches(claims, value -> pattern.matcher(value).matches())
|| azpMatches(claims, pattern);
}
private static boolean azpMatches(Map<String, Object> claims, Pattern pattern) {
Object azp = claims.get("azp");
return azp != null && pattern.matcher(String.valueOf(azp)).matches();
}
}
@@ -11,6 +11,7 @@ public class ApiKey {
private String id;
private String description;
private Long expires;
private Long deletes;
private String apiId;
private String apiKey;
@@ -23,6 +24,9 @@ public class ApiKey {
public Long getExpires() { return expires; }
public void setExpires(Long expires) { this.expires = expires; }
public Long getDeletes() { return deletes; }
public void setDeletes(Long deletes) { this.deletes = deletes; }
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
@@ -0,0 +1,297 @@
package io.github.hectorvent.floci.services.appsync;
import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncExecutionController;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class AppSyncAuthIntegrationTest {
private static final String MGMT_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request";
@Inject
ResolvedServiceCatalog catalog;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void catalogRegistersExecutionController() {
assertTrue(catalog.byResourceClass(AppSyncExecutionController.class).isPresent());
}
@Test
void unsignedApiKeyPostReturnsAppSyncJsonNotS3Xml() {
String apiId = createApi("auth-" + UUID.randomUUID().toString().substring(0, 8));
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
String apiKey = createApiKey(apiId);
given()
.contentType("application/graphql")
.header("x-api-key", apiKey)
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(200)
.contentType(containsString("application/json"))
.body(not(containsString("<Error>")))
.body(not(containsString("NoSuchBucket")))
.body("data.hello", nullValue());
}
@Test
void missingCredentialsReturns401UnauthorizedException() {
String apiId = createApi("unauth-" + UUID.randomUUID().toString().substring(0, 8));
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
given()
.contentType("application/json")
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(401)
.header("x-amzn-errortype", containsString("UnauthorizedException"))
.header("x-amz-request-id", not(nullValue()))
.body("errors[0].errorType", equalTo("UnauthorizedException"))
.body("errors[0].message", equalTo("Missing authorization header"))
.body("data", nullValue())
.body("__type", nullValue());
}
@Test
void invalidApiKeyReturns401() {
String apiId = createApi("badkey-" + UUID.randomUUID().toString().substring(0, 8));
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
given()
.contentType("application/json")
.header("x-api-key", "da2-does-not-exist")
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(401)
.header("x-amzn-errortype", containsString("UnauthorizedException"))
.body("errors[0].message", equalTo("You are not authorized to make this call."));
}
@Test
void dummySigV4OnApiKeyApiReturns401() {
String apiId = createApi("sigv4-" + UUID.randomUUID().toString().substring(0, 8));
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
given()
.contentType("application/json")
.header("Authorization", MGMT_AUTH)
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(401)
.header("x-amzn-errortype", containsString("UnauthorizedException"));
}
@Test
void sigV4PlusValidApiKeyDoesNotFallBackToApiKey() {
String apiId = createApi("nofallback-" + UUID.randomUUID().toString().substring(0, 8));
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
String apiKey = createApiKey(apiId);
given()
.contentType("application/json")
.header("x-api-key", apiKey)
.header("Authorization", MGMT_AUTH)
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(401)
.header("x-amzn-errortype", containsString("UnauthorizedException"));
}
@Test
void unknownApiReturns404BeforeAuth() {
given()
.contentType("application/json")
.header("x-api-key", "da2-looks-valid")
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/does-not-exist-xyz/graphql")
.then()
.statusCode(404)
.header("x-amzn-errortype", containsString("NotFoundException"));
}
@Test
void missingCredentialsOnApiWithoutSchemaReturns401Not502() {
String bareApiId = createApi("bare-auth-" + UUID.randomUUID().toString().substring(0, 8));
given()
.contentType("application/json")
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + bareApiId + "/graphql")
.then()
.statusCode(401)
.header("x-amzn-errortype", containsString("UnauthorizedException"))
.body("errors[0].message", equalTo("Missing authorization header"));
}
@Test
void iamCallerOnApiKeyFieldReturns200WithUnauthorizedError() {
String apiId = given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
.body("""
{
"name": "multi-%s",
"authenticationType": "AWS_IAM",
"additionalAuthenticationProviders": [
{"authenticationType": "API_KEY"}
]
}
""".formatted(UUID.randomUUID().toString().substring(0, 8)))
.when()
.post("/v1/apis")
.then()
.statusCode(200)
.extract().path("graphqlApi.apiId");
startSchema(apiId, "type Query { hello: String @aws_api_key }");
awaitSchemaSuccess(apiId);
given()
.contentType("application/json")
.header("Authorization", MGMT_AUTH)
.body("{\"query\":\"{ hello }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(200)
.header("x-amzn-errortype", nullValue())
.body("data.hello", nullValue())
.body("errors[0].errorType", equalTo("Unauthorized"))
.body("errors[0].message", equalTo("Not Authorized to access hello on type Query"))
.body("errors[0].path", equalTo(java.util.List.of("hello")));
}
@Test
void additionalModeIamCanIntrospect() {
String apiId = given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
.body("""
{
"name": "intro-%s",
"authenticationType": "API_KEY",
"additionalAuthenticationProviders": [
{"authenticationType": "AWS_IAM"}
]
}
""".formatted(UUID.randomUUID().toString().substring(0, 8)))
.when()
.post("/v1/apis")
.then()
.statusCode(200)
.extract().path("graphqlApi.apiId");
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
given()
.contentType("application/json")
.header("Authorization", MGMT_AUTH)
.body("{\"query\":\"{ __schema { types { name } } }\"}")
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(200)
.body("data.__schema.types", not(nullValue()))
.body("errors", nullValue());
}
@Test
void awsAuthOnFieldDefinitionSchemaSucceeds() {
String apiId = createApi("aws-auth-" + UUID.randomUUID().toString().substring(0, 8));
startSchema(apiId, "type Query { secret: String @aws_auth(cognito_groups: [\"Admins\"]) }");
awaitSchemaSuccess(apiId);
}
private static String createApi(String name) {
return given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
.body("""
{"name": "%s", "authenticationType": "API_KEY"}
""".formatted(name))
.when()
.post("/v1/apis")
.then()
.statusCode(200)
.extract().path("graphqlApi.apiId");
}
private static String createApiKey(String apiId) {
return given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
.body("{}")
.when()
.post("/v1/apis/" + apiId + "/apikeys")
.then()
.statusCode(200)
.extract().path("apiKey.apiKey");
}
private static void startSchema(String apiId, String definition) {
String escaped = definition.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
.body("{\"definition\": \"" + escaped + "\"}")
.when()
.post("/v1/apis/" + apiId + "/schemacreation")
.then()
.statusCode(200);
}
private static void awaitSchemaSuccess(String apiId) {
await().atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(25))
.until(() -> {
String status = given()
.header("Authorization", MGMT_AUTH)
.when()
.get("/v1/apis/" + apiId + "/schemacreation")
.then()
.statusCode(200)
.extract().path("status");
return "SUCCESS".equals(status);
});
}
}
@@ -29,6 +29,7 @@ class AppSyncExecutionIntegrationTest {
SchemaRegistry schemaRegistry;
private String apiId;
private String apiKey;
@BeforeAll
static void configureRestAssured() {
@@ -38,6 +39,7 @@ class AppSyncExecutionIntegrationTest {
@BeforeEach
void createApiWithSchema() {
apiId = createApi("exec-" + UUID.randomUUID().toString().substring(0, 8));
apiKey = createApiKey(apiId);
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
}
@@ -45,7 +47,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void dualContentTypeJsonReturnsNullHello() {
given()
.header("Authorization", AUTH)
.header("x-api-key", apiKey)
.contentType("application/json")
.body("{\"query\":\"{ hello }\"}")
.when()
@@ -60,7 +62,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void dualContentTypeGraphqlReturnsNullHello() {
given()
.header("Authorization", AUTH)
.header("x-api-key", apiKey)
.contentType("application/graphql")
.body("{\"query\":\"{ hello }\"}")
.when()
@@ -170,9 +172,10 @@ class AppSyncExecutionIntegrationTest {
@Test
void apiWithoutSchemaReturns502GraphQLSchemaException() {
String bareApiId = createApi("bare-" + UUID.randomUUID().toString().substring(0, 8));
String bareKey = createApiKey(bareApiId);
given()
.header("Authorization", AUTH)
.header("x-api-key", bareKey)
.contentType("application/json")
.body("{\"query\":\"{ hello }\"}")
.when()
@@ -187,7 +190,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void validationErrorReturns200WithTopLevelErrorType() {
given()
.header("Authorization", AUTH)
.header("x-api-key", apiKey)
.contentType("application/json")
.body("{\"query\":\"{ nope }\"}")
.when()
@@ -201,7 +204,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void syntaxErrorReturns200WithSyntaxError() {
given()
.header("Authorization", AUTH)
.header("x-api-key", apiKey)
.contentType("application/json")
.body("{\"query\":\"{ hello\"}")
.when()
@@ -214,7 +217,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void introspectionReturnsNonEmptyTypes() {
Map<String, Object> body = given()
.header("Authorization", AUTH)
.header("x-api-key", apiKey)
.contentType("application/json")
.body("{\"query\":\"{ __schema { types { name } } }\"}")
.when()
@@ -235,11 +238,12 @@ class AppSyncExecutionIntegrationTest {
@Test
void variablesAndOperationNameExecuteSelectedOp() {
String multiApi = createApi("multi-" + UUID.randomUUID().toString().substring(0, 8));
String multiKey = createApiKey(multiApi);
startSchema(multiApi, "type Query { hello(id: String): String }");
awaitSchemaSuccess(multiApi);
given()
.header("Authorization", AUTH)
.header("x-api-key", multiKey)
.contentType("application/json")
.body("""
{
@@ -258,6 +262,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void httpSubscriptionReturns200OperationNotSupported() {
String subApi = createApi("sub-" + UUID.randomUUID().toString().substring(0, 8));
String subKey = createApiKey(subApi);
startSchema(subApi, """
type Query { hello: String }
type Subscription { onHello: String }
@@ -265,7 +270,7 @@ class AppSyncExecutionIntegrationTest {
awaitSchemaSuccess(subApi);
given()
.header("Authorization", AUTH)
.header("x-api-key", subKey)
.contentType("application/json")
.body("{\"query\":\"subscription { onHello }\"}")
.when()
@@ -278,7 +283,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void whitespaceOnlyQueryReturns200SyntaxError() {
given()
.header("Authorization", AUTH)
.header("x-api-key", apiKey)
.contentType("application/json")
.body("{\"query\":\" \"}")
.when()
@@ -291,6 +296,7 @@ class AppSyncExecutionIntegrationTest {
@Test
void rehydrateFromSchemaStoreEnablesExecute() {
String hydrateApi = createApi("hydrate-" + UUID.randomUUID().toString().substring(0, 8));
String hydrateKey = createApiKey(hydrateApi);
startSchema(hydrateApi, "type Query { hello: String }");
awaitSchemaSuccess(hydrateApi);
@@ -298,7 +304,7 @@ class AppSyncExecutionIntegrationTest {
assertTrue(schemaRegistry.getSchema(hydrateApi).isEmpty());
given()
.header("Authorization", AUTH)
.header("x-api-key", hydrateKey)
.contentType("application/json")
.body("{\"query\":\"{ hello }\"}")
.when()
@@ -310,7 +316,7 @@ class AppSyncExecutionIntegrationTest {
rehydrateWorker().rehydrateSchemas();
given()
.header("Authorization", AUTH)
.header("x-api-key", hydrateKey)
.contentType("application/json")
.body("{\"query\":\"{ hello }\"}")
.when()
@@ -341,6 +347,18 @@ class AppSyncExecutionIntegrationTest {
.extract().path("graphqlApi.apiId");
}
private static String createApiKey(String apiId) {
return given()
.header("Authorization", AUTH)
.contentType("application/json")
.body("{}")
.when()
.post("/v1/apis/" + apiId + "/apikeys")
.then()
.statusCode(200)
.extract().path("apiKey.apiKey");
}
private static void startSchema(String apiId, String definition) {
String escaped = definition.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
given()
@@ -0,0 +1,267 @@
package io.github.hectorvent.floci.services.appsync;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker;
import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry;
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
class AppSyncServiceTest {
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
private AppSyncService service;
@BeforeEach
void setUp() {
service = newService(Clock.fixed(NOW, ZoneOffset.UTC));
}
@Test
void validateApiKeyLooksUpByValue() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "a", "authenticationType", "API_KEY"), "us-east-1");
ApiKey created = service.createApiKey(api.getApiId(), Map.of());
assertTrue(service.validateApiKey(api.getApiId(), created.getApiKey()).isPresent());
}
@Test
void validateApiKeyExpiresAtBoundaryFails() {
MutableClock clock = new MutableClock(NOW);
AppSyncService svc = newService(clock);
GraphqlApi api = svc.createGraphqlApi(Map.of("name", "b", "authenticationType", "API_KEY"), "us-east-1");
long expires = NOW.getEpochSecond() + Duration.ofDays(1).getSeconds();
ApiKey created = svc.createApiKey(api.getApiId(), Map.of("expires", expires));
assertTrue(svc.validateApiKey(api.getApiId(), created.getApiKey()).isPresent());
clock.set(NOW.plus(Duration.ofDays(1)));
assertTrue(svc.validateApiKey(api.getApiId(), created.getApiKey()).isEmpty());
}
@Test
void createApiKeyExpiresNowThrowsOutOfBounds() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "bound-now", "authenticationType", "API_KEY"), "us-east-1");
AwsException ex = assertThrows(AwsException.class,
() -> service.createApiKey(api.getApiId(), Map.of("expires", NOW.getEpochSecond())));
assertEquals(400, ex.getHttpStatus());
assertEquals("ApiKeyValidityOutOfBoundsException", ex.getErrorCode());
}
@Test
void createApiKeyExpiresAfter365DaysThrowsOutOfBounds() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "bound-max", "authenticationType", "API_KEY"), "us-east-1");
long expires = NOW.getEpochSecond() + Duration.ofDays(366).getSeconds();
AwsException ex = assertThrows(AwsException.class,
() -> service.createApiKey(api.getApiId(), Map.of("expires", expires)));
assertEquals("ApiKeyValidityOutOfBoundsException", ex.getErrorCode());
}
@Test
void updateApiKeyExpiresOutOfBoundsThrows() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "bound-update", "authenticationType", "API_KEY"), "us-east-1");
ApiKey created = service.createApiKey(api.getApiId(), Map.of());
AwsException tooSoon = assertThrows(AwsException.class,
() -> service.updateApiKey(api.getApiId(), created.getId(), Map.of("expires", NOW.getEpochSecond())));
assertEquals("ApiKeyValidityOutOfBoundsException", tooSoon.getErrorCode());
long tooLate = NOW.getEpochSecond() + Duration.ofDays(366).getSeconds();
AwsException tooFar = assertThrows(AwsException.class,
() -> service.updateApiKey(api.getApiId(), created.getId(), Map.of("expires", tooLate)));
assertEquals("ApiKeyValidityOutOfBoundsException", tooFar.getErrorCode());
}
@Test
void validateApiKeyWrongApiFails() {
GraphqlApi a = service.createGraphqlApi(Map.of("name", "c", "authenticationType", "API_KEY"), "us-east-1");
GraphqlApi b = service.createGraphqlApi(Map.of("name", "d", "authenticationType", "API_KEY"), "us-east-1");
ApiKey created = service.createApiKey(a.getApiId(), Map.of());
assertTrue(service.validateApiKey(b.getApiId(), created.getApiKey()).isEmpty());
}
@Test
void omittedExpiresDefaultsToSevenDays() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "e", "authenticationType", "API_KEY"), "us-east-1");
ApiKey created = service.createApiKey(api.getApiId(), Map.of());
assertEquals(NOW.getEpochSecond() + Duration.ofDays(7).getSeconds(), created.getExpires());
assertEquals(NOW.getEpochSecond() + Duration.ofDays(67).getSeconds(), created.getDeletes());
}
@Test
void explicitExpiresIsStored() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "f", "authenticationType", "API_KEY"), "us-east-1");
long expires = NOW.getEpochSecond() + Duration.ofDays(30).getSeconds();
ApiKey created = service.createApiKey(api.getApiId(), Map.of("expires", expires));
assertEquals(expires, created.getExpires());
assertEquals(expires + Duration.ofDays(60).getSeconds(), created.getDeletes());
}
@Test
void omittedExpiresRoundsDownToHour() {
Instant now = Instant.parse("2026-01-01T00:30:00Z");
AppSyncService svc = newService(Clock.fixed(now, ZoneOffset.UTC));
GraphqlApi api = svc.createGraphqlApi(Map.of("name", "round-default", "authenticationType", "API_KEY"), "us-east-1");
ApiKey created = svc.createApiKey(api.getApiId(), Map.of());
assertEquals(Instant.parse("2026-01-08T00:00:00Z").getEpochSecond(), created.getExpires());
}
@Test
void explicitExpiresRoundsDownToHour() {
Instant now = Instant.parse("2026-01-01T00:30:00Z");
AppSyncService svc = newService(Clock.fixed(now, ZoneOffset.UTC));
GraphqlApi api = svc.createGraphqlApi(Map.of("name", "round-explicit", "authenticationType", "API_KEY"), "us-east-1");
long expires = Instant.parse("2026-01-31T00:30:00Z").getEpochSecond();
ApiKey created = svc.createApiKey(api.getApiId(), Map.of("expires", expires));
assertEquals(Instant.parse("2026-01-31T00:00:00Z").getEpochSecond(), created.getExpires());
}
@Test
void updateApiKeyExpiresRoundsDownToHour() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "round-update", "authenticationType", "API_KEY"), "us-east-1");
ApiKey created = service.createApiKey(api.getApiId(), Map.of());
long expires = Instant.parse("2026-02-01T00:45:00Z").getEpochSecond();
ApiKey updated = service.updateApiKey(api.getApiId(), created.getId(), Map.of("expires", expires));
assertEquals(Instant.parse("2026-02-01T00:00:00Z").getEpochSecond(), updated.getExpires());
}
@Test
void duplicateApiKeyProviderRejected() {
Map<String, Object> request = new HashMap<>();
request.put("name", "dup-key");
request.put("authenticationType", "API_KEY");
request.put("additionalAuthenticationProviders", List.of(Map.of("authenticationType", "API_KEY")));
AwsException ex = assertThrows(AwsException.class, () -> service.createGraphqlApi(request, "us-east-1"));
assertEquals(400, ex.getHttpStatus());
assertEquals("BadRequestException", ex.getErrorCode());
assertEquals(
"Authentication type API_KEY for additional authentication provider 1 already specified on the API. It can only be specified once.",
ex.getMessage());
}
@Test
void duplicateIamAndLambdaRejected() {
AwsException iam = assertThrows(AwsException.class, () -> service.createGraphqlApi(Map.of(
"name", "dup-iam",
"authenticationType", "AWS_IAM",
"additionalAuthenticationProviders", List.of(Map.of("authenticationType", "AWS_IAM"))
), "us-east-1"));
assertEquals(400, iam.getHttpStatus());
assertEquals(
"Authentication type AWS_IAM for additional authentication provider 1 already specified on the API. It can only be specified once.",
iam.getMessage());
AwsException lambda = assertThrows(AwsException.class, () -> service.createGraphqlApi(Map.of(
"name", "dup-lambda",
"authenticationType", "AWS_LAMBDA",
"additionalAuthenticationProviders", List.of(Map.of("authenticationType", "AWS_LAMBDA"))
), "us-east-1"));
assertEquals(400, lambda.getHttpStatus());
assertEquals(
"Authentication type AWS_LAMBDA for additional authentication provider 1 already specified on the API. It can only be specified once.",
lambda.getMessage());
}
@Test
void distinctCognitoPoolsAllowed() {
GraphqlApi api = service.createGraphqlApi(Map.of(
"name", "multi-cog",
"authenticationType", "AMAZON_COGNITO_USER_POOLS",
"userPoolConfig", Map.of("userPoolId", "pool-a", "awsRegion", "us-east-1", "appIdClientRegex", "a"),
"additionalAuthenticationProviders", List.of(Map.of(
"authenticationType", "AMAZON_COGNITO_USER_POOLS",
"userPoolConfig", Map.of("userPoolId", "pool-b", "awsRegion", "us-east-1", "appIdClientRegex", "b")
))
), "us-east-1");
assertEquals(AuthenticationType.AMAZON_COGNITO_USER_POOLS, api.getAuthenticationType());
assertEquals(1, api.getAdditionalAuthenticationProviders().size());
}
@Test
void createResolverDoesNotReregisterSchema() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "r", "authenticationType", "API_KEY"), "us-east-1");
service.createDataSource(api.getApiId(), Map.of("name", "none", "type", "NONE"), "us-east-1");
service.createResolver(api.getApiId(), Map.of(
"typeName", "Query",
"fieldName", "hello",
"dataSourceName", "none"
), "us-east-1");
verify(schemaRegistry, never()).register(any(), any());
}
private SchemaRegistry schemaRegistry;
@SuppressWarnings("unchecked")
private AppSyncService newService(Clock clock) {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return AccountAwareStorageBackend.inMemory("000000000000");
}
};
Instance<RequestContext> requestContext = mock(Instance.class);
schemaRegistry = mock(SchemaRegistry.class);
return new AppSyncService(
storageFactory,
mock(EmulatorConfig.class),
new RegionResolver("us-east-1", "000000000000"),
schemaRegistry,
mock(SchemaCreationWorker.class),
requestContext,
new ObjectMapper(),
AccountAwareStorageBackend.inMemory("000000000000"),
AccountAwareStorageBackend.inMemory("000000000000"),
clock);
}
private static final class MutableClock extends Clock {
private Instant instant;
private MutableClock(Instant instant) {
this.instant = instant;
}
void set(Instant instant) {
this.instant = instant;
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
return this;
}
@Override
public Instant instant() {
return instant;
}
}
}
@@ -6,6 +6,7 @@ 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.List;
@@ -116,4 +117,24 @@ class AppSyncErrorFormatterTest {
assertTrue(responseData.containsKey("hello"));
assertFalse(response.containsKey("errors"));
}
@Test
void unauthorizedClassificationMapsToUnauthorized() {
GraphQLError error = new AppSyncFieldUnauthorizedException(List.of("hello"), "hello", "Query");
Map<String, Object> data = new java.util.LinkedHashMap<>();
data.put("hello", null);
ExecutionResult result = ExecutionResultImpl.newExecutionResult()
.data(data)
.addError(error)
.build();
Map<String, Object> response = formatter.format(result);
@SuppressWarnings("unchecked")
List<Map<String, Object>> errors = (List<Map<String, Object>>) response.get("errors");
assertEquals("Unauthorized", errors.get(0).get("errorType"));
assertEquals("Not Authorized to access hello on type Query", errors.get(0).get("message"));
assertEquals(List.of("hello"), errors.get(0).get("path"));
assertNull(errors.get(0).get("errorInfo"));
}
}
@@ -3,9 +3,15 @@ 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.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.model.AuthenticationType;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -16,12 +22,14 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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;
@@ -34,6 +42,10 @@ class AppSyncExecutionControllerTest {
SchemaRegistry schemaRegistry;
@Mock
QueryExecutor queryExecutor;
@Mock
AuthMiddleware authMiddleware;
@Mock
RequestContext requestContext;
private AppSyncExecutionController controller;
private HttpHeaders jsonHeaders;
@@ -45,17 +57,23 @@ class AppSyncExecutionControllerTest {
schemaRegistry,
queryExecutor,
new AppSyncErrorFormatter(),
new ObjectMapper());
new ObjectMapper(),
authMiddleware,
requestContext);
jsonHeaders = mock(HttpHeaders.class);
when(jsonHeaders.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn("application/json");
lenient().when(jsonHeaders.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn("application/json");
lenient().when(jsonHeaders.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
}
@Test
void unexpectedExecutorFailureReturns500InternalFailure() {
when(appSyncService.getGraphqlApi("api-1")).thenReturn(new GraphqlApi());
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()))
when(queryExecutor.execute(any(GraphQL.class), eq("{ hello }"), isNull(), isNull(), any()))
.thenThrow(new RuntimeException("boom"));
Response response = controller.execute("api-1", jsonHeaders, "{\"query\":\"{ hello }\"}");
@@ -118,4 +136,29 @@ class AppSyncExecutionControllerTest {
assertEquals("InternalFailure", error.get("errorType"));
assertEquals("InternalFailure", error.get("message"));
}
@Test
void authFailureReturns401WithoutCallingExecutor() {
GraphqlApi api = new GraphqlApi();
api.setApiId("api-1");
when(appSyncService.getGraphqlApi("api-1")).thenReturn(api);
when(authMiddleware.authenticate(any(), any(), any())).thenThrow(AppSyncAuth.unauthorized());
Response response = controller.execute("api-1", jsonHeaders, "{\"query\":\"{ hello }\"}");
assertEquals(401, response.getStatus());
assertEquals("UnauthorizedException", response.getHeaderString("x-amzn-errortype"));
@SuppressWarnings("unchecked")
Map<String, Object> body = (Map<String, Object>) response.getEntity();
@SuppressWarnings("unchecked")
Map<String, Object> error = ((List<Map<String, Object>>) body.get("errors")).get(0);
assertEquals("UnauthorizedException", error.get("errorType"));
assertEquals("You are not authorized to make this call.", error.get("message"));
}
private static AppSyncAuthContext authContext(GraphqlApi api) {
return new AppSyncAuthContext(
null, AppSyncAuth.AUTH_TYPE_API_KEY, AuthenticationType.API_KEY, Set.of(),
api, null, "us-east-1", "000000000000");
}
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.appsync.graphql;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuth;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AppSyncVtlContextTest {
private final com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
@Test
void nullIdentityStaysNullNotEmptyMap() {
AppSyncVtlContext ctx = AppSyncVtlContext.builder(mapper)
.identity(null)
.authType(AppSyncAuth.AUTH_TYPE_API_KEY)
.build();
assertNull(ctx.getContextMap().get("identity"));
assertEquals(AppSyncAuth.AUTH_TYPE_API_KEY, ctx.getUtil().authType());
}
@Test
void populatedIdentityIsPreserved() {
Map<String, Object> identity = Map.of("user", "AKIATEST");
AppSyncVtlContext ctx = AppSyncVtlContext.builder(mapper)
.identity(identity)
.authType(AppSyncAuth.AUTH_TYPE_IAM)
.build();
assertEquals(identity, ctx.getContextMap().get("identity"));
}
}
@@ -1,5 +1,7 @@
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;
@@ -8,6 +10,8 @@ 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;
@@ -112,4 +116,36 @@ class QueryExecutorTest {
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"));
}
}
@@ -1,10 +1,13 @@
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.assertTrue;
@@ -52,4 +55,13 @@ class SchemaRegistryTest {
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);
}
}
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ApiKeyAuthValidatorTest {
@Mock
AppSyncService appSyncService;
@Test
void validKeyReturnsStoredKey() {
ApiKey stored = new ApiKey();
stored.setApiKey("da2-abc");
when(appSyncService.validateApiKey("api-1", "da2-abc")).thenReturn(Optional.of(stored));
ApiKey result = new ApiKeyAuthValidator(appSyncService).validate("api-1", "da2-abc");
assertEquals("da2-abc", result.getApiKey());
}
@Test
void unknownKeyThrows401() {
when(appSyncService.validateApiKey("api-1", "da2-missing")).thenReturn(Optional.empty());
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> new ApiKeyAuthValidator(appSyncService).validate("api-1", "da2-missing"));
assertEquals(401, ex.getHttpStatus());
assertEquals("UnauthorizedException", ex.getErrorType());
assertEquals("You are not authorized to make this call.", ex.getMessage());
}
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.appsync.model.AdditionalAuthenticationProvider;
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
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 org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AuthMiddlewareTest {
@Mock ApiKeyAuthValidator apiKeyAuthValidator;
@Mock IamAuthValidator iamAuthValidator;
@Mock CognitoAuthValidator cognitoAuthValidator;
@Mock OidcAuthValidator oidcAuthValidator;
@Mock LambdaAuthorizerValidator lambdaAuthorizerValidator;
private AuthMiddleware middleware;
private AuthRequestInfo info;
@BeforeEach
void setUp() {
middleware = new AuthMiddleware(
apiKeyAuthValidator, iamAuthValidator, cognitoAuthValidator, oidcAuthValidator,
lambdaAuthorizerValidator, new JwtClaimsDecoder(new ObjectMapper()));
info = new AuthRequestInfo("{ hello }", null, Map.of(), List.of("127.0.0.1"),
"req", "000000000000", "us-east-1", Map.of());
}
@Test
void headerMapApiKeySuccess() {
GraphqlApi api = api(AuthenticationType.API_KEY);
when(apiKeyAuthValidator.validate("api-1", "da2-abc")).thenReturn(new ApiKey());
AppSyncAuthContext ctx = middleware.authenticate(Map.of("x-api-key", "da2-abc"), api, info);
assertEquals(AppSyncAuth.AUTH_TYPE_API_KEY, ctx.authType());
assertNull(ctx.identity());
assertEquals(AuthenticationType.API_KEY, ctx.authenticationType());
}
@Test
void missingCredentialsIs401() {
GraphqlApi api = api(AuthenticationType.API_KEY);
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> middleware.authenticate(Map.of(), api, info));
assertEquals(401, ex.getHttpStatus());
assertEquals(AppSyncAuth.MISSING_AUTHORIZATION_HEADER, ex.getMessage());
}
@Test
void classifiedUnconfiguredModeIs401() {
GraphqlApi api = api(AuthenticationType.API_KEY);
assertThrows(AppSyncTransportException.class, () -> middleware.authenticate(
Map.of("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request"),
api, info));
}
@Test
void sigV4WinsOverApiKeyAndDoesNotFallBack() {
GraphqlApi api = api(AuthenticationType.AWS_IAM);
AdditionalAuthenticationProvider extra = new AdditionalAuthenticationProvider();
extra.setAuthenticationType(AuthenticationType.API_KEY);
api.setAdditionalAuthenticationProviders(List.of(extra));
when(iamAuthValidator.validateRequest(any(), eq("api-1"), any())).thenReturn(Map.of("user", "test"));
AppSyncAuthContext ctx = middleware.authenticate(Map.of(
"x-api-key", "da2-abc",
"Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request"),
api, info);
assertEquals(AuthenticationType.AWS_IAM, ctx.authenticationType());
verify(apiKeyAuthValidator, never()).validate(any(), any());
}
@Test
void sigV4DoesNotFallBackToApiKeyWhenIamIsNotConfigured() {
GraphqlApi api = api(AuthenticationType.API_KEY);
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, () -> middleware.authenticate(Map.of(
"x-api-key", "da2-abc",
"Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request"),
api, info));
assertEquals(401, ex.getHttpStatus());
verify(apiKeyAuthValidator, never()).validate(any(), any());
}
@Test
void bearerJwtIsNotSentToLambda() {
GraphqlApi api = api(AuthenticationType.AMAZON_COGNITO_USER_POOLS);
api.setUserPoolConfig(Map.of("userPoolId", "pool", "awsRegion", "us-east-1"));
AdditionalAuthenticationProvider lambda = new AdditionalAuthenticationProvider();
lambda.setAuthenticationType(AuthenticationType.AWS_LAMBDA);
api.setAdditionalAuthenticationProviders(List.of(lambda));
Map<String, Object> claims = Map.of(
"sub", "s",
"iss", "https://cognito-idp.us-east-1.amazonaws.com/pool",
"exp", 9999999999L);
String jwt = JwtClaimsDecoder.encode(new java.util.HashMap<>(claims), new ObjectMapper());
when(cognitoAuthValidator.matchesProvider(any(), any())).thenReturn(true);
when(cognitoAuthValidator.validate(any(), any(), any())).thenReturn(Map.of("sub", "s"));
AppSyncAuthContext ctx = middleware.authenticate(Map.of("Authorization", "Bearer " + jwt), api, info);
assertEquals(AuthenticationType.AMAZON_COGNITO_USER_POOLS, ctx.authenticationType());
verify(lambdaAuthorizerValidator, never()).authorize(any(), any(), any(), any());
}
@Test
void opaqueTokenInvokesLambda() {
GraphqlApi api = api(AuthenticationType.AWS_LAMBDA);
api.setLambdaAuthorizerConfig(Map.of("authorizerUri", "fn"));
when(lambdaAuthorizerValidator.authorize(eq("api-1"), eq("ABC123"), any(), any()))
.thenReturn(new LambdaAuthorizerResult(true, List.of(), Map.of("apple", "green"), null, 10));
AppSyncAuthContext ctx = middleware.authenticate(Map.of("Authorization", "ABC123"), api, info);
assertEquals(AppSyncAuth.AUTH_TYPE_LAMBDA, ctx.authType());
assertEquals("green", ((Map<?, ?>) ctx.identity().get("resolverContext")).get("apple"));
}
private static GraphqlApi api(AuthenticationType type) {
GraphqlApi api = new GraphqlApi();
api.setApiId("api-1");
api.setAuthenticationType(type);
return api;
}
}
@@ -0,0 +1,265 @@
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,91 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CognitoAuthValidatorTest {
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
private final ObjectMapper mapper = new ObjectMapper();
private CognitoAuthValidator validator;
private Map<String, Object> config;
@BeforeEach
void setUp() {
validator = new CognitoAuthValidator(new JwtClaimsDecoder(mapper), Clock.fixed(NOW, ZoneOffset.UTC));
config = new HashMap<>();
config.put("userPoolId", "us-east-1_abc");
config.put("awsRegion", "us-east-1");
config.put("defaultAction", "ALLOW");
config.put("appIdClientRegex", "client-1");
}
@Test
void validJwtBuildsUsernameAndAuthTypeIdentity() {
Map<String, Object> claims = baseClaims();
claims.put("cognito:username", "alice");
Map<String, Object> identity = validator.validate("Bearer " + jwt(claims), config, List.of("127.0.0.1"));
assertEquals("alice", identity.get("username"));
assertEquals("abc", identity.get("sub"));
assertNull(identity.get("cognitoUserPoolId"));
}
@Test
void expiredJwtIs401() {
Map<String, Object> claims = baseClaims();
claims.put("exp", NOW.getEpochSecond() - 10);
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, List.of()));
}
@Test
void malformedTokenIs401() {
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer not-a-jwt", config, List.of()));
}
@Test
void missingSubIs401() {
Map<String, Object> claims = baseClaims();
claims.remove("sub");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, List.of()));
}
@Test
void groupsNullVsEmpty() {
Map<String, Object> missing = validator.validate("Bearer " + jwt(baseClaims()), config, List.of());
assertNull(missing.get("groups"));
Map<String, Object> emptyClaims = baseClaims();
emptyClaims.put("cognito:groups", List.of());
Map<String, Object> empty = validator.validate("Bearer " + jwt(emptyClaims), config, List.of());
assertEquals(List.of(), empty.get("groups"));
}
private Map<String, Object> baseClaims() {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", "abc");
claims.put("iss", "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc");
claims.put("aud", "client-1");
claims.put("exp", NOW.getEpochSecond() + 3600);
return claims;
}
private String jwt(Map<String, Object> claims) {
return JwtClaimsDecoder.encode(claims, mapper);
}
}
@@ -0,0 +1,58 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CredentialClassifierTest {
@Test
void sigV4WinsWhenBothHeadersPresent() {
ClassifiedMode mode = CredentialClassifier.classify(Map.of(
"x-api-key", "da2-abc",
"Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request"));
assertEquals(ClassifiedMode.AWS_IAM, mode);
}
@Test
void apiKeyWinsOverBearerWhenBothPresent() {
String jwt = "eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig";
ClassifiedMode mode = CredentialClassifier.classify(Map.of(
"x-api-key", "da2-abc",
"Authorization", "Bearer " + jwt));
assertEquals(ClassifiedMode.API_KEY, mode);
}
@Test
void sigV4ClassifiesAsIam() {
ClassifiedMode mode = CredentialClassifier.classify(Map.of(
"Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260205/us-east-1/appsync/aws4_request"));
assertEquals(ClassifiedMode.AWS_IAM, mode);
}
@Test
void bearerJwtClassifiesAsBearer() {
String jwt = "eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig";
ClassifiedMode mode = CredentialClassifier.classify(Map.of("Authorization", "Bearer " + jwt));
assertEquals(ClassifiedMode.BEARER_JWT, mode);
}
@Test
void opaqueAuthorizationClassifiesAsLambda() {
ClassifiedMode mode = CredentialClassifier.classify(Map.of("Authorization", "ABC123"));
assertEquals(ClassifiedMode.AWS_LAMBDA, mode);
}
@Test
void missingHeadersClassifyAsNone() {
assertEquals(ClassifiedMode.NONE, CredentialClassifier.classify(Map.of()));
}
@Test
void headerLookupIsCaseInsensitive() {
ClassifiedMode mode = CredentialClassifier.classify(Map.of("X-Api-Key", "da2-xyz"));
assertEquals(ClassifiedMode.API_KEY, mode);
}
}
@@ -0,0 +1,102 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class IamAuthValidatorTest {
private static final String ALLOW = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"appsync:GraphQL","Resource":"*"}]}
""";
private static final String DENY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"appsync:GraphQL","Resource":"*"}]}
""";
private static final String FIELD_DENY = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"appsync:GraphQL","Resource":"arn:aws:appsync:us-east-1:000000000000:apis/api-1/*"},
{"Effect":"Deny","Action":"appsync:GraphQL","Resource":"arn:aws:appsync:us-east-1:000000000000:apis/api-1/types/Query/fields/secret"}
]}
""";
@Mock
IamService iamService;
private IamAuthValidator validator;
private AuthRequestInfo info;
@BeforeEach
void setUp() {
validator = new IamAuthValidator(
new AccountResolver("000000000000"),
iamService,
new IamPolicyEvaluator(new ObjectMapper()));
info = new AuthRequestInfo("{ hello }", null, Map.of(), List.of("10.0.0.1"),
"req-1", "000000000000", "us-east-1", Map.of());
}
@Test
void knownAllowBuildsIdentity() {
when(iamService.resolveCallerContext("AKIAGOOD")).thenReturn(CallerContext.of(List.of(ALLOW)));
when(iamService.resolveCallerArn("AKIAGOOD"))
.thenReturn(Optional.of("arn:aws:iam::000000000000:user/alice"));
Map<String, Object> identity = validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=AKIAGOOD/20260205/us-east-1/appsync/aws4_request",
"api-1", info);
assertEquals("AKIAGOOD", identity.get("user"));
assertEquals("alice", identity.get("username"));
assertInstanceOf(List.class, identity.get("sourceIp"));
assertEquals(List.of("10.0.0.1"), identity.get("sourceIp"));
}
@Test
void knownRequestDenyThrows401() {
when(iamService.resolveCallerContext("AKIDDENY")).thenReturn(CallerContext.of(List.of(DENY)));
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=AKIDDENY/20260205/us-east-1/appsync/aws4_request",
"api-1", info));
assertEquals(401, ex.getHttpStatus());
}
@Test
void unknownTestKeyIsAllowed() {
Map<String, Object> identity = validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request",
"api-1", info);
assertEquals("test", identity.get("user"));
}
@Test
void fieldArnDenyDetected() {
when(iamService.resolveCallerContext("AKIAGOOD")).thenReturn(CallerContext.of(List.of(FIELD_DENY)));
String fieldArn = IamAuthValidator.fieldArn("us-east-1", "000000000000", "api-1", "Query", "secret");
assertTrue(validator.isFieldDenied("AKIAGOOD", fieldArn));
assertFalse(validator.isFieldDenied("AKIAGOOD",
IamAuthValidator.fieldArn("us-east-1", "000000000000", "api-1", "Query", "hello")));
assertFalse(validator.isFieldDenied("test", fieldArn));
}
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 IdentityBuilderTest {
@Test
void iamIdentityIncludesUserAndSourceIpArray() {
Map<String, Object> identity = IdentityBuilder.iam(
"000000000000", "AKIATEST", "alice", "arn:aws:iam::000000000000:user/alice", List.of("10.0.0.1"));
assertEquals("AKIATEST", identity.get("user"));
assertEquals("alice", identity.get("username"));
assertEquals("arn:aws:iam::000000000000:user/alice", identity.get("userArn"));
assertInstanceOf(List.class, identity.get("sourceIp"));
assertEquals(List.of("10.0.0.1"), identity.get("sourceIp"));
assertEquals("", identity.get("cognitoIdentityPoolId"));
}
@Test
void cognitoGroupsNullWhenClaimMissing() {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", "abc");
claims.put("iss", "https://cognito");
claims.put("cognito:username", "bob");
Map<String, Object> identity = IdentityBuilder.cognito(claims, List.of("127.0.0.1"), "ALLOW");
assertNull(identity.get("groups"));
assertEquals("bob", identity.get("username"));
assertTrue(!identity.containsKey("cognitoUserPoolId"));
assertInstanceOf(List.class, identity.get("sourceIp"));
}
@Test
void cognitoGroupsEmptyListWhenClaimEmpty() {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", "abc");
claims.put("cognito:groups", List.of());
Map<String, Object> identity = IdentityBuilder.cognito(claims, List.of(), "DENY");
assertEquals(List.of(), identity.get("groups"));
}
@Test
void oidcIdentityHasSubIssuerClaims() {
Map<String, Object> claims = Map.of("sub", "s1", "iss", "https://issuer");
Map<String, Object> identity = IdentityBuilder.oidc(claims);
assertEquals("s1", identity.get("sub"));
assertEquals("https://issuer", identity.get("issuer"));
assertEquals(claims, identity.get("claims"));
assertTrue(!identity.containsKey("sourceIp"));
assertEquals(3, identity.size());
}
@Test
void lambdaIdentityIsResolverContextOnly() {
Map<String, Object> identity = IdentityBuilder.lambda(Map.of("apple", "green"));
assertEquals(Map.of("apple", "green"), identity.get("resolverContext"));
assertEquals(1, identity.size());
}
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LambdaAuthorizerCacheTest {
@Test
void cacheHitReturnsSameResultWithinTtl() {
Clock clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC);
LambdaAuthorizerCache cache = new LambdaAuthorizerCache(clock);
LambdaAuthorizerResult result = new LambdaAuthorizerResult(
true, List.of("Query.hello"), Map.of("apple", "green"), 10, 100);
cache.put("api-1", "tok", result, 30);
assertEquals(result.deniedFields(), cache.get("api-1", "tok").orElseThrow().deniedFields());
assertEquals("green", cache.get("api-1", "tok").orElseThrow().resolverContext().get("apple"));
}
@Test
void oversizedResponseIsNotCached() {
LambdaAuthorizerCache cache = new LambdaAuthorizerCache();
LambdaAuthorizerResult result = new LambdaAuthorizerResult(
true, List.of(), Map.of(), 10, LambdaAuthorizerCache.MAX_CACHEABLE_BYTES);
cache.put("api-1", "tok", result, 30);
assertTrue(cache.get("api-1", "tok").isEmpty());
}
@Test
void ttlOverrideZeroDoesNotCache() {
LambdaAuthorizerCache cache = new LambdaAuthorizerCache();
LambdaAuthorizerResult result = new LambdaAuthorizerResult(true, List.of(), Map.of(), 0, 10);
cache.put("api-1", "tok", result, 0);
assertTrue(cache.get("api-1", "tok").isEmpty());
}
@Test
void expiredEntryIsMiss() {
MutableClock clock = new MutableClock(Instant.parse("2026-01-01T00:00:00Z"));
LambdaAuthorizerCache cache = new LambdaAuthorizerCache(clock);
cache.put("api-1", "tok", new LambdaAuthorizerResult(true, List.of(), Map.of(), 5, 10), 5);
clock.advance(Duration.ofSeconds(6));
assertTrue(cache.get("api-1", "tok").isEmpty());
}
private static final class MutableClock extends Clock {
private Instant instant;
private MutableClock(Instant instant) {
this.instant = instant;
}
void advance(Duration duration) {
instant = instant.plus(duration);
}
@Override public ZoneOffset getZone() { return ZoneOffset.UTC; }
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
@Override public Instant instant() { return instant; }
}
}
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class LambdaAuthorizerValidatorTest {
@Mock
LambdaService lambdaService;
private final ObjectMapper mapper = new ObjectMapper();
private LambdaAuthorizerValidator validator;
private AuthRequestInfo info;
private Map<String, Object> config;
@BeforeEach
void setUp() {
validator = new LambdaAuthorizerValidator(lambdaService, new LambdaAuthorizerCache(), mapper);
info = new AuthRequestInfo("{ hello }", "GetHello", Map.of("id", "1"),
List.of(), "req-1", "000000000000", "us-east-1", Map.of("authorization", "tok"));
config = Map.of(
"authorizerUri", "arn:aws:lambda:us-east-1:000000000000:function:authz",
"authorizerResultTtlInSeconds", 30);
}
@Test
void authorizedWithFlatResolverContext() throws Exception {
when(lambdaService.invoke(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:authz"),
any(), eq(InvocationType.RequestResponse)))
.thenReturn(invoke("{\"isAuthorized\":true,\"resolverContext\":{\"apple\":\"green\"}}"));
LambdaAuthorizerResult result = validator.authorize("api-1", "tok", config, info);
assertTrue(result.authorized());
assertEquals("green", result.resolverContext().get("apple"));
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invoke(eq("us-east-1"), any(), payload.capture(), eq(InvocationType.RequestResponse));
String event = new String(payload.getValue(), StandardCharsets.UTF_8);
assertTrue(event.contains("\"authorizationToken\":\"tok\""));
assertTrue(event.contains("\"queryString\":\"{ hello }\""));
assertFalse(event.contains("policyDocument"));
}
@Test
void apiGatewayPolicyWithoutIsAuthorizedIs401() {
when(lambdaService.invoke(any(), any(), any(), any()))
.thenReturn(invoke("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\"}}"));
assertThrows(AppSyncTransportException.class,
() -> validator.authorize("api-1", "tok", config, info));
}
@Test
void regexDenyDoesNotInvokeLambda() {
Map<String, Object> withRegex = Map.of(
"authorizerUri", "arn:aws:lambda:us-east-1:000000000000:function:authz",
"identityValidationExpression", "^ok-.*");
assertThrows(AppSyncTransportException.class,
() -> validator.authorize("api-1", "bad-token", withRegex, info));
verify(lambdaService, times(0)).invoke(any(), any(), any(), any());
}
@Test
void nestedResolverContextKeysDropped() {
when(lambdaService.invoke(any(), any(), any(), any()))
.thenReturn(invoke("{\"isAuthorized\":true,\"resolverContext\":{\"apple\":\"green\",\"nested\":{\"x\":1}}}"));
LambdaAuthorizerResult result = validator.authorize("api-1", "tok", config, info);
assertEquals("green", result.resolverContext().get("apple"));
assertFalse(result.resolverContext().containsKey("nested"));
}
@Test
void emptyObjectIs401() {
when(lambdaService.invoke(any(), any(), any(), any())).thenReturn(invoke("{}"));
assertThrows(AppSyncTransportException.class,
() -> validator.authorize("api-1", "tok", config, info));
}
@Test
void cacheHitSkipsSecondInvoke() {
when(lambdaService.invoke(any(), any(), any(), any()))
.thenReturn(invoke("{\"isAuthorized\":true,\"resolverContext\":{\"k\":\"v\"}}"));
validator.authorize("api-1", "tok", config, info);
validator.authorize("api-1", "tok", config, info);
verify(lambdaService, times(1)).invoke(any(), any(), any(), any());
}
@Test
void ttlOverrideZeroInvokesTwice() {
when(lambdaService.invoke(any(), any(), any(), any()))
.thenReturn(invoke("{\"isAuthorized\":true,\"ttlOverride\":0}"));
validator.authorize("api-1", "tok", config, info);
validator.authorize("api-1", "tok", config, info);
verify(lambdaService, times(2)).invoke(any(), any(), any(), any());
}
private static InvokeResult invoke(String json) {
return new InvokeResult(200, null, json.getBytes(StandardCharsets.UTF_8), "", "id");
}
}
@@ -0,0 +1,95 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class OidcAuthValidatorTest {
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
private final ObjectMapper mapper = new ObjectMapper();
private OidcAuthValidator validator;
@BeforeEach
void setUp() {
validator = new OidcAuthValidator(new JwtClaimsDecoder(mapper), Clock.fixed(NOW, ZoneOffset.UTC));
}
@Test
void soleModeSkipsIssuer() {
Map<String, Object> config = config("https://configured-issuer", "my-client");
Map<String, Object> claims = baseClaims("https://other-issuer", "my-client");
Map<String, Object> identity = validator.validate("Bearer " + jwt(claims), config, true);
assertEquals("sub-1", identity.get("sub"));
assertEquals("https://other-issuer", identity.get("issuer"));
assertTrue(!identity.containsKey("sourceIp"));
}
@Test
void multiModeEnforcesIssuer() {
Map<String, Object> config = config("https://configured-issuer", "my-client");
Map<String, Object> claims = baseClaims("https://other-issuer", "my-client");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, false));
}
@Test
void iatTtlExceededIs401() {
Map<String, Object> config = config("https://issuer", "my-client");
config.put("iatTTL", 60);
Map<String, Object> claims = baseClaims("https://issuer", "my-client");
claims.put("iat", NOW.getEpochSecond() - 120);
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, true));
}
@Test
void clientIdRegexMatchesAzp() {
Map<String, Object> config = config("https://issuer", "client-.*");
Map<String, Object> claims = baseClaims("https://issuer", "other");
claims.remove("aud");
claims.put("azp", "client-99");
Map<String, Object> identity = validator.validate("Bearer " + jwt(claims), config, true);
assertEquals("sub-1", identity.get("sub"));
}
@Test
void clientIdMismatchIs401() {
Map<String, Object> config = config("https://issuer", "client-1");
Map<String, Object> claims = baseClaims("https://issuer", "nope");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, true));
}
private Map<String, Object> config(String issuer, String clientId) {
Map<String, Object> config = new HashMap<>();
config.put("issuer", issuer);
config.put("clientId", clientId);
return config;
}
private Map<String, Object> baseClaims(String iss, String aud) {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", "sub-1");
claims.put("iss", iss);
claims.put("aud", aud);
claims.put("iat", NOW.getEpochSecond() - 10);
claims.put("exp", NOW.getEpochSecond() + 3600);
return claims;
}
private String jwt(Map<String, Object> claims) {
return JwtClaimsDecoder.encode(claims, mapper);
}
}