diff --git a/docs/services/appsync.md b/docs/services/appsync.md index b8a879d1d5..3c617d6e3a 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -238,6 +238,7 @@ Responses are `application/json` with AWS AppSync wire shapes (`data` / `errors[ | API exists but no executable schema (incl. PROCESSING) | **502** | `GraphQLSchemaException` — `No schema definition exists.` + `x-amzn-errortype` | | Unexpected failure | 500 | `InternalFailure` | | Missing/invalid/expired credentials, unconfigured mode, Lambda deny | **401** | `UnauthorizedException` — GraphQL does not run; `x-amzn-errortype` is set. Missing headers use message `Missing authorization header`. | +| `AWS_IAM` with an unknown access key, or a session token that does not fit the key | **403** | `UnrecognizedClientException`: `The security token included in the request is invalid`, ending with a period only when no token or an empty one came | | Field directive mismatch, Cognito group miss, Lambda `deniedFields`, IAM field DENY | **200** | Field is `null` and `errors[]` contains `Unauthorized` — `Not Authorized to access {field} on type {type}` (no `x-amzn-errortype`) | **Evidence for data-plane statuses** (empty/`[]`/`{}` → 400; missing schema → 502): AppSync team sample in [graphql/graphql-over-http#81](https://github.com/graphql/graphql-over-http/issues/81) (@robzhu). The management API Reference lists `GraphQLSchemaException` as HTTP 400 for “schema not valid” on management operations — a different surface than the GraphQL execute data plane. @@ -248,7 +249,7 @@ Request auth runs after Content-Type and body parse and after API lookup (unknow Headers are classified by **shape** (not primary-then-fallback). If both `x-api-key` and SigV4 `Authorization` are present, **SigV4 wins**. AppSync does not fall back to the API key when IAM validation fails. -Missing required auth headers return HTTP **401** `UnauthorizedException` with message `Missing authorization header`. Invalid or expired credentials that are present still return 401 with `You are not authorized to make this call.` +Missing required auth headers return HTTP **401** `UnauthorizedException` with message `Missing authorization header`. Invalid or expired credentials that are present still return 401 with `You are not authorized to make this call.`, except the 403 `AWS_IAM` cases in the table above. | Header shape | Mode | |---|---| @@ -262,7 +263,7 @@ Configured modes are the API default `authenticationType` plus `additionalAuthen | Mode | Emulator notes | |---|---| | API_KEY | Lookup by `ApiKey.id`, which is the key value (`da2-…`). Identity is absent (not `{}`). Default key expiry is 7 days when `expires` is omitted; stored `expires` is rounded down to the nearest hour. Create/UpdateApiKey require `expires` between 1 and 365 days from now (`ApiKeyValidityOutOfBoundsException`, 400). `deletes` is `expires` plus 60 days. | -| AWS_IAM | Verifies a real header-signed SigV4 request (`appsync` service, fixed `/v1/apis/{apiId}/graphql` canonical path, 5-minute clock skew): the `Credential=` access key must resolve to a secret via `IamService`, and the signature must match. The legacy `test`/`test` pair is still emulator ALLOW, but it must be signed with secret `test` like any other key, and it is not a bypass. A temporary (`ASIA...`) credential must also present the `X-Amz-Security-Token` header matching the one issued for it. An unknown or unsigned key is always 401 and never becomes the account-root identity. Known keys additionally evaluate `appsync:GraphQL`. | +| AWS_IAM | Verifies a real header-signed SigV4 request (`appsync` service, fixed `/v1/apis/{apiId}/graphql` canonical path, 5-minute clock skew): the `Credential=` access key must resolve to a secret via `IamService`, and the signature must match. The legacy `test`/`test` pair is still emulator ALLOW, but it must be signed with secret `test` like any other key, and it is not a bypass. A temporary (`ASIA...`) credential must also present the `X-Amz-Security-Token` header issued with it, and a long-term key must present none, as on AWS. The `test` key takes any token. An unknown key is 403 and an unsigned one 401, and neither becomes the account-root identity. Known keys additionally evaluate `appsync:GraphQL`. | | Cognito / OIDC | JWT signature is verified, not just decoded. Cognito checks the token against the issuing user pool's own RS256 signing key (`alg`, `kid`, issuer, audience/`clientId`, expiry); OIDC checks it against the configured issuer's published JWKS (via OIDC discovery), the same way the HTTP API JWT authorizer does. Both fail closed: an unreachable issuer, unsupported algorithm (including `none`), unmatched `kid`, or bad signature is 401. OIDC as the sole mode still skips the token's own `iss` claim check, but the signature is always verified against the configured issuer's keys. OIDC identity is `{sub, issuer, claims}` (no `sourceIp`). | | Lambda | AppSync `isAuthorized` contract via `LambdaService.invoke` (not an API Gateway policy document). | diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuth.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuth.java index 557c406daf..e264a06707 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuth.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AppSyncAuth.java @@ -8,6 +8,8 @@ public final class AppSyncAuth { 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 final String UNRECOGNIZED_CLIENT_TYPE = "UnrecognizedClientException"; + public static final String INVALID_SECURITY_TOKEN = "The security token included in the request is invalid"; public static String fieldUnauthorizedMessage(String fieldName, String typeName) { return "Not Authorized to access " + fieldName + " on type " + typeName; @@ -26,6 +28,16 @@ public final class AppSyncAuth { return new AppSyncTransportException(401, UNAUTHORIZED_TYPE, UNAUTHORIZED_MESSAGE); } + /** An access key AppSync does not know, a temporary key with no session token, or an empty token. */ + public static AppSyncTransportException unrecognizedClient() { + return new AppSyncTransportException(403, UNRECOGNIZED_CLIENT_TYPE, INVALID_SECURITY_TOKEN + "."); + } + + /** A session token that does not fit the key. AWS drops the period here. */ + public static AppSyncTransportException invalidSessionToken() { + return new AppSyncTransportException(403, UNRECOGNIZED_CLIENT_TYPE, INVALID_SECURITY_TOKEN); + } + public static AppSyncTransportException missingAuthorizationHeader() { return new AppSyncTransportException(401, UNAUTHORIZED_TYPE, MISSING_AUTHORIZATION_HEADER); } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java index 4e5c4974d8..eb0494d8d4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.core.common.auth.CredentialScope; +import io.github.hectorvent.floci.core.common.auth.SessionTokenCheck; import io.github.hectorvent.floci.core.common.auth.SigV4AuthorizationHeader; import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator; import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException; @@ -124,7 +125,7 @@ public class IamAuthValidator { if (secretKey == null) { LOG.debugv("AppSync SigV4 request references unregistered access key={0}", SigV4RequestValidator.sanitizeForLog(accessKeyId)); - throw AppSyncAuth.unauthorized(); + throw AppSyncAuth.unrecognizedClient(); } checkSessionToken(accessKeyId, info.requestHeaders()); try { @@ -166,40 +167,19 @@ public class IamAuthValidator { return iamService.findSecretKey(accessKeyId).orElse(null); } - /** - * Rejects a temporary ({@code ASIA...}) credential that does not present the session token - * Floci issued with it. Mirrors {@code ExecuteApiSigV4Authorizer.checkSessionToken}: a matching - * secret alone is not the whole credential, since AWS requires the session token on every - * request made with temporary credentials to confirm it is live and genuinely STS-issued. - * - *

The token is compared against the value recorded at mint time, not merely required to be - * present, so a fabricated token is rejected along with a missing one. A session recorded - * before Floci tracked tokens has no issued value to compare against ({@code findSessionToken} - * is empty there), so presence is all that can be demanded of it: rejecting that case would - * lock out an otherwise valid credential. - * - *

The token does not need to ride in {@code SignedHeaders}: comparing it against the issued - * value binds it regardless of where it rode, the same way the execute-api authorizer does. - */ + /** Rejects a session token that does not fit the access key. The local {@code test} key takes any token. */ private void checkSessionToken(String accessKeyId, Map requestHeaders) { - if (!IamService.isTemporaryAccessKey(accessKeyId)) { + if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) { return; } - String presented = header(requestHeaders, SECURITY_TOKEN); - if (isBlank(presented)) { - LOG.debugv("AppSync SigV4 request uses temporary credential accessKey={0} with no {1}", - SigV4RequestValidator.sanitizeForLog(accessKeyId), SECURITY_TOKEN); - throw AppSyncAuth.unauthorized(); - } - String issued = iamService.findSessionToken(accessKeyId).orElse(null); - if (issued == null) { - return; - } - if (!MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8), - presented.getBytes(StandardCharsets.UTF_8))) { - LOG.debugv("AppSync SigV4 request presents a session token that does not match the one" - + " issued for accessKey={0}", SigV4RequestValidator.sanitizeForLog(accessKeyId)); - throw AppSyncAuth.unauthorized(); + String presented = hasHeader(requestHeaders, SECURITY_TOKEN) ? header(requestHeaders, SECURITY_TOKEN) : null; + AppSyncTransportException refusal = switch (SessionTokenCheck.of(iamService, accessKeyId, presented)) { + case VALID -> null; + case MISSING -> AppSyncAuth.unrecognizedClient(); + case INVALID -> AppSyncAuth.invalidSessionToken(); + }; + if (refusal != null) { + throw refusal; } } @@ -253,6 +233,10 @@ public class IamAuthValidator { return ""; } + private static boolean hasHeader(Map headers, String name) { + return headers != null && headers.keySet().stream().anyMatch(name::equalsIgnoreCase); + } + private static boolean isBlank(String value) { return value == null || value.isBlank(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java index 908c636f3f..c4bb323e1d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java @@ -2,18 +2,25 @@ 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.EnforcementFixtures; +import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials; +import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.github.hectorvent.floci.testing.SidecarContainersProfile; import io.github.hectorvent.floci.testutil.AppSyncRequestSigner; +import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.RestAssured; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import java.net.URI; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; @@ -36,6 +43,12 @@ class AppSyncAuthIntegrationTest { @Inject ResolvedServiceCatalog catalog; + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @TestHTTPResource("/") + URI baseUri; + @BeforeAll static void configureRestAssured() { SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.graphql-image"); @@ -210,6 +223,42 @@ class AppSyncAuthIntegrationTest { .body("errors[0].path", equalTo(java.util.List.of("hello"))); } + @Test + void longTermKeyWithASessionTokenIsRefused() throws Exception { + String apiId = given() + .header("Authorization", MGMT_AUTH) + .contentType("application/json") + .body(""" + {"name": "token-%s", "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); + UserCredentials user = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), + EnforcementFixtures.auth("test", "iam"), "appsync-token-user"); + + String body = "{\"query\":\"{ hello }\"}"; + Map headers = new LinkedHashMap<>(AppSyncRequestSigner.signedHeaders(apiId, + "localhost:" + RestAssured.port, body, user.accessKeyId(), user.secretAccessKey(), "us-east-1", + Instant.now())); + headers.put("X-Amz-Security-Token", "bogus"); + given() + .contentType("application/json") + .headers(headers) + .body(body) + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(403) + .header("x-amzn-errortype", equalTo("UnrecognizedClientException")) + .body("errors[0].errorType", equalTo("UnrecognizedClientException")) + .body("errors[0].message", equalTo("The security token included in the request is invalid")); + } + @Test void additionalModeIamCanIntrospect() throws Exception { String apiId = given() diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java index 867bbc2dcf..7a30950534 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidatorTest.java @@ -130,9 +130,7 @@ class IamAuthValidatorTest { Map signed = AppSyncRequestSigner.signedHeaders( "api-1", HOST, BODY, "AKIAUNKNOWN", "whatever-secret", REGION, Instant.now()); - AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, - () -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed))); - assertEquals(401, ex.getHttpStatus()); + assertRefused(signed, "The security token included in the request is invalid."); } @Test @@ -191,25 +189,44 @@ class IamAuthValidatorTest { } @Test - void temporaryCredentialSignedButNoSessionTokenIs401() throws Exception { + void temporaryCredentialSignedButNoSessionTokenIsRefused() throws Exception { when(iamService.findSecretKey("ASIANOTOKEN")).thenReturn(Optional.of("session-secret")); Map signed = AppSyncRequestSigner.signedHeaders( "api-1", HOST, BODY, "ASIANOTOKEN", "session-secret", REGION, Instant.now()); - AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, - () -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed))); - assertEquals(401, ex.getHttpStatus()); + assertRefused(signed, "The security token included in the request is invalid."); } @Test - void temporaryCredentialWithMismatchedSessionTokenIs401() throws Exception { + void temporaryCredentialWithMismatchedSessionTokenIsRefused() throws Exception { when(iamService.findSecretKey("ASIAFORGED")).thenReturn(Optional.of("session-secret")); when(iamService.findSessionToken("ASIAFORGED")).thenReturn(Optional.of("issued-token")); Map signed = signedWithSessionToken("ASIAFORGED", "session-secret", "forged-token"); + assertRefused(signed, "The security token included in the request is invalid"); + } + + @Test + void longTermKeyWithASessionTokenIsRefused() throws Exception { + assertRefused(signedWithSessionToken("AKIAGOOD", "good-secret", "bogus"), + "The security token included in the request is invalid"); + assertRefused(signedWithSessionToken("AKIAGOOD", "good-secret", ""), + "The security token included in the request is invalid."); + } + + @Test + void legacyTestKeyTakesAnySessionToken() throws Exception { + Map signed = signedWithSessionToken("test", "test", "bogus"); + + assertEquals("test", validator.validateRequest(authorization(signed), "api-1", infoWith(signed)).get("user")); + } + + private void assertRefused(Map signed, String message) { AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, () -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed))); - assertEquals(401, ex.getHttpStatus()); + assertEquals(403, ex.getHttpStatus()); + assertEquals("UnrecognizedClientException", ex.getErrorType()); + assertEquals(message, ex.getMessage()); } @Test