mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(appsync): verify JWT signatures and SigV4 requests for GraphQL auth (#3541)
* fix(appsync): verify JWT signatures and SigV4 requests for GraphQL auth
Cognito and OIDC auth modes decoded JWT claims without checking the
signature, and AWS_IAM auth accepted any well-formed Credential= value
without verifying a real SigV4 signature. An unregistered IAM access
key also fell back to an account-root identity instead of being
rejected. Any of these let an attacker forge claims or an identity
for AppSync's GraphQL data-plane endpoint.
Cognito now verifies the token against the issuing user pool's own
RS256 signing key (alg, kid, issuer, expiry) instead of trusting the
decoded payload. OIDC verifies against the configured issuer's
published JWKS via OIDC discovery, reusing JwtSignatureVerifier (the
same verifier the HTTP API JWT authorizer uses), and fails closed on
an unreachable issuer or unsupported algorithm. AWS_IAM verifies a
real header-signed SigV4 request (service "appsync", fixed
/v1/apis/{apiId}/graphql canonical path): the Credential= access key
must resolve to a secret via IamService and the signature must match
the actual request, including its body. An unknown or unsigned key is
always rejected and never resolves to root; the legacy test/test pair
is still emulator-allow but must be signed like any other key.
JwtClaimsDecoder gained decodeHeader()/rawToken() so callers can check
alg/kid and hand the raw token to a signature verifier.
AuthRequestInfo carries the raw request body so IAM signature
verification can hash the real payload rather than trusting an
unsigned one.
* fix(appsync): bind session tokens to temporary IAM credentials
IamAuthValidator.resolveSecretKey resolved a temporary (ASIA...)
access key's session secret and verified the SigV4 signature, but
never checked X-Amz-Security-Token. A caller holding just the secret
could authenticate without presenting the session token AWS requires
to prove the credential is live and genuinely STS-issued.
checkSessionToken now mirrors ExecuteApiSigV4Authorizer: a temporary
key with no X-Amz-Security-Token header is rejected, a present token
is compared against the value IamService recorded at mint time with
MessageDigest.isEqual, and a session recorded before Floci tracked
tokens (no issued value to compare against) is not locked out by a
check it cannot satisfy. The token does not need to ride in
SignedHeaders; comparing it against the issued value binds it
regardless of where it rode.
Also drops the dead Date-header fallback in headerSignedRequest
(AMZ_DATE can never parse RFC 1123 output, so that branch never ran)
and fixes an em-dash in the AWS_IAM docs row.
* test(appsync): sign IAM data-plane requests in the auth integration test
Two AppSyncAuthIntegrationTest cases sent the bare Credential= header
that is enough for the management plane to the GraphQL endpoint and
expected 200. Now that AWS_IAM requests are verified as real SigV4,
that header is an unsigned request and gets 401, which is the intended
behaviour. Sign those two requests with AppSyncRequestSigner using the
legacy test credential; the cases that expect 401 for a dummy
signature are unchanged.
This commit is contained in:
1 parent
d83bc662e0
commit
f38a384e51
15 files changed
+960
-86
No files matched your search
+6
-2
@@ -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;
|
||||
}
|
||||
|
||||
+4
-3
@@ -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<String> sourceIp(HttpHeaders headers) {
|
||||
|
||||
+3
-1
@@ -11,11 +11,13 @@ public record AuthRequestInfo(
|
||||
String requestId,
|
||||
String accountId,
|
||||
String region,
|
||||
Map<String, String> requestHeaders
|
||||
Map<String, String> 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;
|
||||
}
|
||||
}
|
||||
+85
-7
@@ -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.
|
||||
*
|
||||
* <p>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<String, Object> validate(String authorization, Map<String, Object> userPoolConfig, List<String> sourceIp) {
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> claims, Map<String, Object> 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<String, Object> 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.<region>.amazonaws.com/<poolId>} 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<String, Object> 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<String, Object> claims, Map<String, Object> config) {
|
||||
|
||||
+271
-1
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String, String> 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<String, String> requestHeaders) {
|
||||
if (authorization == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = authorization.trim();
|
||||
if (!trimmed.regionMatches(true, 0, ALGORITHM, 0, ALGORITHM.length())) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> 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<String, String> 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<String, String> headers, String name) {
|
||||
if (headers == null) {
|
||||
return "";
|
||||
}
|
||||
String direct = headers.get(name);
|
||||
if (direct != null) {
|
||||
return direct;
|
||||
}
|
||||
for (Map.Entry<String, String> 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;
|
||||
|
||||
+30
-11
@@ -21,6 +21,35 @@ public class JwtClaimsDecoder {
|
||||
}
|
||||
|
||||
public Optional<Map<String, Object>> 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<Map<String, Object>> 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<String> rawToken(String authorization) {
|
||||
return bearerToken(authorization).filter(token -> token.split("\\.", -1).length == 3);
|
||||
}
|
||||
|
||||
private Optional<Map<String, Object>> 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<String> 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<String> 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<String, Object> 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) {
|
||||
|
||||
+31
-1
@@ -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<String, Object> 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 <em>configured</em> 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<String, Object> 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<String, Object> claims, Map<String, Object> oidcConfig, boolean skipIssuer) {
|
||||
return claims.get("sub") != null
|
||||
&& timestampsValid(claims, oidcConfig)
|
||||
|
||||
Reference in new issue
Block a user