fix(appsync): answer a failed AWS_IAM request with AppSync's errors (#5901)

* fix(appsync): answer a bad AWS_IAM signature with AppSync's error and wording

AppSync answers 403 IncompleteSignatureException when the Authorization
header misses a part or the date, and 400 BadRequestException when the
signing time, the signed headers, the scope or the signature are wrong.
The checks run in AppSync's order, and the signature is checked before
the session token.

* fix(appsync): answer an AWS_IAM policy deny with Permission denied

AppSync answers 401 UnauthorizedException "Permission denied" when the
caller's policies do not allow appsync:GraphQL.

* fix(appsync): check a missing signed header and the credential parts in AppSync's order

AppSync checks that every signed header is in the request after the
signing time, then that host is signed, then the credential parts. It
names the header as the request signed it.

* test(appsync): expect BadRequestException for a wrong secret on the GraphQL endpoint

* test(appsync): pin the clock to check the whole signing time message

* chore(appsync): read the Authorization parts with the shared parser
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-18 00:30:48 -04:00
1 parent ae285fc3a8
commit 0dd443478c
8 files changed
+329 -112

No files matched your search

@@ -427,7 +427,7 @@ class SigV4HeaderSignatureIntegrationTest {
@Order(17)
void appSyncGraphqlIsLeftToItsOwnIamCheck() throws Exception {
// The management plane is verified here like any other service; the GraphQL endpoint is
// AppSync's own, and a wrong secret there gets AppSync's UnauthorizedException envelope.
// AppSync's own, and a wrong secret there gets AppSync's BadRequestException envelope.
String apiId = given()
.filter(AwsRequestSigner.signedAs("test", "test", "appsync"))
.contentType("application/json")
@@ -448,9 +448,9 @@ class SigV4HeaderSignatureIntegrationTest {
.when()
.post("/v1/apis/" + apiId + "/graphql")
.then()
.statusCode(401)
.header("x-amzn-errortype", containsString("UnauthorizedException"))
.body("errors[0].errorType", equalTo("UnauthorizedException"));
.statusCode(400)
.header("x-amzn-errortype", containsString("BadRequestException"))
.body("errors[0].errorType", equalTo("BadRequestException"));
}
private static HttpResponse<String> sendSqsListQueues(URI uri, Map<String, String> auth, String contentType,
@@ -1,7 +1,7 @@
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.core.common.Digests;
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;
@@ -13,7 +13,12 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -45,6 +50,7 @@ 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 }";
private static final Instant NOW = Instant.parse("2026-10-17T22:16:18Z");
@Mock
IamService iamService;
@@ -54,9 +60,9 @@ class IamAuthValidatorTest {
@BeforeEach
void setUp() {
validator = new IamAuthValidator(
new AccountResolver("000000000000"),
iamService,
new IamPolicyEvaluator(new ObjectMapper()));
new IamPolicyEvaluator(new ObjectMapper()),
Clock.fixed(NOW, ZoneOffset.UTC));
lenient().when(iamService.findSecretKey("AKIAGOOD")).thenReturn(Optional.of("good-secret"));
lenient().when(iamService.findSecretKey("AKIDDENY")).thenReturn(Optional.of("deny-secret"));
}
@@ -76,7 +82,7 @@ class IamAuthValidatorTest {
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());
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW);
Map<String, Object> identity = validator.validateRequest(
authorization(signed), "api-1", infoWith(signed));
@@ -91,44 +97,172 @@ class IamAuthValidatorTest {
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());
"api-1", HOST, BODY, "AKIDDENY", "deny-secret", REGION, NOW);
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
assertEquals(401, ex.getHttpStatus());
assertEquals("UnauthorizedException", ex.getErrorType());
assertEquals("Permission denied", ex.getMessage());
}
@Test
void knownKeyWithBadSignatureIs401() throws Exception {
void knownKeyWithBadSignatureIsABadRequestNamingTheCanonicalRequest() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "wrong-secret", REGION, Instant.now());
"api-1", HOST, BODY, "AKIAGOOD", "wrong-secret", REGION, NOW);
assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
AppSyncTransportException ex = assertRejected(signed, 400, "BadRequestException");
assertTrue(ex.getMessage().startsWith("The request signature we calculated does not match the signature you"
+ " provided. Check your AWS Secret Access Key and signing method. Consult the service documentation"
+ " for details.\n\nThe Canonical String for this request should have been\n'POST\n"
+ "/v1/apis/api-1/graphql\n\nhost:" + HOST + "\nx-amz-date:" + signed.get("X-Amz-Date")
+ "\n\nhost;x-amz-date\n"), ex.getMessage());
assertTrue(ex.getMessage().contains("'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n"
+ signed.get("X-Amz-Date") + "\n"), ex.getMessage());
}
@Test
void tamperedBodyAfterSigningIs401() throws Exception {
void tamperedBodyAfterSigningIsABadRequest() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, Instant.now());
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, 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,
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", tampered));
assertEquals(400, ex.getHttpStatus());
}
@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())));
void missingPartsAreNamedTogetherWithTheHeaderHash() throws Exception {
String authorization = "AWS4-HMAC-SHA256 Credential=AKIAGOOD/20260205/us-east-1/appsync/aws4_request";
AppSyncTransportException ex = assertRejected(authorization, Map.of(), 403, "IncompleteSignatureException");
assertEquals("Authorization header requires 'Signature' parameter."
+ " Authorization header requires 'SignedHeaders' parameter."
+ " Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header."
+ " (Hashed with SHA-256 and encoded with Base64) Authorization=" + hashed(authorization),
ex.getMessage());
assertEquals("Authorization header requires 'Credential' parameter."
+ " Authorization header requires 'Signature' parameter."
+ " Authorization header requires 'SignedHeaders' parameter."
+ " (Hashed with SHA-256 and encoded with Base64) Authorization=" + hashed("AWS4-HMAC-SHA256"),
assertRejected("AWS4-HMAC-SHA256", Map.of("X-Amz-Date", "20260205T000000Z"), 403,
"IncompleteSignatureException").getMessage());
}
@Test
void aPartWithoutAnEqualsSignRefusesTheHeader() {
String authorization = "AWS4-HMAC-SHA256 garbage";
assertEquals("Invalid key=value pair (missing equal-sign) in Authorization header (hashed with SHA-256 and"
+ " encoded with Base64): '" + hashed(authorization) + "'.",
assertRejected(authorization, Map.of(), 403, "IncompleteSignatureException").getMessage());
}
@Test
void theDateMustBeInTheBasicFormatAndTheCredentialHaveFiveParts() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW);
Map<String, String> dated = new LinkedHashMap<>(signed);
dated.remove("X-Amz-Date");
dated.put("Date", "Sat, 17 Oct 2026 22:15:13 GMT");
assertEquals("Date must be in ISO-8601 'basic format'. Got 'Sat, 17 Oct 2026 22:15:13 GMT'."
+ " See http://en.wikipedia.org/wiki/ISO_8601",
assertRejected(dated, 403, "IncompleteSignatureException").getMessage());
String credential = "AKIAGOOD/x/y";
assertEquals("Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term,"
+ " got 'AKIAGOOD/x/y'", assertRejected(withCredential(signed, credential), 403,
"IncompleteSignatureException").getMessage());
}
@Test
void aSignatureFromTheFutureIsNotYetCurrent() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW.plusSeconds(600));
assertEquals("Signature not yet current: 20261017T222618Z is still later than 20261017T222118Z"
+ " (20261017T221618Z + 5 min.)", assertRejected(signed, 400, "BadRequestException").getMessage());
}
@Test
void theHostMustBeSignedBeforeTheScopeIsChecked() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW);
Map<String, String> unsignedHost = withCredential(signed,
credential(signed).replace("/appsync/", "/execute-api/"));
unsignedHost.put("Authorization", unsignedHost.get("Authorization").replace("host;x-amz-date", "x-amz-date"));
assertEquals("'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization.",
assertRejected(unsignedHost, 400, "BadRequestException").getMessage());
}
@Test
void everyScopeFaultIsNamedAtOnce() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW);
String[] scope = credential(signed).split("/");
String faulty = String.join("/", scope[0], "20200101", scope[2], "execute-api", "aws5_request");
assertEquals("Credential should be scoped to correct service: 'appsync'."
+ " Credential should be scoped with a valid terminator: 'aws4_request'."
+ " Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP. ",
assertRejected(withCredential(signed, faulty), 400, "BadRequestException").getMessage());
}
@Test
void aSignedHeaderMustBeInTheRequestBeforeTheHostOrTheCredentialIsChecked() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW);
Map<String, String> missing = withCredential(signed, "AKIAGOOD/x/y");
missing.put("Authorization", missing.get("Authorization").replace("host;x-amz-date", "x-amz-date;X-Extra"));
assertEquals("'X-Extra' is named as a SignedHeader, but it does not exist in the HTTP request.",
assertRejected(missing, 403, "IncompleteSignatureException").getMessage());
}
@Test
void theHostIsCheckedBeforeTheCredentialParts() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW);
Map<String, String> unsignedHost = withCredential(signed, "AKIAGOOD/x/y");
unsignedHost.put("Authorization", unsignedHost.get("Authorization").replace("host;x-amz-date", "x-amz-date"));
assertEquals("'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization.",
assertRejected(unsignedHost, 400, "BadRequestException").getMessage());
}
private AppSyncTransportException assertRejected(Map<String, String> signed, int status, String errorType) {
return assertRejected(authorization(signed), signed, status, errorType);
}
private AppSyncTransportException assertRejected(String authorization, Map<String, String> headers, int status,
String errorType) {
AppSyncTransportException ex = assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization, "api-1", infoWith(headers)));
assertEquals(status, ex.getHttpStatus(), ex.getMessage());
assertEquals(errorType, ex.getErrorType());
return ex;
}
private static String credential(Map<String, String> signed) {
return authorization(signed).split("Credential=")[1].split(",")[0];
}
private static Map<String, String> withCredential(Map<String, String> signed, String credential) {
Map<String, String> changed = new LinkedHashMap<>(signed);
changed.put("Authorization", authorization(signed).replace(credential(signed), credential));
return changed;
}
private static String hashed(String authorization) {
return Base64.getEncoder().encodeToString(Digests.sha256(authorization.getBytes(StandardCharsets.UTF_8)));
}
@Test
void unknownAccessKeyNeverResolvesToRoot() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAUNKNOWN", "whatever-secret", REGION, Instant.now());
"api-1", HOST, BODY, "AKIAUNKNOWN", "whatever-secret", REGION, NOW);
assertRefused(signed, "The security token included in the request is invalid.");
}
@@ -137,16 +271,16 @@ class IamAuthValidatorTest {
void expiredSignatureIsRejected() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION,
Instant.now().minusSeconds(3600));
NOW.minusSeconds(3600));
assertThrows(AppSyncTransportException.class,
() -> validator.validateRequest(authorization(signed), "api-1", infoWith(signed)));
assertEquals("Signature expired: 20261017T211618Z is now earlier than 20261017T221118Z"
+ " (20261017T221618Z - 5 min.)", assertRejected(signed, 400, "BadRequestException").getMessage());
}
@Test
void legacyTestKeyMustStillBeSigned() throws Exception {
Map<String, String> signed = AppSyncRequestSigner.signedHeaders(
"api-1", HOST, BODY, "test", "test", REGION, Instant.now());
"api-1", HOST, BODY, "test", "test", REGION, NOW);
Map<String, Object> identity = validator.validateRequest(
authorization(signed), "api-1", infoWith(signed));
@@ -192,7 +326,7 @@ class IamAuthValidatorTest {
void temporaryCredentialSignedButNoSessionTokenIsRefused() 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());
"api-1", HOST, BODY, "ASIANOTOKEN", "session-secret", REGION, NOW);
assertRefused(signed, "The security token included in the request is invalid.");
}
@@ -252,7 +386,7 @@ class IamAuthValidatorTest {
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()));
"api-1", HOST, BODY, accessKeyId, secretKey, REGION, NOW));
signed.put("X-Amz-Security-Token", token);
return signed;
}