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

@@ -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; }