fix(appsync): verify JWT signatures and SigV4 requests for GraphQL auth (#3541)

* fix(appsync): verify JWT signatures and SigV4 requests for GraphQL auth

Cognito and OIDC auth modes decoded JWT claims without checking the
signature, and AWS_IAM auth accepted any well-formed Credential= value
without verifying a real SigV4 signature. An unregistered IAM access
key also fell back to an account-root identity instead of being
rejected. Any of these let an attacker forge claims or an identity
for AppSync's GraphQL data-plane endpoint.

Cognito now verifies the token against the issuing user pool's own
RS256 signing key (alg, kid, issuer, expiry) instead of trusting the
decoded payload. OIDC verifies against the configured issuer's
published JWKS via OIDC discovery, reusing JwtSignatureVerifier (the
same verifier the HTTP API JWT authorizer uses), and fails closed on
an unreachable issuer or unsupported algorithm. AWS_IAM verifies a
real header-signed SigV4 request (service "appsync", fixed
/v1/apis/{apiId}/graphql canonical path): the Credential= access key
must resolve to a secret via IamService and the signature must match
the actual request, including its body. An unknown or unsigned key is
always rejected and never resolves to root; the legacy test/test pair
is still emulator-allow but must be signed like any other key.

JwtClaimsDecoder gained decodeHeader()/rawToken() so callers can check
alg/kid and hand the raw token to a signature verifier.
AuthRequestInfo carries the raw request body so IAM signature
verification can hash the real payload rather than trusting an
unsigned one.

* fix(appsync): bind session tokens to temporary IAM credentials

IamAuthValidator.resolveSecretKey resolved a temporary (ASIA...)
access key's session secret and verified the SigV4 signature, but
never checked X-Amz-Security-Token. A caller holding just the secret
could authenticate without presenting the session token AWS requires
to prove the credential is live and genuinely STS-issued.

checkSessionToken now mirrors ExecuteApiSigV4Authorizer: a temporary
key with no X-Amz-Security-Token header is rejected, a present token
is compared against the value IamService recorded at mint time with
MessageDigest.isEqual, and a session recorded before Floci tracked
tokens (no issued value to compare against) is not locked out by a
check it cannot satisfy. The token does not need to ride in
SignedHeaders; comparing it against the issued value binds it
regardless of where it rode.

Also drops the dead Date-header fallback in headerSignedRequest
(AMZ_DATE can never parse RFC 1123 output, so that branch never ran)
and fixes an em-dash in the AWS_IAM docs row.

* test(appsync): sign IAM data-plane requests in the auth integration test

Two AppSyncAuthIntegrationTest cases sent the bare Credential= header
that is enough for the management plane to the GraphQL endpoint and
expected 200. Now that AWS_IAM requests are verified as real SigV4,
that header is an unsigned request and gets 401, which is the intended
behaviour. Sign those two requests with AppSyncRequestSigner using the
legacy test credential; the cases that expect 401 for a dummy
signature are unchanged.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-13 17:56:24 -04:00
1 parent d83bc662e0
commit f38a384e51
15 files changed
+960 -86

No files matched your search

@@ -3,12 +3,16 @@ 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.github.hectorvent.floci.testutil.AppSyncRequestSigner;
import io.restassured.RestAssured;
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.time.Instant;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
@@ -163,7 +167,7 @@ class AppSyncAuthIntegrationTest {
}
@Test
void iamCallerOnApiKeyFieldReturns200WithUnauthorizedError() {
void iamCallerOnApiKeyFieldReturns200WithUnauthorizedError() throws Exception {
String apiId = given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
@@ -185,10 +189,11 @@ class AppSyncAuthIntegrationTest {
startSchema(apiId, "type Query { hello: String @aws_api_key }");
awaitSchemaSuccess(apiId);
String body = "{\"query\":\"{ hello }\"}";
given()
.contentType("application/json")
.header("Authorization", MGMT_AUTH)
.body("{\"query\":\"{ hello }\"}")
.headers(iamSignedHeaders(apiId, body))
.body(body)
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
@@ -201,7 +206,7 @@ class AppSyncAuthIntegrationTest {
}
@Test
void additionalModeIamCanIntrospect() {
void additionalModeIamCanIntrospect() throws Exception {
String apiId = given()
.header("Authorization", MGMT_AUTH)
.contentType("application/json")
@@ -223,10 +228,11 @@ class AppSyncAuthIntegrationTest {
startSchema(apiId, "type Query { hello: String }");
awaitSchemaSuccess(apiId);
String body = "{\"query\":\"{ __schema { types { name } } }\"}";
given()
.contentType("application/json")
.header("Authorization", MGMT_AUTH)
.body("{\"query\":\"{ __schema { types { name } } }\"}")
.headers(iamSignedHeaders(apiId, body))
.body(body)
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
@@ -242,6 +248,15 @@ class AppSyncAuthIntegrationTest {
awaitSchemaSuccess(apiId);
}
/**
* Data-plane requests in {@code AWS_IAM} mode must carry a real SigV4 signature; the bare
* {@code Credential=} header that is enough for the management plane is rejected there.
*/
private static Map<String, String> iamSignedHeaders(String apiId, String body) throws Exception {
return AppSyncRequestSigner.signedHeaders(apiId, "localhost:" + RestAssured.port, body,
"test", "test", "us-east-1", Instant.now());
}
private static String createApi(String name) {
return given()
.header("Authorization", MGMT_AUTH)
@@ -42,7 +42,7 @@ class AuthMiddlewareTest {
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());
"req", "000000000000", "us-east-1", Map.of(), "{ hello }");
}
@Test
@@ -1,13 +1,28 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
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.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -15,40 +30,106 @@ 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.Mockito.lenient;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class CognitoAuthValidatorTest {
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
private static final String POOL_ID = "us-east-1_abc";
private static final String KEY_ID = "signing-key-1";
private static final String ISSUER = "http://127.0.0.1:12345/us-east-1_abc";
private final ObjectMapper mapper = new ObjectMapper();
@Mock
CognitoService cognitoService;
private CognitoAuthValidator validator;
private Map<String, Object> config;
private RSAPrivateKey privateKey;
private UserPool pool;
@BeforeEach
void setUp() {
validator = new CognitoAuthValidator(new JwtClaimsDecoder(mapper), Clock.fixed(NOW, ZoneOffset.UTC));
void setUp() throws Exception {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair pair = gen.generateKeyPair();
privateKey = (RSAPrivateKey) pair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
pool = new UserPool();
pool.setSigningKeyId(KEY_ID);
pool.setSigningPublicKey(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
lenient().when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool);
lenient().when(cognitoService.getIssuer(POOL_ID)).thenReturn(ISSUER);
validator = new CognitoAuthValidator(new JwtClaimsDecoder(mapper), cognitoService,
Clock.fixed(NOW, ZoneOffset.UTC));
config = new HashMap<>();
config.put("userPoolId", "us-east-1_abc");
config.put("userPoolId", POOL_ID);
config.put("awsRegion", "us-east-1");
config.put("defaultAction", "ALLOW");
config.put("appIdClientRegex", "client-1");
}
@Test
void validJwtBuildsUsernameAndAuthTypeIdentity() {
void validSignedJwtBuildsUsernameAndAuthTypeIdentity() throws Exception {
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"));
Map<String, Object> identity = validator.validate(
"Bearer " + signedJwt(claims, KEY_ID, privateKey), config, List.of("127.0.0.1"));
assertEquals("alice", identity.get("username"));
assertEquals("abc", identity.get("sub"));
assertNull(identity.get("cognitoUserPoolId"));
}
@Test
void expiredJwtIs401() {
void unsignedAlgNoneTokenIs401() {
Map<String, Object> claims = baseClaims();
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + JwtClaimsDecoder.encode(claims, mapper), config, List.of()));
}
@Test
void tokenSignedByAForeignKeyIs401() throws Exception {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
RSAPrivateKey forgedKey = (RSAPrivateKey) gen.generateKeyPair().getPrivate();
Map<String, Object> claims = baseClaims();
assertThrows(AppSyncTransportException.class,
() -> validator.validate(
"Bearer " + signedJwt(claims, KEY_ID, forgedKey), config, List.of()));
}
@Test
void tokenWithUnknownKidIs401() throws Exception {
Map<String, Object> claims = baseClaims();
assertThrows(AppSyncTransportException.class,
() -> validator.validate(
"Bearer " + signedJwt(claims, "some-other-key", privateKey), config, List.of()));
}
@Test
void tokenForAnUnregisteredPoolIs401() throws Exception {
when(cognitoService.describeUserPool(POOL_ID))
.thenThrow(new AwsException("ResourceNotFoundException", "User pool not found", 400));
Map<String, Object> claims = baseClaims();
assertThrows(AppSyncTransportException.class,
() -> validator.validate(
"Bearer " + signedJwt(claims, KEY_ID, privateKey), config, List.of()));
}
@Test
void expiredJwtIs401() throws Exception {
Map<String, Object> claims = baseClaims();
claims.put("exp", NOW.getEpochSecond() - 10);
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, List.of()));
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, List.of()));
}
@Test
@@ -58,34 +139,62 @@ class CognitoAuthValidatorTest {
}
@Test
void missingSubIs401() {
void missingSubIs401() throws Exception {
Map<String, Object> claims = baseClaims();
claims.remove("sub");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, List.of()));
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, List.of()));
}
@Test
void groupsNullVsEmpty() {
Map<String, Object> missing = validator.validate("Bearer " + jwt(baseClaims()), config, List.of());
void wrongIssuerIs401() throws Exception {
Map<String, Object> claims = baseClaims();
claims.put("iss", "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, List.of()));
}
@Test
void groupsNullVsEmpty() throws Exception {
Map<String, Object> missing = validator.validate(
"Bearer " + signedJwt(baseClaims(), KEY_ID, privateKey), 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());
Map<String, Object> empty = validator.validate(
"Bearer " + signedJwt(emptyClaims, KEY_ID, privateKey), 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("iss", ISSUER);
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);
private String signedJwt(Map<String, Object> claims, String kid, RSAPrivateKey signingKey)
throws GeneralSecurityException {
ObjectNode header = mapper.createObjectNode();
header.put("alg", "RS256");
header.put("typ", "JWT");
header.put("kid", kid);
ObjectNode payload = mapper.createObjectNode();
claims.forEach((key, value) -> payload.putPOJO(key, value));
String signingInput = base64Url(header.toString()) + "." + base64Url(payload.toString());
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
}
}
@@ -6,12 +6,14 @@ import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportExcep
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 io.github.hectorvent.floci.testutil.AppSyncRequestSigner;
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.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -21,6 +23,7 @@ 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.lenient;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@@ -39,11 +42,14 @@ class IamAuthValidatorTest {
]}
""";
private static final String HOST = "appsync.us-east-1.amazonaws.com";
private static final String REGION = "us-east-1";
private static final String BODY = "{ hello }";
@Mock
IamService iamService;
private IamAuthValidator validator;
private AuthRequestInfo info;
@BeforeEach
void setUp() {
@@ -51,19 +57,29 @@ class IamAuthValidatorTest {
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());
lenient().when(iamService.findSecretKey("AKIAGOOD")).thenReturn(Optional.of("good-secret"));
lenient().when(iamService.findSecretKey("AKIDDENY")).thenReturn(Optional.of("deny-secret"));
}
private AuthRequestInfo infoWith(Map<String, String> signedHeaders) {
return new AuthRequestInfo("{ hello }", null, Map.of(), List.of("10.0.0.1"),
"req-1", "000000000000", "us-east-1", signedHeaders, BODY);
}
private static String authorization(Map<String, String> signedHeaders) {
return signedHeaders.get("Authorization");
}
@Test
void knownAllowBuildsIdentity() {
void knownAllowBuildsIdentity() throws Exception {
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, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, Instant.now());
Map<String, Object> identity = validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=AKIAGOOD/20260205/us-east-1/appsync/aws4_request",
"api-1", info);
authorization(signed), "api-1", infoWith(signed));
assertEquals("AKIAGOOD", identity.get("user"));
assertEquals("alice", identity.get("username"));
@@ -72,24 +88,81 @@ class IamAuthValidatorTest {
}
@Test
void knownRequestDenyThrows401() {
void knownRequestDenyThrows401() throws Exception {
when(iamService.resolveCallerContext("AKIDDENY")).thenReturn(CallerContext.of(List.of(DENY)));
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIDDENY", "deny-secret", REGION, Instant.now());
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=AKIDDENY/20260205/us-east-1/appsync/aws4_request",
"api-1", info));
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
assertEquals(401, ex.getHttpStatus());
}
@Test
void unknownTestKeyIsAllowed() {
void knownKeyWithBadSignatureIs401() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "wrong-secret", REGION, Instant.now());
assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
}
@Test
void tamperedBodyAfterSigningIs401() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, Instant.now());
AuthRequestInfo tampered = new AuthRequestInfo("{ hello }", null, Map.of(), List.of("10.0.0.1"),
"req-1", "000000000000", "us-east-1", signed, "{ hello, tampered }");
assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", tampered));
}
@Test
void unsignedRequestIsRejected() {
assertThrows(AppSyncTransportException.class, () -> validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=AKIAGOOD/20260205/us-east-1/appsync/aws4_request",
"api-1", infoWith(Map.of())));
}
@Test
void unknownAccessKeyNeverResolvesToRoot() throws Exception {
Map<String, String> 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());
}
@Test
void expiredSignatureIsRejected() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION,
Instant.now().minusSeconds(3600));
assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
}
@Test
void legacyTestKeyMustStillBeSigned() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "test", "test", REGION, Instant.now());
Map<String, Object> identity = validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request",
"api-1", info);
authorization(signed), "api-1", infoWith(signed));
assertEquals("test", identity.get("user"));
}
@Test
void unsignedLegacyTestKeyIsRejected() {
assertThrows(AppSyncTransportException.class, () -> validator.validateRequest(
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request",
"api-1", infoWith(Map.of())));
}
/**
* These two build the resource the policy evaluator matches against, and the ARN a customer
* writes their policy from is the one AppSync minted, which carries the region's partition.
@@ -117,6 +190,56 @@ class IamAuthValidatorTest {
IamAuthValidator.requestArn(null, "000000000000", "api-1"));
}
@Test
void temporaryCredentialSignedButNoSessionTokenIs401() throws Exception {
when(iamService.findSecretKey("ASIANOTOKEN")).thenReturn(Optional.of("session-secret"));
Map<String, String> 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());
}
@Test
void temporaryCredentialWithMismatchedSessionTokenIs401() throws Exception {
when(iamService.findSecretKey("ASIAFORGED")).thenReturn(Optional.of("session-secret"));
when(iamService.findSessionToken("ASIAFORGED")).thenReturn(Optional.of("issued-token"));
Map<String, String> signed = signedWithSessionToken("ASIAFORGED", "session-secret", "forged-token");
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
assertEquals(401, ex.getHttpStatus());
}
@Test
void temporaryCredentialWithIssuedSessionTokenIsAllowed() throws Exception {
when(iamService.findSecretKey("ASIALIVE")).thenReturn(Optional.of("session-secret"));
when(iamService.findSessionToken("ASIALIVE")).thenReturn(Optional.of("issued-token"));
when(iamService.resolveCallerArn("ASIALIVE")).thenReturn(
Optional.of("arn:aws:sts::000000000000:assumed-role/app/floci-session"));
Map<String, String> signed = signedWithSessionToken("ASIALIVE", "session-secret", "issued-token");
Map<String, Object> identity = validator.validateRequest(
authorization(signed), "api-1", infoWith(signed));
assertEquals("ASIALIVE", identity.get("user"));
assertEquals("floci-session", identity.get("username"));
}
/**
* Presents the session token the way an SDK does: as a header outside {@code SignedHeaders}.
* Nothing binds it to the signature, which is the point of comparing it against the issued
* value instead.
*/
private static Map<String, String> signedWithSessionToken(String accessKeyId, String secretKey, String token)
throws Exception {
Map<String, String> signed = new java.util.LinkedHashMap<>(AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, accessKeyId, secretKey, REGION, Instant.now()));
signed.put("X-Amz-Security-Token", token);
return signed;
}
@Test
void fieldArnDenyDetected() {
when(iamService.resolveCallerContext("AKIAGOOD")).thenReturn(CallerContext.of(List.of(FIELD_DENY)));
@@ -41,7 +41,7 @@ class LambdaAuthorizerValidatorTest {
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"));
List.of(), "req-1", "000000000000", "us-east-1", Map.of("authorization", "tok"), "{ hello }");
config = Map.of(
"authorizerUri", "arn:aws:lambda:us-east-1:000000000000:function:authz",
"authorizerResultTtlInSeconds", 30);
@@ -1,13 +1,31 @@
package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@@ -15,61 +33,143 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Follows {@code JwtSignatureVerifierTest}'s pattern: a real local {@code com.sun.net.httpserver}
* discovery/JWKS fixture and genuinely RS256-signed tokens, since {@link OidcAuthValidator} now
* delegates its signature check to the real {@link JwtSignatureVerifier} rather than a fake.
*/
class OidcAuthValidatorTest {
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
private static final String KEY_ID = "test-key-1";
private final ObjectMapper mapper = new ObjectMapper();
private HttpServer server;
private String issuer;
private RSAPrivateKey privateKey;
private RSAPublicKey publicKey;
private OidcAuthValidator validator;
@BeforeEach
void setUp() {
validator = new OidcAuthValidator(new JwtClaimsDecoder(mapper), Clock.fixed(NOW, ZoneOffset.UTC));
void setUp() throws Exception {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair pair = gen.generateKeyPair();
privateKey = (RSAPrivateKey) pair.getPrivate();
publicKey = (RSAPublicKey) pair.getPublic();
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/.well-known/openid-configuration", this::discovery);
server.createContext("/jwks", this::jwks);
server.start();
issuer = "http://127.0.0.1:" + server.getAddress().getPort();
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
validator = new OidcAuthValidator(new JwtClaimsDecoder(mapper),
new JwtSignatureVerifier(mapper, httpClient), Clock.fixed(NOW, ZoneOffset.UTC));
}
@AfterEach
void tearDown() {
server.stop(0);
}
private void discovery(com.sun.net.httpserver.HttpExchange exchange) throws IOException {
String body = "{\"issuer\":\"" + issuer + "\",\"jwks_uri\":\"" + issuer + "/jwks\"}";
respond(exchange, body);
}
private void jwks(com.sun.net.httpserver.HttpExchange exchange) throws IOException {
String n = base64UrlUnsigned(publicKey.getModulus());
String e = base64UrlUnsigned(publicKey.getPublicExponent());
String body = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"" + KEY_ID + "\",\"alg\":\"RS256\",\"use\":\"sig\","
+ "\"n\":\"" + n + "\",\"e\":\"" + e + "\"}]}";
respond(exchange, body);
}
private static void respond(com.sun.net.httpserver.HttpExchange exchange, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
}
@Test
void soleModeSkipsIssuer() {
Map<String, Object> config = config("https://configured-issuer", "my-client");
void soleModeSkipsIssuerClaimButStillVerifiesSignatureAgainstConfiguredIssuer() throws Exception {
Map<String, Object> config = config(issuer, "my-client");
Map<String, Object> claims = baseClaims("https://other-issuer", "my-client");
Map<String, Object> identity = validator.validate("Bearer " + jwt(claims), config, true);
Map<String, Object> identity = validator.validate(
"Bearer " + signedJwt(claims, KEY_ID, privateKey), 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");
void multiModeEnforcesIssuerClaim() throws Exception {
Map<String, Object> config = config(issuer, "my-client");
Map<String, Object> claims = baseClaims("https://other-issuer", "my-client");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, false));
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, false));
}
@Test
void iatTtlExceededIs401() {
Map<String, Object> config = config("https://issuer", "my-client");
void iatTtlExceededIs401() throws Exception {
Map<String, Object> config = config(issuer, "my-client");
config.put("iatTTL", 60);
Map<String, Object> claims = baseClaims("https://issuer", "my-client");
Map<String, Object> claims = baseClaims(issuer, "my-client");
claims.put("iat", NOW.getEpochSecond() - 120);
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, true));
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, true));
}
@Test
void clientIdRegexMatchesAzp() {
Map<String, Object> config = config("https://issuer", "client-.*");
Map<String, Object> claims = baseClaims("https://issuer", "other");
void clientIdRegexMatchesAzp() throws Exception {
Map<String, Object> config = config(issuer, "client-.*");
Map<String, Object> claims = baseClaims(issuer, "other");
claims.remove("aud");
claims.put("azp", "client-99");
Map<String, Object> identity = validator.validate("Bearer " + jwt(claims), config, true);
Map<String, Object> identity = validator.validate(
"Bearer " + signedJwt(claims, KEY_ID, privateKey), 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");
void clientIdMismatchIs401() throws Exception {
Map<String, Object> config = config(issuer, "client-1");
Map<String, Object> claims = baseClaims(issuer, "nope");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + jwt(claims), config, true));
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, true));
}
@Test
void unsignedAlgNoneTokenIs401() {
Map<String, Object> config = config(issuer, "my-client");
Map<String, Object> claims = baseClaims(issuer, "my-client");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + JwtClaimsDecoder.encode(claims, mapper), config, true));
}
@Test
void tokenSignedByAForeignKeyIs401() throws Exception {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
RSAPrivateKey forgedKey = (RSAPrivateKey) gen.generateKeyPair().getPrivate();
Map<String, Object> config = config(issuer, "my-client");
Map<String, Object> claims = baseClaims(issuer, "my-client");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, forgedKey), config, true));
}
@Test
void unreachableIssuerFailsClosed() throws Exception {
Map<String, Object> config = config("http://127.0.0.1:1", "my-client"); // nothing listening
Map<String, Object> claims = baseClaims("http://127.0.0.1:1", "my-client");
assertThrows(AppSyncTransportException.class,
() -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, privateKey), config, true));
}
private Map<String, Object> config(String issuer, String clientId) {
@@ -89,7 +189,33 @@ class OidcAuthValidatorTest {
return claims;
}
private String jwt(Map<String, Object> claims) {
return JwtClaimsDecoder.encode(claims, mapper);
private String signedJwt(Map<String, Object> claims, String kid, RSAPrivateKey signingKey)
throws GeneralSecurityException {
ObjectNode header = mapper.createObjectNode();
header.put("alg", "RS256");
header.put("typ", "JWT");
header.put("kid", kid);
ObjectNode payload = mapper.createObjectNode();
claims.forEach((key, value) -> payload.putPOJO(key, value));
String signingInput = base64Url(header.toString()) + "." + base64Url(payload.toString());
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
}
private static String base64UrlUnsigned(BigInteger value) {
byte[] bytes = value.toByteArray();
if (bytes.length > 1 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}
@@ -0,0 +1,97 @@
package io.github.hectorvent.floci.testutil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Signs an AppSync GraphQL data-plane request the way an AWS SDK signer would, so tests can
* exercise the {@code AWS_IAM} enforcement in {@code IamAuthValidator} against real signatures
* rather than against fixtures produced by the same code under test.
*
* <p>Header-signed only: real AppSync SDKs never presign this endpoint, and the fixed path/no
* query-string shape of {@code /v1/apis/{apiId}/graphql} needs nothing else.
*/
public final class AppSyncRequestSigner {
public static final String SIGNING_SERVICE = "appsync";
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private static final DateTimeFormatter SCOPE_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC);
private AppSyncRequestSigner() {
}
/**
* Returns the {@code Authorization}, {@code X-Amz-Date} and {@code Host} headers a header-signed
* {@code POST /v1/apis/{apiId}/graphql} request carries.
*/
public static Map<String, String> signedHeaders(String apiId, String host, String body,
String accessKeyId, String secretKey,
String region, Instant signedAt) throws Exception {
String amzDate = AMZ_DATE.format(signedAt);
String scopeDate = SCOPE_DATE.format(signedAt);
String credentialScope = scopeDate + "/" + region + "/" + SIGNING_SERVICE + "/aws4_request";
String signedHeaderNames = "host;x-amz-date";
String canonicalUri = "/v1/apis/" + apiId + "/graphql";
String canonicalRequest = "POST\n"
+ canonicalUri + "\n"
+ "\n"
+ "host:" + host + "\n"
+ "x-amz-date:" + amzDate + "\n"
+ "\n"
+ signedHeaderNames + "\n"
+ sha256Hex(body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8));
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = deriveSigningKey(secretKey, scopeDate, region);
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
Map<String, String> headers = new LinkedHashMap<>();
headers.put("Host", host);
headers.put("X-Amz-Date", amzDate);
headers.put("Authorization", "AWS4-HMAC-SHA256 "
+ "Credential=" + accessKeyId + "/" + credentialScope + ", "
+ "SignedHeaders=" + signedHeaderNames + ", "
+ "Signature=" + signature);
return headers;
}
private static byte[] deriveSigningKey(String secretKey, String date, String region) throws Exception {
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSha256(kSecret, date);
byte[] kRegion = hmacSha256(kDate, region);
byte[] kService = hmacSha256(kRegion, SIGNING_SERVICE);
return hmacSha256(kService, "aws4_request");
}
private static byte[] hmacSha256(byte[] key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(byte[] input) throws Exception {
return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
hex.append(String.format("%02x", b));
}
return hex.toString();
}
}