mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(appsync): accept a bare Cognito or OIDC JWT in the Authorization header (#8399)
This commit is contained in:
1 parent
c3e9dbad96
commit
704f895982
5 files changed
+132
-11
No files matched your search
@@ -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 <jwt>` | 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 <jwt>` 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.
|
||||
|
||||
|
||||
@@ -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 <jwt>},
|
||||
* since AppSync does not accept an OIDC token as the Lambda authorization token.
|
||||
*/
|
||||
private AppSyncAuthContext authenticateBareJwtOrLambda(
|
||||
Map<String, String> headers, GraphqlApi api, Set<AuthenticationType> 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<String, String> headers, GraphqlApi api, Set<AuthenticationType> configured, AuthRequestInfo info) {
|
||||
if (!configured.contains(AuthenticationType.API_KEY)) {
|
||||
|
||||
@@ -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:<jwt>}) 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) {
|
||||
|
||||
@@ -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<String, Object> 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");
|
||||
|
||||
+11
@@ -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"));
|
||||
|
||||
Reference in new issue
Block a user