diff --git a/docs/services/appsync.md b/docs/services/appsync.md index abb27e480d..9fcee65b56 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -222,8 +222,8 @@ 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 | Parses `Credential=` access key; no HMAC. Known keys evaluate `appsync:GraphQL`. Unknown/`test` keys are emulator ALLOW. | -| Cognito / OIDC | JWT payload decode only (no JWKS). OIDC as the sole mode skips the `iss` check. OIDC identity is `{sub, issuer, claims}` (no `sourceIp`). | +| 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 matching the one issued for it. An unknown or unsigned key is always 401 and never becomes the account-root identity. 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). | SDL field auth: unmarked fields require the API **default** mode. Additional modes unlock fields tagged `@aws_api_key` / `@aws_iam` / `@aws_oidc` / `@aws_cognito_user_pools` / `@aws_lambda`. Multiple directives on a field are OR. Field-level directives override type-level. `@aws_auth` is allowed on `OBJECT \| FIELD_DEFINITION` and is ignored when additional modes exist. diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java index 2cbda32ef9..1478f76eda 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java @@ -60,8 +60,12 @@ public class JwtSignatureVerifier { .build()); } - /** Package-private for tests: injects a client pointed at a local fixture server. */ - JwtSignatureVerifier(ObjectMapper objectMapper, HttpClient httpClient) { + /** + * Injects a caller-supplied client, so tests (including {@code OidcAuthValidatorTest} in the + * AppSync auth package, which points it at a local fixture server) don't have to reach the + * real network to exercise verification. + */ + public JwtSignatureVerifier(ObjectMapper objectMapper, HttpClient httpClient) { this.objectMapper = objectMapper; this.httpClient = httpClient; } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java index a7ea596de8..86548c571f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java @@ -97,7 +97,7 @@ public class AppSyncExecutionController { AppSyncAuthContext authContext; try { authContext = authMiddleware.authenticate( - headerMap(headers), api, authRequestInfo(parsed, headers)); + headerMap(headers), api, authRequestInfo(parsed, headers, body)); } catch (AppSyncTransportException e) { return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage()); } @@ -203,7 +203,7 @@ public class AppSyncExecutionController { return map; } - private AuthRequestInfo authRequestInfo(ParsedRequest parsed, HttpHeaders headers) { + private AuthRequestInfo authRequestInfo(ParsedRequest parsed, HttpHeaders headers, String rawBody) { String accountId = requestContext.getAccountId() != null ? requestContext.getAccountId() : "000000000000"; String region = requestContext.getRegion() != null ? requestContext.getRegion() : "us-east-1"; String requestId = headers.getHeaderString("x-amzn-RequestId"); @@ -218,7 +218,8 @@ public class AppSyncExecutionController { requestId, accountId, region, - headerMap(headers)); + headerMap(headers), + rawBody); } private static List sourceIp(HttpHeaders headers) { diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthRequestInfo.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthRequestInfo.java index 0219f40d38..d4b45c9f57 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthRequestInfo.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthRequestInfo.java @@ -11,11 +11,13 @@ public record AuthRequestInfo( String requestId, String accountId, String region, - Map requestHeaders + Map requestHeaders, + String rawBody ) { public AuthRequestInfo { sourceIp = sourceIp == null ? List.of() : List.copyOf(sourceIp); variables = variables == null ? Map.of() : Map.copyOf(variables); requestHeaders = requestHeaders == null ? Map.of() : Map.copyOf(requestHeaders); + rawBody = rawBody == null ? "" : rawBody; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidator.java index 2344aa57cc..92f67b846f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidator.java @@ -1,28 +1,50 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cognito.CognitoService; +import io.github.hectorvent.floci.services.cognito.model.UserPool; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; import java.time.Clock; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +/** + * Verifies a Cognito user pool bearer token the same way real AppSync does: a valid RS256 + * signature from the pool's own signing key, a {@code kid} that names that key, and the pool's + * real issuer, on top of the existing expiry/audience checks. + * + *

The signing key is read directly off the {@link UserPool} model rather than fetched over + * HTTP from the emulator's own {@code .well-known/jwks.json}: Floci's Cognito emulator and AppSync + * run in the same process, so there is a real key to read in memory, and looping back over HTTP to + * ourselves would only add a network dependency a unit test would otherwise need to fake. + */ @ApplicationScoped public class CognitoAuthValidator { private final JwtClaimsDecoder jwtClaimsDecoder; + private final CognitoService cognitoService; private final Clock clock; @Inject - public CognitoAuthValidator(JwtClaimsDecoder jwtClaimsDecoder, Clock clock) { + public CognitoAuthValidator(JwtClaimsDecoder jwtClaimsDecoder, CognitoService cognitoService, Clock clock) { this.jwtClaimsDecoder = jwtClaimsDecoder; + this.cognitoService = cognitoService; this.clock = clock; } public Map validate(String authorization, Map userPoolConfig, List sourceIp) { Map claims = jwtClaimsDecoder.decode(authorization) .orElseThrow(AppSyncAuth::unauthorized); + verifySignature(authorization, userPoolConfig); if (claims.get("sub") == null || String.valueOf(claims.get("sub")).isBlank()) { throw AppSyncAuth.unauthorized(); } @@ -39,6 +61,59 @@ public class CognitoAuthValidator { return IdentityBuilder.cognito(claims, sourceIp, defaultAction); } + /** + * Fails closed: a missing/blank pool id, a pool this emulator never issued + * ({@code AwsException} from {@code describeUserPool}), an unsupported {@code alg}, a {@code kid} + * that does not name the pool's current signing key, or a signature that does not verify are all + * treated as verification failure, never as "unverifiable, so allow." + */ + private void verifySignature(String authorization, Map userPoolConfig) { + String poolId = userPoolConfig == null ? null : coerceString(userPoolConfig.get("userPoolId"), null); + if (poolId == null) { + throw AppSyncAuth.unauthorized(); + } + UserPool pool; + try { + pool = cognitoService.describeUserPool(poolId); + } catch (AwsException e) { + throw AppSyncAuth.unauthorized(); + } + Map header = jwtClaimsDecoder.decodeHeader(authorization) + .orElseThrow(AppSyncAuth::unauthorized); + if (!"RS256".equals(header.get("alg"))) { + throw AppSyncAuth.unauthorized(); + } + String kid = coerceString(header.get("kid"), null); + if (kid == null || !kid.equals(pool.getSigningKeyId())) { + throw AppSyncAuth.unauthorized(); + } + String token = jwtClaimsDecoder.rawToken(authorization).orElseThrow(AppSyncAuth::unauthorized); + int lastDot = token.lastIndexOf('.'); + String signingInput = token.substring(0, lastDot); + byte[] signature = Base64.getUrlDecoder().decode(pad(token.substring(lastDot + 1))); + if (!signatureValid(signingInput, signature, pool)) { + throw AppSyncAuth.unauthorized(); + } + } + + private boolean signatureValid(String signingInput, byte[] signature, UserPool pool) { + try { + byte[] encodedKey = Base64.getDecoder().decode(pool.getSigningPublicKey()); + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encodedKey)); + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(publicKey); + verifier.update(signingInput.getBytes(StandardCharsets.UTF_8)); + return verifier.verify(signature); + } catch (Exception e) { + return false; + } + } + + private static String pad(String value) { + int rem = value.length() % 4; + return rem == 0 ? value : value + "=".repeat(4 - rem); + } + boolean matchesProvider(Map claims, Map userPoolConfig) { return claims.get("sub") != null && unexpired(claims) @@ -63,7 +138,14 @@ public class CognitoAuthValidator { return expected != null && expected.equals(iss); } - static String expectedIssuer(Map config) { + /** + * The real emulator issuer for the configured pool ({@code cognitoService.getIssuer(poolId)}), + * unless the config carries an explicit override. There is no AWS-style + * {@code https://cognito-idp..amazonaws.com/} guess here any more: Floci's own + * Cognito emulator never signs a token with that issuer, so comparing against it could never + * match a genuine emulator-issued token. + */ + private String expectedIssuer(Map config) { if (config == null) { return null; } @@ -72,11 +154,7 @@ public class CognitoAuthValidator { return issuer; } String poolId = coerceString(config.get("userPoolId"), null); - String region = coerceString(config.get("awsRegion"), null); - if (poolId == null || region == null) { - return null; - } - return "https://cognito-idp." + region + ".amazonaws.com/" + poolId; + return poolId == null ? null : cognitoService.getIssuer(poolId); } private boolean audienceMatches(Map claims, Map config) { 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 00026a00cf..df9dec33d0 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 @@ -2,17 +2,56 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.AccountResolver; +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; import io.github.hectorvent.floci.services.iam.model.CallerContext; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import org.jboss.logging.Logger; +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.Locale; import java.util.Map; +/** + * Verifies the SigV4 signature on an AppSync GraphQL data-plane request, so {@code AWS_IAM} auth + * actually requires a signed caller rather than merely a well-formed {@code Credential=} value. + * + *

Scoped narrowly to this one endpoint: header-signed only (AppSync's SDKs never presign this + * call), signing service {@code "appsync"} (not {@code execute-api}), and a fixed canonical path of + * {@code /v1/apis/{apiId}/graphql} with no query string, since that is the endpoint's entire shape. + * Modeled on {@code ExecuteApiSigV4Authorizer} and {@code SigV4Validator}, which cannot be reused + * directly: both hardcode a different signing service name. + * + *

The well-known local-dev {@code test}/{@code test} credential pair is honoured as a known + * secret, exactly like every other SigV4 validator in this codebase: it still has to produce a + * valid signature, it is not a bypass of the signature check itself. No other unregistered access + * key is ever accepted, and an unresolvable key never falls back to a default secret or an + * account-root identity. + */ @ApplicationScoped public class IamAuthValidator { + private static final Logger LOG = Logger.getLogger(IamAuthValidator.class); + + private static final String ALGORITHM = "AWS4-HMAC-SHA256"; + private static final String SIGNING_SERVICE = "appsync"; + private static final String TERMINATOR = "aws4_request"; + 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 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; @@ -31,6 +70,7 @@ public class IamAuthValidator { if (accessKeyId == null || accessKeyId.isBlank()) { throw AppSyncAuth.unauthorized(); } + verifySignature(authorization, apiId, info, accessKeyId); if (!isEmulatorAllow(accessKeyId)) { CallerContext caller = iamService.resolveCallerContext(accessKeyId); if (caller != null) { @@ -43,11 +83,241 @@ public class IamAuthValidator { } } String userArn = iamService.resolveCallerArn(accessKeyId).orElseGet( - () -> "arn:aws:iam::" + nullToEmpty(info.accountId()) + ":root"); + () -> isEmulatorAllow(accessKeyId) ? "arn:aws:iam::" + nullToEmpty(info.accountId()) + ":root" + : null); + if (userArn == null) { + // resolveSecretKey already proved the key is registered, so this is unreachable for any + // real access key - only the legacy test/test pair has no IamService entry to resolve. + throw AppSyncAuth.unauthorized(); + } String username = usernameFromArn(userArn, accessKeyId); return IdentityBuilder.iam(info.accountId(), accessKeyId, username, userArn, info.sourceIp()); } + /** + * 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. + */ + private void verifySignature(String authorization, String apiId, AuthRequestInfo info, String accessKeyId) { + SignedRequest signed = headerSignedRequest(authorization, info.requestHeaders()); + if (signed == null) { + throw AppSyncAuth.unauthorized(); + } + CredentialScope scope = CredentialScope.parse(signed.credential()); + if (scope == null || !SIGNING_SERVICE.equals(scope.service()) || !accessKeyId.equals(scope.accessKeyId())) { + throw AppSyncAuth.unauthorized(); + } + Instant signedAt; + try { + signedAt = Instant.from(AMZ_DATE.parse(signed.amzDate())); + } catch (Exception e) { + throw AppSyncAuth.unauthorized(); + } + if (Math.abs(Instant.now().getEpochSecond() - signedAt.getEpochSecond()) > MAX_CLOCK_SKEW_SECONDS) { + throw AppSyncAuth.unauthorized(); + } + String secretKey = resolveSecretKey(accessKeyId); + if (secretKey == null) { + LOG.debugv("AppSync SigV4 request references unregistered access key={0}", sanitizeForLog(accessKeyId)); + throw AppSyncAuth.unauthorized(); + } + checkSessionToken(accessKeyId, info.requestHeaders()); + try { + String canonicalUri = "/v1/apis/" + apiId + "/graphql"; + String payloadHash = 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" + + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)); + byte[] signingKey = deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()); + String expected = hexEncode(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}", sanitizeForLog(accessKeyId)); + throw AppSyncAuth.unauthorized(); + } + } catch (AppSyncTransportException e) { + throw e; + } catch (Exception e) { + LOG.debugv(e, "AppSync SigV4 verification failed to complete: {0}", e.getMessage()); + throw AppSyncAuth.unauthorized(); + } + } + + /** + * Resolves the secret backing an access key, or {@code null} for a credential this emulator + * will not authenticate. Never falls back to the access key id as its own secret and never + * mints a secret for a key {@link IamService} does not know: that is exactly what let an + * unregistered key sign its own requests before this fix. + */ + private String resolveSecretKey(String accessKeyId) { + if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) { + return LEGACY_SECRET_KEY; + } + return iamService.findSecretKey(accessKeyId).orElse(null); + } + + /** + * Rejects a temporary ({@code ASIA...}) credential that does not present the session token + * Floci issued with it. Mirrors {@code ExecuteApiSigV4Authorizer.checkSessionToken}: a matching + * secret alone is not the whole credential, since AWS requires the session token on every + * request made with temporary credentials to confirm it is live and genuinely STS-issued. + * + *

The token is compared against the value recorded at mint time, not merely required to be + * present, so a fabricated token is rejected along with a missing one. A session recorded + * before Floci tracked tokens has no issued value to compare against ({@code findSessionToken} + * is empty there), so presence is all that can be demanded of it: rejecting that case would + * lock out an otherwise valid credential. + * + *

The token does not need to ride in {@code SignedHeaders}: comparing it against the issued + * value binds it regardless of where it rode, the same way the execute-api authorizer does. + */ + private void checkSessionToken(String accessKeyId, Map requestHeaders) { + if (!IamService.isTemporaryAccessKey(accessKeyId)) { + return; + } + String presented = header(requestHeaders, SECURITY_TOKEN); + if (isBlank(presented)) { + LOG.debugv("AppSync SigV4 request uses temporary credential accessKey={0} with no {1}", + sanitizeForLog(accessKeyId), SECURITY_TOKEN); + throw AppSyncAuth.unauthorized(); + } + String issued = iamService.findSessionToken(accessKeyId).orElse(null); + if (issued == null) { + return; + } + if (!MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8), + presented.getBytes(StandardCharsets.UTF_8))) { + LOG.debugv("AppSync SigV4 request presents a session token that does not match the one" + + " issued for accessKey={0}", sanitizeForLog(accessKeyId)); + throw AppSyncAuth.unauthorized(); + } + } + + 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) { + if (authorization == null) { + return null; + } + String trimmed = authorization.trim(); + if (!trimmed.regionMatches(true, 0, ALGORITHM, 0, ALGORITHM.length())) { + return null; + } + Map parameters = new LinkedHashMap<>(); + 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()); + } + } + String credential = parameters.get("Credential"); + String signedHeaders = parameters.get("SignedHeaders"); + String signature = parameters.get("Signature"); + String amzDate = header(requestHeaders, "X-Amz-Date"); + if (isBlank(credential) || isBlank(signedHeaders) || isBlank(signature) || isBlank(amzDate)) { + return null; + } + return new SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature, amzDate); + } + + private record CredentialScope(String accessKeyId, String date, String region, String service) { + + String credentialScope() { + return date + "/" + region + "/" + service + "/" + TERMINATOR; + } + + static CredentialScope parse(String credential) { + if (credential == null) { + return null; + } + String[] parts = credential.split("/"); + if (parts.length != 5 || !TERMINATOR.equals(parts[4])) { + return null; + } + if (parts[0].isBlank() || parts[1].length() != 8 || parts[2].isBlank() || parts[3].isBlank()) { + return null; + } + return new CredentialScope(parts[0], parts[1], parts[2], parts[3].toLowerCase(Locale.ROOT)); + } + } + + private static String canonicalHeaders(String signedHeaders, Map requestHeaders) { + StringBuilder canonical = new StringBuilder(); + for (String name : signedHeaders.split(";")) { + canonical.append(name).append(':').append(normalizeHeaderValue(header(requestHeaders, name))).append('\n'); + } + return canonical.toString(); + } + + private static String header(Map headers, String name) { + if (headers == null) { + return ""; + } + String direct = headers.get(name); + if (direct != null) { + return direct; + } + for (Map.Entry entry : headers.entrySet()) { + if (entry.getKey() != null && entry.getKey().equalsIgnoreCase(name)) { + return entry.getValue() == null ? "" : entry.getValue(); + } + } + return ""; + } + + private static String normalizeHeaderValue(String value) { + return value == null ? "" : value.trim().replaceAll("\\s+", " "); + } + + private static byte[] deriveSigningKey(String secretKey, String date, String region, String service) + throws Exception { + byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8); + byte[] kDate = hmacSha256(kSecret, date); + byte[] kRegion = hmacSha256(kDate, region); + byte[] kService = hmacSha256(kRegion, service); + return hmacSha256(kService, TERMINATOR); + } + + 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(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16)); + } + return hex.toString(); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } + + /** Strips control characters from attacker-controlled values before they reach a log line. */ + private static String sanitizeForLog(String value) { + return value == null ? null : value.replaceAll("\\p{Cntrl}", ""); + } + public boolean isFieldDenied(String accessKeyId, String fieldArn) { if (accessKeyId == null || isEmulatorAllow(accessKeyId)) { return false; diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java index f96dbe7381..832e8a0ecb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java @@ -21,6 +21,35 @@ public class JwtClaimsDecoder { } public Optional> decode(String authorization) { + return part(authorization, 1).flatMap(this::readMap); + } + + /** The JWT header segment ({@code alg}, {@code kid}, ...), decoded the same way as the claims. */ + public Optional> decodeHeader(String authorization) { + return part(authorization, 0).flatMap(this::readMap); + } + + /** The bare JWT (no {@code Bearer } prefix), only when it has the three dot-separated segments. */ + public Optional rawToken(String authorization) { + return bearerToken(authorization).filter(token -> token.split("\\.", -1).length == 3); + } + + private Optional> readMap(String base64UrlSegment) { + try { + byte[] json = Base64.getUrlDecoder().decode(pad(base64UrlSegment)); + return Optional.of(objectMapper.readValue(json, new TypeReference<>() {})); + } catch (Exception e) { + return Optional.empty(); + } + } + + private static Optional part(String authorization, int index) { + return bearerToken(authorization).map(token -> token.split("\\.", -1)) + .filter(parts -> parts.length == 3) + .map(parts -> parts[index]); + } + + private static Optional bearerToken(String authorization) { if (authorization == null || authorization.isBlank()) { return Optional.empty(); } @@ -28,17 +57,7 @@ public class JwtClaimsDecoder { if (authorization.regionMatches(true, 0, "Bearer ", 0, 7)) { token = authorization.substring(7).trim(); } - String[] parts = token.split("\\.", -1); - if (parts.length != 3) { - return Optional.empty(); - } - try { - byte[] json = Base64.getUrlDecoder().decode(pad(parts[1])); - Map claims = objectMapper.readValue(json, new TypeReference<>() {}); - return Optional.of(claims); - } catch (Exception e) { - return Optional.empty(); - } + return Optional.of(token); } private static String pad(String value) { diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidator.java index 1b45196cfc..1ff3655b75 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidator.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth; +import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -7,15 +8,24 @@ import java.time.Clock; import java.util.Map; import java.util.regex.Pattern; +/** + * Verifies an OIDC bearer token's RS256 signature against the configured provider's own JWKS, + * reusing {@link JwtSignatureVerifier} (already used by the HTTP API JWT authorizer): it fetches + * {@code {issuer}/.well-known/openid-configuration}, resolves the token's {@code kid} against the + * JWKS it points to, and fails closed on any network error, unreachable issuer, unsupported + * algorithm, or unmatched key. + */ @ApplicationScoped public class OidcAuthValidator { private final JwtClaimsDecoder jwtClaimsDecoder; + private final JwtSignatureVerifier jwtSignatureVerifier; private final Clock clock; @Inject - public OidcAuthValidator(JwtClaimsDecoder jwtClaimsDecoder, Clock clock) { + public OidcAuthValidator(JwtClaimsDecoder jwtClaimsDecoder, JwtSignatureVerifier jwtSignatureVerifier, Clock clock) { this.jwtClaimsDecoder = jwtClaimsDecoder; + this.jwtSignatureVerifier = jwtSignatureVerifier; this.clock = clock; } @@ -26,6 +36,7 @@ public class OidcAuthValidator { ) { Map claims = jwtClaimsDecoder.decode(authorization) .orElseThrow(AppSyncAuth::unauthorized); + verifySignature(authorization, oidcConfig); if (claims.get("sub") == null || String.valueOf(claims.get("sub")).isBlank()) { throw AppSyncAuth.unauthorized(); } @@ -41,6 +52,25 @@ public class OidcAuthValidator { return IdentityBuilder.oidc(claims); } + /** + * Verifies against the configured issuer's JWKS regardless of {@code skipIssuer}: + * that configured URL is the only OIDC provider this API trusts, so it is what signs the keys + * to check against even when the token's own {@code iss} claim is not separately asserted to + * equal it. + */ + private void verifySignature(String authorization, Map oidcConfig) { + String issuer = oidcConfig == null ? null : CognitoAuthValidator.coerceString(oidcConfig.get("issuer"), null); + if (issuer == null) { + throw AppSyncAuth.unauthorized(); + } + String token = jwtClaimsDecoder.rawToken(authorization).orElseThrow(AppSyncAuth::unauthorized); + try { + jwtSignatureVerifier.verify(token, issuer); + } catch (JwtSignatureVerifier.JwtVerificationException e) { + throw AppSyncAuth.unauthorized(); + } + } + boolean matchesProvider(Map claims, Map oidcConfig, boolean skipIssuer) { return claims.get("sub") != null && timestampsValid(claims, oidcConfig) diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java index 0b8244ddef..c2ef2c2b3b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java @@ -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 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) diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthMiddlewareTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthMiddlewareTest.java index 1d2803e5c7..f781602477 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthMiddlewareTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/AuthMiddlewareTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java index 4c46d90ecc..961558fa57 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java @@ -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 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 claims = baseClaims(); claims.put("cognito:username", "alice"); - Map identity = validator.validate("Bearer " + jwt(claims), config, List.of("127.0.0.1")); + Map 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 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 claims = baseClaims(); + + assertThrows(AppSyncTransportException.class, + () -> validator.validate( + "Bearer " + signedJwt(claims, KEY_ID, forgedKey), config, List.of())); + } + + @Test + void tokenWithUnknownKidIs401() throws Exception { + Map 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 claims = baseClaims(); + + assertThrows(AppSyncTransportException.class, + () -> validator.validate( + "Bearer " + signedJwt(claims, KEY_ID, privateKey), config, List.of())); + } + + @Test + void expiredJwtIs401() throws Exception { Map 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 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 missing = validator.validate("Bearer " + jwt(baseClaims()), config, List.of()); + void wrongIssuerIs401() throws Exception { + Map 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 missing = validator.validate( + "Bearer " + signedJwt(baseClaims(), KEY_ID, privateKey), config, List.of()); assertNull(missing.get("groups")); Map emptyClaims = baseClaims(); emptyClaims.put("cognito:groups", List.of()); - Map empty = validator.validate("Bearer " + jwt(emptyClaims), config, List.of()); + Map empty = validator.validate( + "Bearer " + signedJwt(emptyClaims, KEY_ID, privateKey), config, List.of()); assertEquals(List.of(), empty.get("groups")); } private Map baseClaims() { Map 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 claims) { - return JwtClaimsDecoder.encode(claims, mapper); + private String signedJwt(Map 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)); } } 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 7221d32906..867bbc2dcf 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 @@ -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 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 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 signed = AppSyncRequestSigner.signedHeaders( + "api-1", HOST, BODY, "AKIAGOOD", "good-secret", REGION, Instant.now()); Map 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 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 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 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 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 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 signed = AppSyncRequestSigner.signedHeaders( + "api-1", HOST, BODY, "test", "test", REGION, Instant.now()); + Map 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 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 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 signed = signedWithSessionToken("ASIALIVE", "session-secret", "issued-token"); + + Map 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 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())); + signed.put("X-Amz-Security-Token", token); + return signed; + } + @Test void fieldArnDenyDetected() { when(iamService.resolveCallerContext("AKIAGOOD")).thenReturn(CallerContext.of(List.of(FIELD_DENY))); diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/LambdaAuthorizerValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/LambdaAuthorizerValidatorTest.java index 1269426e7d..44ad76711a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/LambdaAuthorizerValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/LambdaAuthorizerValidatorTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java index 90467ff47d..44b7b86910 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java @@ -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 config = config("https://configured-issuer", "my-client"); + void soleModeSkipsIssuerClaimButStillVerifiesSignatureAgainstConfiguredIssuer() throws Exception { + Map config = config(issuer, "my-client"); Map claims = baseClaims("https://other-issuer", "my-client"); - Map identity = validator.validate("Bearer " + jwt(claims), config, true); + Map 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 config = config("https://configured-issuer", "my-client"); + void multiModeEnforcesIssuerClaim() throws Exception { + Map config = config(issuer, "my-client"); Map 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 config = config("https://issuer", "my-client"); + void iatTtlExceededIs401() throws Exception { + Map config = config(issuer, "my-client"); config.put("iatTTL", 60); - Map claims = baseClaims("https://issuer", "my-client"); + Map 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 config = config("https://issuer", "client-.*"); - Map claims = baseClaims("https://issuer", "other"); + void clientIdRegexMatchesAzp() throws Exception { + Map config = config(issuer, "client-.*"); + Map claims = baseClaims(issuer, "other"); claims.remove("aud"); claims.put("azp", "client-99"); - Map identity = validator.validate("Bearer " + jwt(claims), config, true); + Map identity = validator.validate( + "Bearer " + signedJwt(claims, KEY_ID, privateKey), config, true); assertEquals("sub-1", identity.get("sub")); } @Test - void clientIdMismatchIs401() { - Map config = config("https://issuer", "client-1"); - Map claims = baseClaims("https://issuer", "nope"); + void clientIdMismatchIs401() throws Exception { + Map config = config(issuer, "client-1"); + Map 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 config = config(issuer, "my-client"); + Map 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 config = config(issuer, "my-client"); + Map claims = baseClaims(issuer, "my-client"); + + assertThrows(AppSyncTransportException.class, + () -> validator.validate("Bearer " + signedJwt(claims, KEY_ID, forgedKey), config, true)); + } + + @Test + void unreachableIssuerFailsClosed() throws Exception { + Map config = config("http://127.0.0.1:1", "my-client"); // nothing listening + Map 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 config(String issuer, String clientId) { @@ -89,7 +189,33 @@ class OidcAuthValidatorTest { return claims; } - private String jwt(Map claims) { - return JwtClaimsDecoder.encode(claims, mapper); + private String signedJwt(Map 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); } } diff --git a/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java new file mode 100644 index 0000000000..5b07c81e6e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java @@ -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. + * + *

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 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 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(); + } +}