mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
74da157681
commit
3f12428d97
46 files changed
+3564
-64
No files matched your search
+297
@@ -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
-11
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -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"));
|
||||
}
|
||||
}
|
||||
+47
-4
@@ -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");
|
||||
}
|
||||
}
|
||||
+34
@@ -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"));
|
||||
}
|
||||
}
|
||||
+36
@@ -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"));
|
||||
}
|
||||
}
|
||||
+12
@@ -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);
|
||||
}
|
||||
}
|
||||
+44
@@ -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());
|
||||
}
|
||||
}
|
||||
+146
@@ -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;
|
||||
}
|
||||
}
|
||||
+265
@@ -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");
|
||||
}
|
||||
}
|
||||
+91
@@ -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);
|
||||
}
|
||||
}
|
||||
+58
@@ -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);
|
||||
}
|
||||
}
|
||||
+102
@@ -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));
|
||||
}
|
||||
}
|
||||
+67
@@ -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());
|
||||
}
|
||||
}
|
||||
+67
@@ -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; }
|
||||
}
|
||||
}
|
||||
+124
@@ -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");
|
||||
}
|
||||
}
|
||||
+95
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user