From 0dd443478c0ea9ddae8b0fe2ac75e6c1c8cdf2be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Sun, 18 Oct 2026 13:30:48 +0900 Subject: [PATCH] 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 --- docs/services/appsync.md | 8 +- .../common/SigV4HeaderSignatureFilter.java | 2 +- .../core/common/auth/CredentialScope.java | 5 +- .../common/auth/SigV4AuthorizationHeader.java | 12 +- .../appsync/graphql/auth/AppSyncAuth.java | 13 ++ .../graphql/auth/IamAuthValidator.java | 213 ++++++++++++------ .../SigV4HeaderSignatureIntegrationTest.java | 8 +- .../graphql/auth/IamAuthValidatorTest.java | 180 +++++++++++++-- 8 files changed, 329 insertions(+), 112 deletions(-) diff --git a/docs/services/appsync.md b/docs/services/appsync.md index 3c617d6e3a..8e0cbab664 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -237,7 +237,9 @@ Responses are `application/json` with AWS AppSync wire shapes (`data` / `errors[ | Unknown `apiId` | 404 | `NotFoundException` | | 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`. | +| 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`. An `AWS_IAM` caller whose policies deny `appsync:GraphQL` gets `Permission denied`. | +| `AWS_IAM` with a `SigV4` header that misses a part or a date, a date not in the ISO-8601 basic format, a credential without 5 parts, or a signed header the request lacks | **403** | `IncompleteSignatureException` with AWS's message. A missing part names a Base64 SHA-256 hash of the `Authorization` header. | +| `AWS_IAM` signed outside 5 minutes, without `host` in `SignedHeaders`, scoped to another service, terminator or date, or with a signature that does not match | **400** | `BadRequestException` with AWS's message. A mismatch names the canonical request and the string to sign that Floci computed. | | `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`) | @@ -249,7 +251,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.`, except the 403 `AWS_IAM` cases in the table above. +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 `AWS_IAM` cases in the table above. | Header shape | Mode | |---|---| @@ -263,7 +265,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 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`. | +| 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. The checks run in AppSync's order. The scope's region is not checked, because Floci takes the request's region from it. 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/core/common/SigV4HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java index c43840aac8..41a6e5ffa8 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java @@ -160,7 +160,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter { return; } signed = new SigV4AuthorizationHeader(query.getFirst("X-Amz-Credential"), - query.getFirst("X-Amz-SignedHeaders"), query.getFirst("X-Amz-Signature")); + query.getFirst("X-Amz-SignedHeaders"), query.getFirst("X-Amz-Signature"), false); } else { signed = SigV4AuthorizationHeader.parse(authorization); if (signed == null) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java index 6eae14fc5a..368aa7e115 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/CredentialScope.java @@ -7,9 +7,8 @@ import java.util.Locale; * carried by a {@code Credential} parameter, whether that parameter arrived in an * {@code Authorization} header or an {@code X-Amz-Credential} query/token component. Shared by * every SigV4 verifier in this codebase that checks an Authorization-header-signed request - * against this exact five-part shape: {@code ExecuteApiSigV4Authorizer} (API Gateway) and - * {@code IamAuthValidator} (AppSync) both parsed and rebuilt this independently before this class - * existed. + * against this exact five-part shape. AppSync's {@code IamAuthValidator} splits the scope itself, + * because it names each fault the way AppSync does. */ public record CredentialScope(String accessKeyId, String date, String region, String service) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4AuthorizationHeader.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4AuthorizationHeader.java index 0782114100..c2544b9ab7 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4AuthorizationHeader.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4AuthorizationHeader.java @@ -9,8 +9,11 @@ import java.util.Map; * Shared by every SigV4 verifier in this codebase that accepts a header-signed request: * {@code ExecuteApiSigV4Authorizer} (API Gateway) and {@code IamAuthValidator} (AppSync) both * parsed this independently before this class existed. + * + *

{@code missingEqualSign} is true when a part has no {@code =}. AppSync refuses such a header. */ -public record SigV4AuthorizationHeader(String credential, String signedHeaders, String signature) { +public record SigV4AuthorizationHeader(String credential, String signedHeaders, String signature, + boolean missingEqualSign) { private static final String ALGORITHM = "AWS4-HMAC-SHA256"; @@ -29,13 +32,16 @@ public record SigV4AuthorizationHeader(String credential, String signedHeaders, return null; } Map parameters = new LinkedHashMap<>(); + boolean missingEqualSign = false; for (String part : trimmed.substring(ALGORITHM.length()).split(",")) { int equals = part.indexOf('='); if (equals > 0) { parameters.put(part.substring(0, equals).trim(), part.substring(equals + 1).trim()); + } else if (equals < 0 && !part.isBlank()) { + missingEqualSign = true; } } - return new SigV4AuthorizationHeader( - parameters.get("Credential"), parameters.get("SignedHeaders"), parameters.get("Signature")); + return new SigV4AuthorizationHeader(parameters.get("Credential"), parameters.get("SignedHeaders"), + parameters.get("Signature"), missingEqualSign); } } 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 e264a06707..e0a174b0f9 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 @@ -38,6 +38,19 @@ public final class AppSyncAuth { return new AppSyncTransportException(403, UNRECOGNIZED_CLIENT_TYPE, INVALID_SECURITY_TOKEN); } + /** An {@code AWS_IAM} caller whose policies do not allow {@code appsync:GraphQL}. */ + public static AppSyncTransportException permissionDenied() { + return new AppSyncTransportException(401, UNAUTHORIZED_TYPE, "Permission denied"); + } + + public static AppSyncTransportException incompleteSignature(String message) { + return new AppSyncTransportException(403, "IncompleteSignatureException", message); + } + + public static AppSyncTransportException badRequest(String message) { + return new AppSyncTransportException(400, "BadRequestException", message); + } + 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 eb0494d8d4..13c1797f9c 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 @@ -1,13 +1,12 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth; -import io.github.hectorvent.floci.core.common.AccountResolver; 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.core.common.auth.SigV4SignedRequest; 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; @@ -18,9 +17,14 @@ import org.jboss.logging.Logger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.time.Clock; +import java.time.DateTimeException; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; import java.util.Locale; import java.util.Map; @@ -49,30 +53,34 @@ public class IamAuthValidator { private static final String SIGNING_SERVICE = "appsync"; private static final DateTimeFormatter AMZ_DATE = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); - private static final long MAX_CLOCK_SKEW_SECONDS = 300; + private static final String TERMINATOR = "aws4_request"; + private static final String SIGNATURE_MISMATCH = "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."; private static final String LEGACY_ACCESS_KEY_ID = "test"; private static final String LEGACY_SECRET_KEY = "test"; private static final String SECURITY_TOKEN = "X-Amz-Security-Token"; - private final AccountResolver accountResolver; private final IamService iamService; private final IamPolicyEvaluator iamPolicyEvaluator; + private final Clock clock; @Inject - public IamAuthValidator(AccountResolver accountResolver, - IamService iamService, - IamPolicyEvaluator iamPolicyEvaluator) { - this.accountResolver = accountResolver; + public IamAuthValidator(IamService iamService, IamPolicyEvaluator iamPolicyEvaluator) { + this(iamService, iamPolicyEvaluator, Clock.systemUTC()); + } + + IamAuthValidator(IamService iamService, IamPolicyEvaluator iamPolicyEvaluator, Clock clock) { this.iamService = iamService; this.iamPolicyEvaluator = iamPolicyEvaluator; + this.clock = clock; } public Map validateRequest(String authorization, String apiId, AuthRequestInfo info) { - String accessKeyId = accountResolver.extractAccessKeyId(authorization); - if (accessKeyId == null || accessKeyId.isBlank()) { + if (authorization == null || !authorization.trim().startsWith(ALGORITHM)) { throw AppSyncAuth.unauthorized(); } - verifySignature(authorization, apiId, info, accessKeyId); + String accessKeyId = verifySignature(authorization.trim(), apiId, info); if (!isEmulatorAllow(accessKeyId)) { CallerContext caller = iamService.resolveCallerContext(accessKeyId); if (caller != null) { @@ -80,7 +88,7 @@ public class IamAuthValidator { IamPolicyEvaluator.Decision decision = iamPolicyEvaluator.evaluate( caller, null, "appsync:GraphQL", resource, null); if (decision == IamPolicyEvaluator.Decision.DENY) { - throw AppSyncAuth.unauthorized(); + throw AppSyncAuth.permissionDenied(); } } } @@ -98,60 +106,140 @@ public class IamAuthValidator { } /** - * Fails closed: a missing/unparsable {@code Authorization} header, a credential not scoped to - * {@code appsync}, a signing timestamp outside the accepted clock skew, an access key this - * emulator has never registered, or a signature that does not match are all rejected. There is - * no default secret and no path that authenticates an unregistered key. + * Returns the access key that signed the request. The checks run in AppSync's order with its + * wording. AppSync names the scope region it refuses, but Floci takes the request's region from + * that scope, so it is not checked. There is no default secret and no path that authenticates + * an unregistered key. */ - private void verifySignature(String authorization, String apiId, AuthRequestInfo info, String accessKeyId) { - SignedRequest signed = headerSignedRequest(authorization, info.requestHeaders()); - if (signed == null) { - throw AppSyncAuth.unauthorized(); + private String verifySignature(String authorization, String apiId, AuthRequestInfo info) { + Map headers = info.requestHeaders(); + SigV4AuthorizationHeader parsed = SigV4AuthorizationHeader.parse(authorization); + if (parsed.missingEqualSign()) { + throw AppSyncAuth.incompleteSignature("Invalid key=value pair (missing equal-sign) in Authorization" + + " header (hashed with SHA-256 and encoded with Base64): '" + hashed(authorization) + "'."); } - CredentialScope scope = CredentialScope.parse(signed.credential()); - if (scope == null || !SIGNING_SERVICE.equals(scope.service()) || !accessKeyId.equals(scope.accessKeyId())) { - throw AppSyncAuth.unauthorized(); + String credential = parsed.credential(); + String signedHeaders = parsed.signedHeaders(); + String signature = parsed.signature(); + String date = hasHeader(headers, "X-Amz-Date") ? header(headers, "X-Amz-Date") + : hasHeader(headers, "Date") ? header(headers, "Date") : null; + List missing = new ArrayList<>(); + if (isBlank(credential)) { + missing.add("Authorization header requires 'Credential' parameter."); } - Instant signedAt; - try { - signedAt = Instant.from(AMZ_DATE.parse(signed.amzDate())); - } catch (Exception e) { - throw AppSyncAuth.unauthorized(); + if (isBlank(signature)) { + missing.add("Authorization header requires 'Signature' parameter."); } - if (Math.abs(Instant.now().getEpochSecond() - signedAt.getEpochSecond()) > MAX_CLOCK_SKEW_SECONDS) { - throw AppSyncAuth.unauthorized(); + if (isBlank(signedHeaders)) { + missing.add("Authorization header requires 'SignedHeaders' parameter."); } + if (date == null) { + missing.add("Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header."); + } + if (!missing.isEmpty()) { + throw AppSyncAuth.incompleteSignature(String.join(" ", missing) + + " (Hashed with SHA-256 and encoded with Base64) Authorization=" + hashed(authorization)); + } + Instant signedAt = signedAt(date); + if (signedAt == null) { + throw AppSyncAuth.incompleteSignature("Date must be in ISO-8601 'basic format'. Got '" + date + + "'. See http://en.wikipedia.org/wiki/ISO_8601"); + } + checkSigningTime(signedAt); + for (String name : signedHeaders.split(";")) { + if (!hasHeader(headers, name)) { + throw AppSyncAuth.incompleteSignature("'" + name + + "' is named as a SignedHeader, but it does not exist in the HTTP request."); + } + } + String names = signedHeaders.toLowerCase(Locale.ROOT); + if (!SigV4RequestValidator.containsHeader(names, "host") + && !SigV4RequestValidator.containsHeader(names, ":authority")) { + throw AppSyncAuth.badRequest("'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization."); + } + String[] scope = credential.split("/", -1); + if (scope.length != 5) { + throw AppSyncAuth.incompleteSignature("Credential must have exactly 5 slash-delimited elements," + + " e.g. keyid/date/region/service/term, got '" + credential + "'"); + } + String amzDate = AMZ_DATE.format(signedAt); + checkScope(scope, amzDate); + String accessKeyId = scope[0]; String secretKey = resolveSecretKey(accessKeyId); if (secretKey == null) { LOG.debugv("AppSync SigV4 request references unregistered access key={0}", SigV4RequestValidator.sanitizeForLog(accessKeyId)); throw AppSyncAuth.unrecognizedClient(); } - checkSessionToken(accessKeyId, info.requestHeaders()); + String canonicalRequest = "POST\n/v1/apis/" + apiId + "/graphql\n\n" + canonicalHeaders(names, headers) + + "\n" + names + "\n" + Digests.sha256Hex(info.rawBody().getBytes(StandardCharsets.UTF_8)); + String stringToSign = ALGORITHM + "\n" + amzDate + "\n" + String.join("/", scope[1], scope[2], scope[3], scope[4]) + + "\n" + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); + String expected; try { - String canonicalUri = "/v1/apis/" + apiId + "/graphql"; - String payloadHash = Digests.sha256Hex(info.rawBody().getBytes(StandardCharsets.UTF_8)); - String canonicalHeaders = canonicalHeaders(signed.signedHeaders(), info.requestHeaders()); - String canonicalRequest = "POST\n" + canonicalUri + "\n\n" - + canonicalHeaders + "\n" + signed.signedHeaders() + "\n" + payloadHash; - String stringToSign = ALGORITHM + "\n" + signed.amzDate() + "\n" + scope.credentialScope() + "\n" - + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); - byte[] signingKey = SigV4RequestValidator.deriveSigningKey( - secretKey, scope.date(), scope.region(), scope.service()); - String expected = SigV4RequestValidator.hexEncode( - SigV4RequestValidator.hmacSha256(signingKey, stringToSign)); - if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), - signed.signature().getBytes(StandardCharsets.UTF_8))) { - LOG.debugv("AppSync SigV4 signature mismatch for accessKey={0}", - SigV4RequestValidator.sanitizeForLog(accessKeyId)); - throw AppSyncAuth.unauthorized(); - } - } catch (AppSyncTransportException e) { - throw e; + byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scope[1], scope[2], scope[3]); + expected = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, stringToSign)); } catch (Exception e) { LOG.debugv(e, "AppSync SigV4 verification failed to complete: {0}", e.getMessage()); throw AppSyncAuth.unauthorized(); } + if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) { + LOG.debugv("AppSync SigV4 signature mismatch for accessKey={0}", + SigV4RequestValidator.sanitizeForLog(accessKeyId)); + throw AppSyncAuth.badRequest(SIGNATURE_MISMATCH + "\n\nThe Canonical String for this request should have been\n'" + + canonicalRequest + "'\n\nThe String-to-Sign should have been\n'" + stringToSign + "'\n"); + } + checkSessionToken(accessKeyId, headers); + return accessKeyId; + } + + private static String hashed(String authorization) { + return Base64.getEncoder().encodeToString(Digests.sha256(authorization.getBytes(StandardCharsets.UTF_8))); + } + + /** AppSync reads the basic format, and the extended one too. */ + private static Instant signedAt(String date) { + try { + return Instant.from(AMZ_DATE.parse(date)); + } catch (DateTimeException notBasic) { + try { + return Instant.parse(date); + } catch (DateTimeException expected) { + // Refused with the basic format message. + return null; + } + } + } + + private void checkSigningTime(Instant signedAt) { + Instant now = clock.instant(); + Instant earliest = now.minusSeconds(SigV4SignedRequest.MAX_CLOCK_SKEW_SECONDS); + Instant latest = now.plusSeconds(SigV4SignedRequest.MAX_CLOCK_SKEW_SECONDS); + if (signedAt.isBefore(earliest)) { + throw AppSyncAuth.badRequest("Signature expired: " + AMZ_DATE.format(signedAt) + " is now earlier than " + + AMZ_DATE.format(earliest) + " (" + AMZ_DATE.format(now) + " - 5 min.)"); + } + if (signedAt.isAfter(latest)) { + throw AppSyncAuth.badRequest("Signature not yet current: " + AMZ_DATE.format(signedAt) + + " is still later than " + AMZ_DATE.format(latest) + " (" + AMZ_DATE.format(now) + " + 5 min.)"); + } + } + + /** {@code scope} is key, date, region, service and terminator. AppSync reports every fault at once. */ + private static void checkScope(String[] scope, String amzDate) { + List faults = new ArrayList<>(); + if (!SIGNING_SERVICE.equals(scope[3])) { + faults.add("Credential should be scoped to correct service: '" + SIGNING_SERVICE + "'."); + } + if (!TERMINATOR.equals(scope[4])) { + faults.add("Credential should be scoped with a valid terminator: '" + TERMINATOR + "'."); + } + if (!amzDate.substring(0, 8).equals(scope[1])) { + faults.add("Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP."); + } + if (!faults.isEmpty()) { + throw AppSyncAuth.badRequest(String.join(" ", faults) + " "); + } } /** @@ -183,31 +271,6 @@ public class IamAuthValidator { } } - private record SignedRequest(String credential, String signedHeaders, String signature, String amzDate) {} - - /** - * {@code X-Amz-Date} is a real HTTP header on a header-signed request, never a field inside the - * {@code Authorization} value itself (that only ever carries {@code Credential}/ - * {@code SignedHeaders}/{@code Signature}), so it is read from {@code requestHeaders} - the same - * source {@code ExecuteApiSigV4Authorizer} reads it from. There is no fallback to the plain - * {@code Date} header: unlike {@code X-Amz-Date}, it is RFC 1123-formatted, which {@link - * #AMZ_DATE} can never parse, so a request that only sets {@code Date} is rejected below - * regardless. - */ - private static SignedRequest headerSignedRequest(String authorization, Map requestHeaders) { - SigV4AuthorizationHeader parsed = SigV4AuthorizationHeader.parse(authorization); - if (parsed == null) { - return null; - } - String amzDate = header(requestHeaders, "X-Amz-Date"); - if (isBlank(parsed.credential()) || isBlank(parsed.signedHeaders()) - || isBlank(parsed.signature()) || isBlank(amzDate)) { - return null; - } - return new SignedRequest(parsed.credential(), parsed.signedHeaders().toLowerCase(Locale.ROOT), - parsed.signature(), amzDate); - } - private static String canonicalHeaders(String signedHeaders, Map requestHeaders) { StringBuilder canonical = new StringBuilder(); for (String name : signedHeaders.split(";")) { diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java index def4d81c89..ff7682eec0 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java @@ -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 sendSqsListQueues(URI uri, Map auth, String contentType, 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 7a30950534..2eb8c0fbc5 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 @@ -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 signed = AppSyncRequestSigner.signedHeaders( - "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, Instant.now()); + "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW); Map 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 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 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 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 signed = AppSyncRequestSigner.signedHeaders( + "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW); + Map 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 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 signed = AppSyncRequestSigner.signedHeaders( + "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW); + Map 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 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 signed = AppSyncRequestSigner.signedHeaders( + "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW); + Map 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 signed = AppSyncRequestSigner.signedHeaders( + "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, NOW); + Map 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 signed, int status, String errorType) { + return assertRejected(authorization(signed), signed, status, errorType); + } + + private AppSyncTransportException assertRejected(String authorization, Map 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 signed) { + return authorization(signed).split("Credential=")[1].split(",")[0]; + } + + private static Map withCredential(Map signed, String credential) { + Map 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 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 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 signed = AppSyncRequestSigner.signedHeaders( - "api-1", HOST, BODY, "test", "test", REGION, Instant.now()); + "api-1", HOST, BODY, "test", "test", REGION, NOW); Map 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 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 signedWithSessionToken(String accessKeyId, String secretKey, String token) throws Exception { Map 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; }