Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(apigateway): verify and propagate HTTP API v2 JWT authorizer claims (#2353)

Jay0444753eb85f
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
index 9b65d74394..47313268f9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.apigateway.model.Stage;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
+import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
import io.github.hectorvent.floci.services.apigatewayv2.websocket.ConnectionInfo;
@@ -92,6 +93,7 @@ public class ApiGatewayExecuteController {
private final ElbV2Service elbV2Service;
private final SqsQueryHandler sqsQueryHandler;
private final ApiGatewayExecuteRouteContext routeContext;
+ private final JwtSignatureVerifier jwtSignatureVerifier;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
@@ -101,7 +103,8 @@ public class ApiGatewayExecuteController {
WebSocketConnectionManager webSocketConnectionManager,
ElbV2Service elbV2Service,
SqsQueryHandler sqsQueryHandler,
- ApiGatewayExecuteRouteContext routeContext) {
+ ApiGatewayExecuteRouteContext routeContext,
+ JwtSignatureVerifier jwtSignatureVerifier) {
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
@@ -113,6 +116,7 @@ public class ApiGatewayExecuteController {
this.elbV2Service = elbV2Service;
this.sqsQueryHandler = sqsQueryHandler;
this.routeContext = routeContext;
+ this.jwtSignatureVerifier = jwtSignatureVerifier;
}
/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */
@@ -1340,9 +1344,11 @@ public class ApiGatewayExecuteController {
.type(MediaType.APPLICATION_JSON).build();
}
+ Map<String, String> jwtClaims = null;
if ("JWT".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
- Response authError = enforceJwtAuthorizer(region, apiId, route, headers, uriInfo);
- if (authError != null) return authError;
+ JwtAuthorizerResult jwtResult = enforceJwtAuthorizer(region, apiId, route, headers, uriInfo);
+ if (jwtResult.errorResponse() != null) return jwtResult.errorResponse();
+ jwtClaims = jwtResult.claims();
}
if ("CUSTOM".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
@@ -1373,7 +1379,8 @@ public class ApiGatewayExecuteController {
if (integrationType == null || integrationType.isEmpty()) integrationType = "AWS_PROXY";
if ("HTTP_PROXY".equalsIgnoreCase(integrationType)) {
- return dispatchHttpProxyV2(integration, route, httpMethod, path, headers, uriInfo, body, apiId, stageName);
+ return dispatchHttpProxyV2(integration, route, httpMethod, path, headers, uriInfo, body,
+ apiId, stageName, jwtClaims);
}
String functionName = functionNameFromUri(integration.getIntegrationUri());
@@ -1385,7 +1392,7 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(),
- apiId, region, stageName, headers, uriInfo, body, requestId);
+ apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
@@ -1409,7 +1416,7 @@ public class ApiGatewayExecuteController {
private Response dispatchHttpProxyV2(io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration,
Route route, String httpMethod, String path,
HttpHeaders headers, UriInfo uriInfo, byte[] body,
- String apiId, String stageName) {
+ String apiId, String stageName, Map<String, String> jwtClaims) {
// CDK HttpAlbIntegration sets integrationUri to an ALB listener ARN. Resolve it
// to the listener's bound localhost port so HttpProxyInvoker (which assumes a
// concrete http(s) URL) can forward through the listener's data plane.
@@ -1442,14 +1449,14 @@ public class ApiGatewayExecuteController {
}
Map<String, String> pathParams = extractV2PathParams(route.getRouteKey(), path);
- Map<String, Object> claims = Map.of();
- if ("JWT".equalsIgnoreCase(route.getAuthorizationType())) {
- String token = extractBearerToken(headers);
- if (token != null) {
- Map<String, Object> parsed = parseAllJwtClaims(token);
- if (parsed != null) claims = parsed;
- }
- }
+ // Reuses the claims dispatchV2 already verified via enforceJwtAuthorizer, rather than
+ // independently re-extracting a token and re-parsing it here: extractBearerToken only
+ // reads the Authorization header, ignoring the authorizer's configured identitySource
+ // (which - see HttpApiJwtAuthorizerQuerystringTest - can be a querystring parameter). A
+ // caller passing a valid token via the configured source plus an unrelated Bearer header
+ // would otherwise have $context.authorizer.claims.* resolve from the unverified header
+ // token instead of the one the authorizer actually checked.
+ Map<String, Object> claims = jwtClaims != null ? Map.copyOf(jwtClaims) : Map.of();
String sourceIp = requestHeaders.getOrDefault("X-Forwarded-For", "127.0.0.1");
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
@@ -1515,28 +1522,6 @@ public class ApiGatewayExecuteController {
return copy;
}
- private static String extractBearerToken(HttpHeaders headers) {
- String auth = headers.getHeaderString("Authorization");
- if (auth == null) return null;
- if (auth.startsWith("Bearer ")) return auth.substring("Bearer ".length()).trim();
- return null;
- }
-
- /** Extracts ALL JWT claims as a Map<String,Object> for use as $context.authorizer.claims.X source values. */
- private Map<String, Object> parseAllJwtClaims(String token) {
- try {
- String[] parts = token.split("\\.");
- if (parts.length < 2) return null;
- byte[] payloadBytes = Base64.getUrlDecoder().decode(padBase64(parts[1]));
- String payload = new String(payloadBytes, StandardCharsets.UTF_8);
- JsonNode root = objectMapper.readTree(payload);
- return objectMapper.convertValue(root, MAP_TYPE);
- } catch (Exception e) {
- LOG.debugv("JWT full-claims parse error: {0}", e.getMessage());
- return null;
- }
- }
-
/**
* Captures path parameters from a route key like {@code "ANY /wallet/{proxy+}"} matched
* against an actual path. Compiled regexes are cached per route key so the regex is
@@ -1570,43 +1555,65 @@ public class ApiGatewayExecuteController {
/** Extracts parameter names from a route template; the pattern itself is constant. */
private static final Pattern ROUTE_PARAM_NAMES = Pattern.compile("\\{([a-zA-Z_]+)\\+?\\}");
- private Response enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers,
+ // Mirrors AuthorizerResult's shape (used by the v1/REST CUSTOM-authorizer path) for the same
+ // reason: a null errorResponse means "authorized, proceed", and claims (when non-null) is what
+ // the caller threads through to buildV2ProxyEvent so requestContext.authorizer.jwt.claims is
+ // actually populated - previously this information was parsed and validated, then discarded.
+ private record JwtAuthorizerResult(Response errorResponse, Map<String, String> claims) {}
+
+ private JwtAuthorizerResult enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers,
UriInfo uriInfo) {
Authorizer authorizer;
try {
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
} catch (AwsException e) {
- return Response.status(500)
+ return new JwtAuthorizerResult(Response.status(500)
.entity(jsonMessage("Authorizer not found"))
- .type(MediaType.APPLICATION_JSON).build();
+ .type(MediaType.APPLICATION_JSON).build(), null);
}
String token = extractToken(authorizer, headers, uriInfo);
if (token == null) {
- return Response.status(401)
+ return new JwtAuthorizerResult(Response.status(401)
.entity(jsonMessage("Unauthorized"))
- .type(MediaType.APPLICATION_JSON).build();
+ .type(MediaType.APPLICATION_JSON).build(), null);
+ }
+
+ // Signature verification happens before anything in the payload is trusted (including the
+ // exp/iss/aud checks below) - a claim from an unverified token proves nothing about who
+ // sent it. Mirrors what real API Gateway's JWT authorizer does against the issuer's real
+ // JWKS; failure here (bad signature, unreachable issuer, unsupported alg) is a 401 the same
+ // as any other rejection, not a fallback to unverified acceptance.
+ String configuredIssuer = authorizer.getJwtConfiguration() != null
+ ? authorizer.getJwtConfiguration().issuer() : null;
+ try {
+ jwtSignatureVerifier.verify(token, configuredIssuer);
+ } catch (JwtSignatureVerifier.JwtVerificationException e) {
+ LOG.debugv("JWT signature verification failed for API {0}: {1}", apiId, e.getMessage());
+ return new JwtAuthorizerResult(Response.status(401)
+ .entity(jsonMessage("Unauthorized"))
+ .type(MediaType.APPLICATION_JSON).build(), null);
}
JwtClaims claims = parseJwtClaims(token);
if (claims == null) {
- return Response.status(401)
+ return new JwtAuthorizerResult(Response.status(401)
.entity(jsonMessage("Unauthorized"))
- .type(MediaType.APPLICATION_JSON).build();
+ .type(MediaType.APPLICATION_JSON).build(), null);
}
if (claims.exp > 0 && claims.exp < System.currentTimeMillis() / 1000) {
- return Response.status(401)
+ return new JwtAuthorizerResult(Response.status(401)
.entity(jsonMessage("The incoming token has expired"))
- .type(MediaType.APPLICATION_JSON).build();
+ .type(MediaType.APPLICATION_JSON).build(), null);
}
if (authorizer.getJwtConfiguration() != null) {
String issuer = authorizer.getJwtConfiguration().issuer();
if (issuer != null && !issuer.isBlank() && !issuer.equals(claims.iss)) {
- return Response.status(401)
+ return new JwtAuthorizerResult(Response.status(401)
.entity(jsonMessage("Unauthorized"))
- .type(MediaType.APPLICATION_JSON).build();
+ .type(MediaType.APPLICATION_JSON).build(), null);
}
List<String> audiences = authorizer.getJwtConfiguration().audience();
@@ -1616,14 +1623,14 @@ public class ApiGatewayExecuteController {
boolean audMatch = audiences.stream().anyMatch(a ->
a.equals(claims.aud) || a.equals(claims.clientId));
if (!audMatch) {
- return Response.status(401)
+ return new JwtAuthorizerResult(Response.status(401)
.entity(jsonMessage("Unauthorized"))
- .type(MediaType.APPLICATION_JSON).build();
+ .type(MediaType.APPLICATION_JSON).build(), null);
}
}
}
- return null; // authorized
+ return new JwtAuthorizerResult(null, claims.raw); // authorized
}
// ──────────────────────────── HTTP API v2 Lambda REQUEST authorizer ────────────────────────────
@@ -1920,7 +1927,11 @@ public class ApiGatewayExecuteController {
return value;
}
- private record JwtClaims(String iss, String aud, String clientId, long exp) {}
+ // `raw` carries every claim the token actually presented (as strings, since that's the shape
+ // requestContext.authorizer.jwt.claims uses on real AWS - a Lambda reads e.g. "sub" out of it
+ // the same way regardless of provider), so enforceJwtAuthorizer's caller can propagate the full
+ // set into the outgoing Lambda event instead of only the fields needed for verification.
+ private record JwtClaims(String iss, String aud, String clientId, long exp, Map<String, String> raw) {}
private JwtClaims parseJwtClaims(String token) {
try {
@@ -1935,7 +1946,20 @@ public class ApiGatewayExecuteController {
// JWT authorizers accept either when matching the configured audience list.
String clientId = claims.path("client_id").asText(null);
long exp = claims.path("exp").asLong(0);
- return new JwtClaims(iss, aud, clientId, exp);
+
+ // AWS's real requestContext.authorizer.jwt.claims flattens every claim to a string,
+ // including non-scalar ones (arrays/objects become their JSON text) - mirrored here
+ // rather than dropping or restructuring anything, since callers may read any claim
+ // name, not just the ones this method itself validates.
+ Map<String, String> raw = new java.util.LinkedHashMap<>();
+ java.util.Iterator<Map.Entry<String, JsonNode>> fields = claims.fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> field = fields.next();
+ JsonNode value = field.getValue();
+ raw.put(field.getKey(), value.isTextual() ? value.asText() : value.toString());
+ }
+
+ return new JwtClaims(iss, aud, clientId, exp, raw);
} catch (Exception e) {
LOG.debugv("JWT parse error: {0}", e.getMessage());
return null;
@@ -1954,6 +1978,19 @@ public class ApiGatewayExecuteController {
String apiId, String region, String stageName,
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId) {
+ return buildV2ProxyEvent(httpMethod, path, routeKey, apiId, region, stageName,
+ headers, uriInfo, body, requestId, null);
+ }
+
+ // jwtClaims is non-null only when the route's authorizer is JWT-type and verification
+ // succeeded (see dispatchV2/enforceJwtAuthorizer) - null means either no authorizer on this
+ // route (Auth: NONE) or a CUSTOM/REQUEST authorizer. Unlike the v1/REST CUSTOM-authorizer
+ // path (buildV1ProxyEvent's principalId/context handling), a v2 CUSTOM/REQUEST authorizer's
+ // response context is not currently threaded into requestContext.authorizer here at all.
+ String buildV2ProxyEvent(String httpMethod, String path, String routeKey,
+ String apiId, String region, String stageName,
+ HttpHeaders headers, UriInfo uriInfo,
+ byte[] body, String requestId, Map<String, String> jwtClaims) {
ObjectNode event = objectMapper.createObjectNode();
event.put("version", "2.0");
event.put("routeKey", routeKey != null ? routeKey : "$default");
@@ -2001,6 +2038,27 @@ public class ApiGatewayExecuteController {
http.put("userAgent", headers.getHeaderString("User-Agent") != null
? headers.getHeaderString("User-Agent") : "");
+ // Matches AWS's real HTTP API JWT authorizer shape: requestContext.authorizer.jwt.claims
+ // retains the token's claims, while jwt.scopes contains the standard OAuth2 scope claim
+ // split on whitespace. This differs from the v1/REST CUSTOM-authorizer shape
+ // (requestContext.authorizer.principalId/<claim>) built elsewhere in this class.
+ // Previously enforceJwtAuthorizer's claims were discarded instead of reaching here, so
+ // this node was never present at all.
+ if (jwtClaims != null && !jwtClaims.isEmpty()) {
+ ObjectNode authorizerNode = ctx.putObject("authorizer");
+ ObjectNode jwtNode = authorizerNode.putObject("jwt");
+ ObjectNode claimsNode = jwtNode.putObject("claims");
+ jwtClaims.forEach(claimsNode::put);
+
+ String scopeClaim = jwtClaims.get("scope");
+ if (scopeClaim != null && !scopeClaim.isBlank()) {
+ ArrayNode scopesNode = jwtNode.putArray("scopes");
+ for (String scope : scopeClaim.trim().split("\\s+")) {
+ scopesNode.add(scope);
+ }
+ }
+ }
+
if (body != null && body.length > 0) {
boolean isText = isV2TextContentType(headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
event.put("body", isText
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
new file mode 100644
index 0000000000..2cbda32ef9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java
@@ -0,0 +1,245 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.math.BigInteger;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.Signature;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.RSAPublicKeySpec;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Verifies the RS256 signature of a token presented to an HTTP API v2 JWT authorizer, the same
+ * way real API Gateway does: fetch {@code {issuer}/.well-known/openid-configuration} to discover
+ * {@code jwks_uri}, fetch the JWK Set from there, select the key matching the token's {@code kid},
+ * and verify. Nothing here is Floci-specific — this is a generic OIDC-relying-party check against
+ * whatever issuer a JWT authorizer is configured with (Cognito, Auth0, Okta, ...), not a lookup
+ * against Floci's own emulated Cognito keys.
+ *
+ * <p>Per-issuer JWKS are cached (see {@link #CACHE_TTL}) so repeat requests to the same route
+ * don't refetch the discovery document and key set on every call.
+ *
+ * <p>Fails closed: a network error, an unreachable issuer, an unsupported algorithm ({@code none}
+ * included), or no matching key are all treated as verification failure, not as "unverifiable, so
+ * allow." A local emulator that can't reach the real issuer must reject, since silently accepting
+ * would reopen exactly the unauthenticated-claims gap this class exists to close.
+ */
+@ApplicationScoped
+public class JwtSignatureVerifier {
+
+ private static final Logger LOG = Logger.getLogger(JwtSignatureVerifier.class);
+
+ private static final Duration CACHE_TTL = Duration.ofMinutes(10);
+ private static final Duration HTTP_TIMEOUT = Duration.ofSeconds(10);
+
+ private final ObjectMapper objectMapper;
+ private final HttpClient httpClient;
+ private final Map<String, CachedJwks> jwksCache = new ConcurrentHashMap<>();
+
+ @Inject
+ public JwtSignatureVerifier(ObjectMapper objectMapper) {
+ this(objectMapper, HttpClient.newBuilder()
+ .version(HttpClient.Version.HTTP_1_1)
+ .connectTimeout(HTTP_TIMEOUT)
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .build());
+ }
+
+ /** Package-private for tests: injects a client pointed at a local fixture server. */
+ JwtSignatureVerifier(ObjectMapper objectMapper, HttpClient httpClient) {
+ this.objectMapper = objectMapper;
+ this.httpClient = httpClient;
+ }
+
+ public static class JwtVerificationException extends Exception {
+ public JwtVerificationException(String message) {
+ super(message);
+ }
+
+ public JwtVerificationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ }
+
+ private record CachedJwks(Map<String, RSAPublicKey> keysByKid, Instant fetchedAt) {
+ boolean isExpired() {
+ return Instant.now().isAfter(fetchedAt.plus(CACHE_TTL));
+ }
+ }
+
+ /**
+ * Verifies {@code token}'s signature against {@code issuer}'s published JWKS.
+ *
+ * @throws JwtVerificationException if the token is not RS256, the issuer's discovery/JWKS
+ * endpoints are unreachable or malformed, no key matches the
+ * token's {@code kid}, or the signature does not verify.
+ */
+ public void verify(String token, String issuer) throws JwtVerificationException {
+ if (issuer == null || issuer.isBlank()) {
+ throw new JwtVerificationException("JWT authorizer has no configured issuer");
+ }
+
+ String[] parts = token == null ? new String[0] : token.split("\\.", -1);
+ if (parts.length != 3) {
+ throw new JwtVerificationException("Token is not a well-formed JWT");
+ }
+
+ JsonNode header = decodeJson(parts[0])
+ .orElseThrow(() -> new JwtVerificationException("Token header is not valid JSON"));
+ String alg = header.path("alg").asText("");
+ if (!"RS256".equals(alg)) {
+ throw new JwtVerificationException(
+ "Unsupported token signing algorithm: " + (alg.isEmpty() ? "none" : alg));
+ }
+ String kid = header.path("kid").asText(null);
+ if (kid == null || kid.isBlank()) {
+ throw new JwtVerificationException("Token header has no kid");
+ }
+
+ RSAPublicKey key = resolveKey(issuer, kid);
+ if (key == null) {
+ throw new JwtVerificationException(
+ "No JWKS key matches kid '" + kid + "' for issuer " + issuer);
+ }
+
+ if (!signatureValid(parts[0] + "." + parts[1], parts[2], key)) {
+ throw new JwtVerificationException("Token signature is invalid");
+ }
+ }
+
+ private RSAPublicKey resolveKey(String issuer, String kid) throws JwtVerificationException {
+ CachedJwks cached = jwksCache.get(issuer);
+ if (cached != null && !cached.isExpired()) {
+ RSAPublicKey key = cached.keysByKid().get(kid);
+ if (key != null) {
+ return key;
+ }
+ // A cached-but-stale key set (e.g. the issuer rotated keys) is worth one refetch
+ // before giving up, rather than waiting out the full TTL.
+ }
+
+ Map<String, RSAPublicKey> fetched = fetchJwks(issuer);
+ jwksCache.put(issuer, new CachedJwks(fetched, Instant.now()));
+ return fetched.get(kid);
+ }
+
+ private Map<String, RSAPublicKey> fetchJwks(String issuer) throws JwtVerificationException {
+ String jwksUri = fetchJwksUri(issuer);
+ JsonNode jwks = httpGetJson(jwksUri, "JWKS document");
+
+ JsonNode keys = jwks.path("keys");
+ if (!keys.isArray()) {
+ throw new JwtVerificationException("JWKS document at " + jwksUri + " has no keys array");
+ }
+
+ Map<String, RSAPublicKey> result = new ConcurrentHashMap<>();
+ for (JsonNode jwk : keys) {
+ String kty = jwk.path("kty").asText("");
+ String kid = jwk.path("kid").asText(null);
+ if (!"RSA".equals(kty) || kid == null || kid.isBlank()) {
+ continue; // non-RSA or unidentifiable keys can't back an RS256 check
+ }
+ String n = jwk.path("n").asText(null);
+ String e = jwk.path("e").asText(null);
+ if (n == null || e == null) {
+ continue;
+ }
+ try {
+ result.put(kid, toRsaPublicKey(n, e));
+ } catch (GeneralSecurityException | IllegalArgumentException ex) {
+ LOG.debugv("Skipping unparsable JWKS entry for issuer {0}, kid {1}: {2}",
+ issuer, kid, ex.getMessage());
+ }
+ }
+ return result;
+ }
+
+ private String fetchJwksUri(String issuer) throws JwtVerificationException {
+ String discoveryUrl = issuer.replaceAll("/+$", "") + "/.well-known/openid-configuration";
+ JsonNode discovery = httpGetJson(discoveryUrl, "OIDC discovery document");
+ String jwksUri = discovery.path("jwks_uri").asText(null);
+ if (jwksUri == null || jwksUri.isBlank()) {
+ throw new JwtVerificationException(
+ "OIDC discovery document at " + discoveryUrl + " has no jwks_uri");
+ }
+ return jwksUri;
+ }
+
+ private JsonNode httpGetJson(String url, String description) throws JwtVerificationException {
+ HttpRequest request;
+ try {
+ request = HttpRequest.newBuilder()
+ .uri(URI.create(url))
+ .timeout(HTTP_TIMEOUT)
+ .GET()
+ .build();
+ } catch (IllegalArgumentException e) {
+ throw new JwtVerificationException("Invalid " + description + " URL: " + url, e);
+ }
+
+ try {
+ HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
+ if (response.statusCode() != 200) {
+ throw new JwtVerificationException(
+ "Fetching " + description + " from " + url + " returned HTTP " + response.statusCode());
+ }
+ return objectMapper.readTree(response.body());
+ } catch (JwtVerificationException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new JwtVerificationException("Failed to fetch " + description + " from " + url, e);
+ }
+ }
+
+ private RSAPublicKey toRsaPublicKey(String n, String e) throws GeneralSecurityException {
+ BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(n)));
+ BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(e)));
+ RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
+ return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
+ }
+
+ private boolean signatureValid(String signingInput, String encodedSignature, RSAPublicKey publicKey) {
+ try {
+ Signature signature = Signature.getInstance("SHA256withRSA");
+ signature.initVerify(publicKey);
+ signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
+ return signature.verify(Base64.getUrlDecoder().decode(padBase64(encodedSignature)));
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
+ LOG.debugv("JWT signature check failed: {0}", e.getMessage());
+ return false;
+ }
+ }
+
+ private java.util.Optional<JsonNode> decodeJson(String base64UrlSegment) {
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(padBase64(base64UrlSegment));
+ JsonNode node = objectMapper.readTree(decoded);
+ return node != null && node.isObject() ? java.util.Optional.of(node) : java.util.Optional.empty();
+ } catch (IllegalArgumentException | java.io.IOException e) {
+ return java.util.Optional.empty();
+ }
+ }
+
+ private static String padBase64(String base64) {
+ return switch (base64.length() % 4) {
+ case 2 -> base64 + "==";
+ case 3 -> base64 + "=";
+ default -> base64;
+ };
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java
index 89069a6f7f..74803e6668 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java
@@ -35,7 +35,7 @@ class ApiGatewayExecuteControllerTest {
return new ApiGatewayExecuteController(
null, null, null,
regionResolver, objectMapper, null,
- null, null, null, null, new ApiGatewayExecuteRouteContext());
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null);
}
@Test
@@ -235,7 +235,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext());
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null);
Response response = controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -265,7 +265,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext());
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null);
controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -299,7 +299,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext());
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null);
controller.dispatch("GET", "restapi1", "prod", "hello", headers, null, null);
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
index bc7e1e86bc..1bdd5cca2c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
@@ -36,7 +36,7 @@ class ApiGatewayProxyMatchTest {
ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService,
new RegionResolver("us-east-1", "000000000000"),
new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,
- new ApiGatewayExecuteRouteContext());
+ new ApiGatewayExecuteRouteContext(), null);
}
private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java
index d7db4161c7..6cdcb3ac19 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java
@@ -50,7 +50,7 @@ class BuildV2ProxyEventBodyEncodingTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, objectMapper, null,
- null, null, null, null, new ApiGatewayExecuteRouteContext()
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null
);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java
new file mode 100644
index 0000000000..46c6691baa
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java
@@ -0,0 +1,122 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.UriInfo;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.net.URI;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Verifies that {@link ApiGatewayExecuteController#buildV2ProxyEvent} populates
+ * {@code requestContext.authorizer.jwt.claims} for HTTP API (V2) routes whose JWT authorizer
+ * verified successfully - previously this information was parsed and validated by
+ * enforceJwtAuthorizer, then discarded rather than propagated to the Lambda event.
+ */
+class BuildV2ProxyEventJwtClaimsTest {
+
+ private ApiGatewayExecuteController controller;
+ private HttpHeaders headers;
+ private UriInfo uriInfo;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ RegionResolver regionResolver = mock(RegionResolver.class);
+ when(regionResolver.getAccountId()).thenReturn("000000000000");
+
+ headers = mock(HttpHeaders.class);
+ when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
+ when(headers.getHeaderString("User-Agent")).thenReturn(null);
+
+ uriInfo = mock(UriInfo.class);
+ when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
+ when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/v1/things"));
+
+ controller = new ApiGatewayExecuteController(
+ null, null, null,
+ regionResolver, new ObjectMapper(), null,
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null
+ );
+ }
+
+ @Test
+ void populatesAuthorizerJwtClaimsWhenPresent() throws Exception {
+ Map<String, String> claims = new LinkedHashMap<>();
+ claims.put("sub", "user_01ABC");
+ claims.put("iss", "https://example.authkit.app");
+
+ String json = controller.buildV2ProxyEvent(
+ "POST", "/v1/things", "$default",
+ "abc123", "us-east-2", "$default", headers, uriInfo, null, "req-1", claims);
+ JsonNode event = new ObjectMapper().readTree(json);
+
+ JsonNode jwtClaims = event.at("/requestContext/authorizer/jwt/claims");
+ assertFalse(jwtClaims.isMissingNode(), "requestContext.authorizer.jwt.claims must be present");
+ assertEquals("user_01ABC", jwtClaims.get("sub").asText());
+ assertEquals("https://example.authkit.app", jwtClaims.get("iss").asText());
+ }
+
+ @Test
+ void populatesAuthorizerJwtScopesFromSpaceDelimitedScopeClaim() throws Exception {
+ Map<String, String> claims = new LinkedHashMap<>();
+ claims.put("sub", "user_01ABC");
+ claims.put("scope", "read:things write:things");
+
+ String json = controller.buildV2ProxyEvent(
+ "POST", "/v1/things", "$default",
+ "abc123", "us-east-2", "$default", headers, uriInfo, null, "req-4", claims);
+ JsonNode event = new ObjectMapper().readTree(json);
+
+ JsonNode scopes = event.at("/requestContext/authorizer/jwt/scopes");
+ assertTrue(scopes.isArray(), "requestContext.authorizer.jwt.scopes must be an array");
+ assertEquals(2, scopes.size());
+ assertEquals("read:things", scopes.get(0).asText());
+ assertEquals("write:things", scopes.get(1).asText());
+ }
+
+ @Test
+ void omitsScopesWhenScopeClaimAbsent() throws Exception {
+ Map<String, String> claims = new LinkedHashMap<>();
+ claims.put("sub", "user_01ABC");
+
+ String json = controller.buildV2ProxyEvent(
+ "POST", "/v1/things", "$default",
+ "abc123", "us-east-2", "$default", headers, uriInfo, null, "req-5", claims);
+ JsonNode event = new ObjectMapper().readTree(json);
+
+ assertFalse(event.at("/requestContext/authorizer/jwt").has("scopes"),
+ "scopes must be absent when the token has no scope claim");
+ }
+
+ @Test
+ void omitsAuthorizerNodeWhenClaimsAreNull() throws Exception {
+ String json = controller.buildV2ProxyEvent(
+ "GET", "/v1/things", "$default",
+ "abc123", "us-east-2", "$default", headers, uriInfo, null, "req-2", null);
+ JsonNode event = new ObjectMapper().readTree(json);
+
+ assertFalse(event.get("requestContext").has("authorizer"),
+ "requestContext.authorizer must be absent for routes with no JWT authorizer claims (Auth: NONE or CUSTOM)");
+ }
+
+ @Test
+ void omitsAuthorizerNodeWhenClaimsAreEmpty() throws Exception {
+ String json = controller.buildV2ProxyEvent(
+ "GET", "/v1/things", "$default",
+ "abc123", "us-east-2", "$default", headers, uriInfo, null, "req-3", Map.of());
+ JsonNode event = new ObjectMapper().readTree(json);
+
+ assertFalse(event.get("requestContext").has("authorizer"),
+ "requestContext.authorizer must be absent when claims map is empty");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
index 6b1519f19a..46edab3deb 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
@@ -41,7 +41,7 @@ class BuildV2ProxyEventPathParametersTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext()
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null
);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java
index 228b1e1beb..ee186c4f49 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java
@@ -1,13 +1,25 @@
package io.github.hectorvent.floci.services.apigatewayv2;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+import java.math.BigInteger;
+import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import static io.restassured.RestAssured.given;
@@ -18,10 +30,11 @@ import static org.hamcrest.Matchers.notNullValue;
* identity sources, not just {@code $request.header.*} — a template/API call configuring
* a query-string token source must not 401 a request carrying a valid token there.
*
- * <p>Tokens here are unsigned (header.payload.signature-shaped strings whose payload is
- * plain base64url JSON) — {@code ApiGatewayExecuteController.parseJwtClaims} doesn't verify
- * a signature, matching this emulator's local-dev scope, so no real signing key is needed
- * to exercise the extraction and claims-matching logic under test.
+ * <p>Tokens here are real RS256-signed JWTs verified against a local fixture server serving
+ * {@code /.well-known/openid-configuration} and a JWKS document — {@code JwtSignatureVerifier}
+ * checks every JWT authorizer's token against its issuer's real published keys (the same as real
+ * API Gateway), so an unsigned or wrongly-signed token is correctly rejected regardless of which
+ * identity source carried it.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -32,8 +45,54 @@ class HttpApiJwtAuthorizerQuerystringTest {
private static String routeId;
private static String authorizerId;
- private static final String ISSUER = "https://issuer.example.com";
+ private static HttpServer issuerServer;
+ private static String ISSUER;
private static final String AUDIENCE = "my-client-id";
+ private static final String KEY_ID = "test-key-1";
+
+ private static RSAPrivateKey privateKey;
+ private static RSAPublicKey publicKey;
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ @BeforeAll
+ static void startIssuerServer() throws Exception {
+ KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
+ gen.initialize(2048);
+ KeyPair pair = gen.generateKeyPair();
+ privateKey = (RSAPrivateKey) pair.getPrivate();
+ publicKey = (RSAPublicKey) pair.getPublic();
+
+ issuerServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ ISSUER = "http://127.0.0.1:" + issuerServer.getAddress().getPort();
+
+ issuerServer.createContext("/.well-known/openid-configuration", exchange -> {
+ String body = "{\"issuer\":\"" + ISSUER + "\",\"jwks_uri\":\"" + ISSUER + "/jwks\"}";
+ 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();
+ });
+ issuerServer.createContext("/jwks", exchange -> {
+ 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 + "\"}]}";
+ 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();
+ });
+ issuerServer.start();
+ }
+
+ @AfterAll
+ static void stopIssuerServer() {
+ if (issuerServer != null) {
+ issuerServer.stop(0);
+ }
+ }
@Test
@Order(1)
@@ -100,13 +159,14 @@ class HttpApiJwtAuthorizerQuerystringTest {
@Test
@Order(10)
- void requestWithValidTokenInQueryStringIsAuthorized() {
+ void requestWithValidTokenInQueryStringIsAuthorized() throws Exception {
// The integration target isn't a real reachable backend, so a successful proxy
// round-trip isn't asserted here — only that the request got past the authorizer.
// Before the fix, an invalid/missing token (or a source type extractToken can't read)
// 401s before ever reaching the integration; getting a 502 (backend unreachable) rather
- // than a 401 proves the querystring token was actually extracted and accepted.
- String token = fakeJwt(ISSUER, AUDIENCE);
+ // than a 401 proves the querystring token was actually extracted, signature-verified,
+ // and accepted.
+ String token = signedJwt(ISSUER, AUDIENCE);
given()
.when().get("/execute-api/" + httpApiId + "/test/hello?token=" + token)
@@ -123,11 +183,11 @@ class HttpApiJwtAuthorizerQuerystringTest {
@Test
@Order(30)
- void requestWithValidTokenOnlyInHeaderIsUnauthorizedWhenSourceIsQuerystring() {
+ void requestWithValidTokenOnlyInHeaderIsUnauthorizedWhenSourceIsQuerystring() throws Exception {
// The authorizer's IdentitySource is $request.querystring.token, not a header — a
// token presented via Authorization must not satisfy an identity source it wasn't
// configured for.
- String token = fakeJwt(ISSUER, AUDIENCE);
+ String token = signedJwt(ISSUER, AUDIENCE);
given()
.header("Authorization", "Bearer " + token)
@@ -135,15 +195,85 @@ class HttpApiJwtAuthorizerQuerystringTest {
.then().statusCode(401);
}
- private static String fakeJwt(String issuer, String audience) {
- String header = base64Url("{\"alg\":\"none\"}");
- String payload = base64Url(
- "{\"iss\":\"" + issuer + "\",\"aud\":\"" + audience + "\",\"exp\":9999999999}");
- return header + "." + payload + ".signature";
+ @Test
+ @Order(40)
+ void requestWithForgedSignatureInQueryStringIsUnauthorized() throws Exception {
+ // Same kid, same claims, but signed with an unrelated keypair — this must not verify
+ // against the issuer's real published key.
+ KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
+ gen.initialize(2048);
+ RSAPrivateKey forgedKey = (RSAPrivateKey) gen.generateKeyPair().getPrivate();
+ String token = signedJwt(ISSUER, AUDIENCE, forgedKey);
+
+ given()
+ .when().get("/execute-api/" + httpApiId + "/test/hello?token=" + token)
+ .then().statusCode(401);
+ }
+
+ @Test
+ @Order(50)
+ void requestWithValidSignatureButExpiredTokenIsUnauthorized() throws Exception {
+ // Signature verification (checked first) passes here - this exercises the exp check
+ // that runs afterward, which a change to the check ordering could otherwise silently
+ // skip without any test catching it.
+ String token = signedJwt(ISSUER, AUDIENCE, privateKey, 1L); // epoch second 1: long expired
+
+ given()
+ .when().get("/execute-api/" + httpApiId + "/test/hello?token=" + token)
+ .then().statusCode(401);
+ }
+
+ @Test
+ @Order(60)
+ void requestWithValidSignatureButWrongAudienceIsUnauthorized() throws Exception {
+ // Same: signature is genuinely valid, only the aud claim is wrong, isolating the
+ // audience check from the signature check that now runs ahead of it.
+ String token = signedJwt(ISSUER, "someone-elses-client-id");
+
+ given()
+ .when().get("/execute-api/" + httpApiId + "/test/hello?token=" + token)
+ .then().statusCode(401);
+ }
+
+ private static String signedJwt(String issuer, String audience) throws Exception {
+ return signedJwt(issuer, audience, privateKey, 9999999999L);
+ }
+
+ private static String signedJwt(String issuer, String audience, RSAPrivateKey signingKey) throws Exception {
+ return signedJwt(issuer, audience, signingKey, 9999999999L);
+ }
+
+ private static String signedJwt(String issuer, String audience, RSAPrivateKey signingKey, long exp)
+ throws Exception {
+ ObjectNode header = OBJECT_MAPPER.createObjectNode();
+ header.put("alg", "RS256");
+ header.put("typ", "JWT");
+ header.put("kid", KEY_ID);
+
+ ObjectNode payload = OBJECT_MAPPER.createObjectNode();
+ payload.put("iss", issuer);
+ payload.put("aud", audience);
+ payload.put("exp", exp);
+
+ 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 json) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(json.getBytes(StandardCharsets.UTF_8));
}
+
+ private static String base64UrlUnsigned(BigInteger value) {
+ byte[] bytes = value.toByteArray();
+ if (bytes.length > 1 && bytes[0] == 0) {
+ bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
+ }
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java
new file mode 100644
index 0000000000..97b6e05036
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java
@@ -0,0 +1,243 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.sun.net.httpserver.HttpServer;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.math.BigInteger;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Base64;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Regression test: an HTTP_PROXY integration on a JWT-authorized route maps
+ * {@code $context.authorizer.claims.*} into the outgoing backend request from the token the
+ * authorizer actually verified — not from a second, independently (and previously unverified)
+ * parsed token.
+ *
+ * <p>Before the fix, {@code dispatchHttpProxyV2} re-extracted a token from the
+ * {@code Authorization} header (regardless of the authorizer's configured identity source) and
+ * re-parsed its claims without checking the signature. This authorizer's identity source is a
+ * query-string parameter, not a header, so a caller presenting a validly-signed token there
+ * *and* an unrelated, attacker-controlled {@code Authorization} header would have had claim
+ * mappings resolve from the unverified header token instead of the one the authorizer checked.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class HttpProxyJwtClaimsMappingIntegrationTest {
+
+ private static String httpApiId;
+ private static String routeId;
+
+ private static HttpServer issuerServer;
+ private static HttpServer backendServer;
+ private static String issuer;
+ private static final String AUDIENCE = "my-client-id";
+ private static final String KEY_ID = "test-key-1";
+
+ private static RSAPrivateKey privateKey;
+ private static RSAPublicKey publicKey;
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+ private static final AtomicReference<String> receivedSubHeader = new AtomicReference<>();
+
+ @BeforeAll
+ static void startFixtureServers() throws Exception {
+ KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
+ gen.initialize(2048);
+ KeyPair pair = gen.generateKeyPair();
+ privateKey = (RSAPrivateKey) pair.getPrivate();
+ publicKey = (RSAPublicKey) pair.getPublic();
+
+ issuerServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ issuer = "http://127.0.0.1:" + issuerServer.getAddress().getPort();
+ issuerServer.createContext("/.well-known/openid-configuration", exchange -> {
+ String body = "{\"issuer\":\"" + issuer + "\",\"jwks_uri\":\"" + issuer + "/jwks\"}";
+ 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();
+ });
+ issuerServer.createContext("/jwks", exchange -> {
+ 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 + "\"}]}";
+ 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();
+ });
+ issuerServer.start();
+
+ backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ backendServer.createContext("/", exchange -> {
+ receivedSubHeader.set(exchange.getRequestHeaders().getFirst("x-user-id"));
+ byte[] resp = "ok".getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(200, resp.length);
+ exchange.getResponseBody().write(resp);
+ exchange.close();
+ });
+ backendServer.start();
+ }
+
+ @AfterAll
+ static void stopFixtureServers() {
+ if (issuerServer != null) issuerServer.stop(0);
+ if (backendServer != null) backendServer.stop(0);
+ }
+
+ @Test
+ @Order(1)
+ void setup() {
+ httpApiId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"http-proxy-jwt-claims-mapping-test","protocolType":"HTTP"}
+ """)
+ .when().post("/v2/apis")
+ .then().statusCode(201)
+ .extract().path("apiId");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"stageName":"test"}
+ """)
+ .when().post("/v2/apis/" + httpApiId + "/stages")
+ .then().statusCode(201);
+
+ String backendUrl = "http://127.0.0.1:" + backendServer.getAddress().getPort();
+ String integrationId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"integrationType":"HTTP_PROXY","integrationUri":"%s","payloadFormatVersion":"1.0",\
+ "requestParameters":{"append:header.x-user-id":"$context.authorizer.claims.sub"}}
+ """.formatted(backendUrl))
+ .when().post("/v2/apis/" + httpApiId + "/integrations")
+ .then().statusCode(201)
+ .extract().path("integrationId");
+
+ routeId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"routeKey":"GET /hello","target":"integrations/%s"}
+ """.formatted(integrationId))
+ .when().post("/v2/apis/" + httpApiId + "/routes")
+ .then().statusCode(201)
+ .extract().path("routeId");
+
+ String authorizerId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"jwt-querystring-auth","authorizerType":"JWT",\
+ "identitySource":"$request.querystring.token",\
+ "jwtConfiguration":{"audience":["%s"],"issuer":"%s"}}
+ """.formatted(AUDIENCE, issuer))
+ .when().post("/v2/apis/" + httpApiId + "/authorizers")
+ .then().statusCode(201)
+ .extract().path("authorizerId");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"authorizationType":"JWT","authorizerId":"%s"}
+ """.formatted(authorizerId))
+ .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId)
+ .then().statusCode(200);
+ }
+
+ @Test
+ @Order(10)
+ void claimsMappingUsesTheVerifiedQuerystringTokenNotASpoofedHeaderToken() throws Exception {
+ receivedSubHeader.set(null);
+
+ // The authorizer's identitySource is the querystring token, and that's the one that
+ // gets verified — this token's claims are what $context.authorizer.claims.sub must
+ // resolve to. The Authorization header carries a different, entirely unsigned token
+ // naming a different subject; if the backend receives THAT subject, the vulnerability
+ // Greptile flagged (unverified header claims leaking into request mappings) is back.
+ String verifiedToken = signedJwt(issuer, AUDIENCE, "verified-user", privateKey);
+ String spoofedHeaderToken = unsignedJwt("attacker-controlled-user");
+
+ given()
+ .header("Authorization", "Bearer " + spoofedHeaderToken)
+ .when().get("/execute-api/" + httpApiId + "/test/hello?token=" + verifiedToken)
+ .then().statusCode(200);
+
+ assertEquals("verified-user", receivedSubHeader.get());
+ }
+
+ @Test
+ @Order(20)
+ void requestWithNoAuthorizationHeaderStillMapsTheVerifiedQuerystringToken() throws Exception {
+ receivedSubHeader.set(null);
+
+ String verifiedToken = signedJwt(issuer, AUDIENCE, "only-querystring-user", privateKey);
+
+ given()
+ .when().get("/execute-api/" + httpApiId + "/test/hello?token=" + verifiedToken)
+ .then().statusCode(200);
+
+ assertEquals("only-querystring-user", receivedSubHeader.get());
+ }
+
+ private static String signedJwt(String issuer, String audience, String subject, RSAPrivateKey signingKey)
+ throws Exception {
+ ObjectNode header = OBJECT_MAPPER.createObjectNode();
+ header.put("alg", "RS256");
+ header.put("typ", "JWT");
+ header.put("kid", KEY_ID);
+
+ ObjectNode payload = OBJECT_MAPPER.createObjectNode();
+ payload.put("iss", issuer);
+ payload.put("aud", audience);
+ payload.put("sub", subject);
+ payload.put("exp", 9999999999L);
+
+ 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 unsignedJwt(String subject) {
+ String header = base64Url("{\"alg\":\"none\"}");
+ String payload = base64Url("{\"sub\":\"" + subject + "\"}");
+ return header + "." + payload + ".";
+ }
+
+ private static String base64Url(String json) {
+ return Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(json.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static String base64UrlUnsigned(BigInteger value) {
+ byte[] bytes = value.toByteArray();
+ if (bytes.length > 1 && bytes[0] == 0) {
+ bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
+ }
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java
new file mode 100644
index 0000000000..c555c32a09
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java
@@ -0,0 +1,175 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.sun.net.httpserver.HttpServer;
+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.Duration;
+import java.util.Base64;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Verifies {@link JwtSignatureVerifier} against a real local OIDC discovery + JWKS server
+ * (following the {@code HttpProxyInvokerTest} pattern of a real {@code com.sun.net.httpserver}
+ * backend rather than a mock), and a real RS256-signed token - the same shape a real IdP's would
+ * take, since this class exists specifically to check tokens against a live issuer's real keys.
+ */
+class JwtSignatureVerifierTest {
+
+ private HttpServer server;
+ private String issuer;
+ private RSAPrivateKey privateKey;
+ private RSAPublicKey publicKey;
+ private JwtSignatureVerifier verifier;
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ @BeforeEach
+ 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", exchange -> {
+ String issuerUrl = "http://127.0.0.1:" + server.getAddress().getPort();
+ String body = "{\"issuer\":\"" + issuerUrl + "\",\"jwks_uri\":\"" + issuerUrl + "/jwks\"}";
+ 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();
+ });
+
+ server.createContext("/jwks", exchange -> {
+ String n = base64UrlUnsigned(publicKey.getModulus());
+ String e = base64UrlUnsigned(publicKey.getPublicExponent());
+ String body = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"test-key-1\",\"alg\":\"RS256\",\"use\":\"sig\","
+ + "\"n\":\"" + n + "\",\"e\":\"" + e + "\"}]}";
+ 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();
+ });
+
+ server.start();
+ issuer = "http://127.0.0.1:" + server.getAddress().getPort();
+
+ HttpClient client = HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(5))
+ .build();
+ verifier = new JwtSignatureVerifier(objectMapper, client);
+ }
+
+ @AfterEach
+ void tearDown() {
+ server.stop(0);
+ }
+
+ @Test
+ void verifiesATokenSignedWithTheMatchingKey() throws Exception {
+ String token = signToken("test-key-1", privateKey);
+ verifier.verify(token, issuer); // does not throw
+ }
+
+ @Test
+ void rejectsATokenSignedWithADifferentKey() throws Exception {
+ KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
+ gen.initialize(2048);
+ RSAPrivateKey forgedKey = (RSAPrivateKey) gen.generateKeyPair().getPrivate();
+
+ // kid still names the real key, but the signature was produced by an unrelated keypair -
+ // this is exactly what a forged token looks like on the wire.
+ String token = signToken("test-key-1", forgedKey);
+
+ assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
+ () -> verifier.verify(token, issuer));
+ }
+
+ @Test
+ void rejectsATokenWithNoMatchingKid() throws Exception {
+ String token = signToken("unknown-kid", privateKey);
+
+ assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
+ () -> verifier.verify(token, issuer));
+ }
+
+ @Test
+ void rejectsAnUnsignedAlgNoneToken() {
+ String header = base64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}");
+ String payload = base64Url("{\"sub\":\"user1\"}");
+ String token = header + "." + payload + ".";
+
+ JwtSignatureVerifier.JwtVerificationException ex = assertThrows(
+ JwtSignatureVerifier.JwtVerificationException.class,
+ () -> verifier.verify(token, issuer));
+ assertTrue(ex.getMessage().toLowerCase().contains("alg") || ex.getMessage().toLowerCase().contains("none"));
+ }
+
+ @Test
+ void rejectsWhenIssuerHasNoDiscoveryDocument() throws Exception {
+ String token = signToken("test-key-1", privateKey);
+
+ assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
+ () -> verifier.verify(token, "http://127.0.0.1:1")); // nothing listening
+ }
+
+ @Test
+ void rejectsWhenIssuerIsMissing() throws Exception {
+ String token = signToken("test-key-1", privateKey);
+
+ assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
+ () -> verifier.verify(token, null));
+ }
+
+ private String signToken(String kid, RSAPrivateKey signingKey) throws GeneralSecurityException {
+ ObjectNode header = objectMapper.createObjectNode();
+ header.put("alg", "RS256");
+ header.put("typ", "JWT");
+ header.put("kid", kid);
+
+ ObjectNode payload = objectMapper.createObjectNode();
+ payload.put("sub", "user1");
+ payload.put("iss", issuer);
+ payload.put("exp", System.currentTimeMillis() / 1000 + 3600);
+
+ 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 s) {
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(s.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static String base64UrlUnsigned(BigInteger value) {
+ byte[] bytes = value.toByteArray();
+ if (bytes.length > 1 && bytes[0] == 0) {
+ bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
+ }
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+}