From 704f895982987a499f0d9b67eff3d04493d9ec27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Ziel?= <159726064+danielvanza@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:48:09 +0100 Subject: [PATCH] fix(appsync): accept a bare Cognito or OIDC JWT in the Authorization header (#8399) --- docs/services/appsync.md | 2 +- .../appsync/graphql/auth/AuthMiddleware.java | 24 +++++- .../graphql/auth/CredentialClassifier.java | 29 ++++++- .../graphql/auth/AuthMiddlewareTest.java | 77 +++++++++++++++++-- .../auth/CredentialClassifierTest.java | 11 +++ 5 files changed, 132 insertions(+), 11 deletions(-) diff --git a/docs/services/appsync.md b/docs/services/appsync.md index e4aac6d768..5d1db13d95 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -258,7 +258,7 @@ Missing required auth headers return HTTP **401** `UnauthorizedException` with m | `Authorization` starts with `AWS4-HMAC-SHA256` | `AWS_IAM` (wins over `x-api-key` if both are present) | | `x-api-key` present | `API_KEY` | | `Authorization: Bearer ` | Cognito and/or OIDC (matched by `iss` / `aud` or `azp`) | -| Other `Authorization` | `AWS_LAMBDA` | +| Other `Authorization` | `AWS_LAMBDA`, except that a bare JWT (three dot-separated segments, no `Bearer ` prefix) is handled like `Bearer ` when Cognito or OIDC is configured: a token they reject returns 401 and is not sent to `AWS_LAMBDA` | Configured modes are the API default `authenticationType` plus `additionalAuthenticationProviders`. A classified mode that is not configured returns 401. diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddleware.java b/src/main/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddleware.java index d7de774706..4c754e6258 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddleware.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddleware.java @@ -45,10 +45,32 @@ public class AuthMiddleware { case API_KEY -> authenticateApiKey(headers, api, configured, info); case AWS_IAM -> authenticateIam(headers, api, configured, info); case BEARER_JWT -> authenticateBearer(headers, api, configured, info); - case AWS_LAMBDA -> authenticateLambda(headers, api, configured, info); + case AWS_LAMBDA -> authenticateBareJwtOrLambda(headers, api, configured, info); }; } + /** + * AppSync takes the JWT itself as the {@code Authorization} value for Cognito and OIDC APIs, the + * {@code Bearer } scheme being optional. A bare JWT on such an API is handled like {@code Bearer }, + * since AppSync does not accept an OIDC token as the Lambda authorization token. + */ + private AppSyncAuthContext authenticateBareJwtOrLambda( + Map headers, GraphqlApi api, Set configured, AuthRequestInfo info) { + boolean bearerModes = configured.contains(AuthenticationType.AMAZON_COGNITO_USER_POOLS) + || configured.contains(AuthenticationType.OPENID_CONNECT); + String authorization = CredentialClassifier.header(headers, "authorization"); + if (bearerModes && isDecodableBareJwt(authorization)) { + return authenticateBearer(headers, api, configured, info); + } + return authenticateLambda(headers, api, configured, info); + } + + private boolean isDecodableBareJwt(String authorization) { + return CredentialClassifier.isBareJwt(authorization) + && jwtClaimsDecoder.decodeHeader(authorization).isPresent() + && jwtClaimsDecoder.decode(authorization).isPresent(); + } + private AppSyncAuthContext authenticateApiKey( Map headers, GraphqlApi api, Set configured, AuthRequestInfo info) { if (!configured.contains(AuthenticationType.API_KEY)) { diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifier.java b/src/main/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifier.java index d840687649..ceef1abfbd 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifier.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifier.java @@ -47,7 +47,34 @@ public final class CredentialClassifier { if (authorization.length() < 7 || !authorization.regionMatches(true, 0, "Bearer ", 0, 7)) { return false; } - String token = authorization.substring(7).trim(); + return hasJwtShape(authorization.substring(7)); + } + + /** + * True when the value is three dot-separated base64url segments, so a Lambda token wrapped with + * a prefix or suffix (for example {@code prefix:}) is not taken for a JWT. + */ + static boolean isBareJwt(String value) { + if (!hasJwtShape(value)) { + return false; + } + String token = value.trim(); + for (int i = 0; i < token.length(); i++) { + char c = token.charAt(i); + boolean base64Url = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == '-' || c == '_'; + if (c != '.' && !base64Url) { + return false; + } + } + return true; + } + + private static boolean hasJwtShape(String value) { + if (value == null) { + return false; + } + String token = value.trim(); int first = token.indexOf('.'); int second = token.indexOf('.', first + 1); if (first <= 0 || second <= first + 1) { diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddlewareTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddlewareTest.java index 2d6730dafc..0b896323d7 100644 --- a/src/test/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddlewareTest.java +++ b/src/test/java/io/floci/aws/services/appsync/graphql/auth/AuthMiddlewareTest.java @@ -9,6 +9,8 @@ import io.floci.aws.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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -103,13 +105,10 @@ class AuthMiddlewareTest { 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)); + @ParameterizedTest + @ValueSource(strings = {"Bearer ", ""}) + void jwtIsNotSentToLambda(String scheme) { + GraphqlApi api = cognitoAndLambdaApi(); Map claims = Map.of( "sub", "s", @@ -119,12 +118,65 @@ class AuthMiddlewareTest { 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); + AppSyncAuthContext ctx = middleware.authenticate(Map.of("Authorization", scheme + jwt), api, info); assertEquals(AuthenticationType.AMAZON_COGNITO_USER_POOLS, ctx.authenticationType()); verify(lambdaAuthorizerValidator, never()).authorize(any(), any(), any(), any()); } + @Test + void bareJwtWithoutBearerPrefixAuthenticatesAgainstCognito() { + GraphqlApi api = api(AuthenticationType.AMAZON_COGNITO_USER_POOLS); + api.setUserPoolConfig(Map.of("userPoolId", "pool", "awsRegion", "us-east-1")); + String jwt = JwtClaimsDecoder.encode(new HashMap<>(Map.of("sub", "s", "exp", 9999999999L)), 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", jwt), api, info); + + assertEquals(AuthenticationType.AMAZON_COGNITO_USER_POOLS, ctx.authenticationType()); + verify(lambdaAuthorizerValidator, never()).authorize(any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(strings = {"Bearer ", ""}) + void rejectedJwtIs401AndNotSentToLambda(String scheme) { + GraphqlApi api = cognitoAndLambdaApi(); + String jwt = JwtClaimsDecoder.encode(new HashMap<>(Map.of("sub", "s")), new ObjectMapper()); + + AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, + () -> middleware.authenticate(Map.of("Authorization", scheme + jwt), api, info)); + + assertEquals(401, ex.getHttpStatus()); + verify(lambdaAuthorizerValidator, never()).authorize(any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(strings = {"prefix:%s", "%s:suffix"}) + void wrappedJwtStillReachesLambdaWhenCognitoIsConfigured(String wrapper) { + GraphqlApi api = cognitoAndLambdaApi(); + String token = wrapper.formatted(JwtClaimsDecoder.encode(new HashMap<>(Map.of("sub", "s")), new ObjectMapper())); + when(lambdaAuthorizerValidator.authorize(eq("api-1"), eq(token), any(), any())) + .thenReturn(new LambdaAuthorizerResult(true, List.of(), Map.of(), null, 10)); + + AppSyncAuthContext ctx = middleware.authenticate(Map.of("Authorization", token), api, info); + + assertEquals(AppSyncAuth.AUTH_TYPE_LAMBDA, ctx.authType()); + } + + @Test + void jwtWithRandomAlphanumericPrefixStillReachesLambda() { + GraphqlApi api = cognitoAndLambdaApi(); + String token = "x7f" + JwtClaimsDecoder.encode(new HashMap<>(Map.of("sub", "s")), new ObjectMapper()); + when(lambdaAuthorizerValidator.authorize(eq("api-1"), eq(token), any(), any())) + .thenReturn(new LambdaAuthorizerResult(true, List.of(), Map.of(), null, 10)); + + AppSyncAuthContext ctx = middleware.authenticate(Map.of("Authorization", token), api, info); + + assertEquals(AppSyncAuth.AUTH_TYPE_LAMBDA, ctx.authType()); + verify(cognitoAuthValidator, never()).validate(any(), any(), any()); + } + @Test void opaqueTokenInvokesLambda() { GraphqlApi api = api(AuthenticationType.AWS_LAMBDA); @@ -138,6 +190,15 @@ class AuthMiddlewareTest { assertEquals("green", ((Map) ctx.identity().get("resolverContext")).get("apple")); } + private static GraphqlApi cognitoAndLambdaApi() { + 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)); + return api; + } + private static GraphqlApi api(AuthenticationType type) { GraphqlApi api = new GraphqlApi(); api.setApiId("api-1"); diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifierTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifierTest.java index f7698b3c1a..5f653999ee 100644 --- a/src/test/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifierTest.java +++ b/src/test/java/io/floci/aws/services/appsync/graphql/auth/CredentialClassifierTest.java @@ -5,6 +5,8 @@ import org.junit.jupiter.api.Test; 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.assertTrue; class CredentialClassifierTest { @@ -39,6 +41,15 @@ class CredentialClassifierTest { assertEquals(ClassifiedMode.BEARER_JWT, mode); } + @Test + void bareJwtIsRecognisedButWrappedTokensAreNot() { + String jwt = "eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig"; + assertTrue(CredentialClassifier.isBareJwt(jwt)); + assertFalse(CredentialClassifier.isBareJwt("prefix:" + jwt)); + assertFalse(CredentialClassifier.isBareJwt(jwt + ":suffix")); + assertFalse(CredentialClassifier.isBareJwt("ABC123")); + } + @Test void opaqueAuthorizationClassifiesAsLambda() { ClassifiedMode mode = CredentialClassifier.classify(Map.of("Authorization", "ABC123"));