mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(apigateway): verify and propagate HTTP API v2 JWT authorizer claims (#2353)
* fix(apigateway): propagate JWT authorizer claims to HTTP API v2 Lambda events
enforceJwtAuthorizer (the HttpApi v2 route path for AuthorizationType:
JWT) correctly verifies a token's issuer/audience/expiry, but discarded
the parsed claims on success instead of exposing them - so
buildV2ProxyEvent never populated requestContext.authorizer.jwt.claims
in the event sent to the Lambda, unlike the sibling CUSTOM/Lambda
REQUEST authorizer path, which does build and propagate a context.
Any Lambda relying solely on the native JWT authorizer's verified
identity (rather than re-verifying the token itself) saw no identity at
all, even though the token was accepted and the request let through.
Confirmed against a real downstream consumer (kbdb, migrating off
in-process token verification in favor of the native authorizer) -
every write route gated on the caller's authorizer-verified `sub`
failed after a real sam deploy to floci, despite passing identically
against real AWS API Gateway.
JwtClaims now retains every claim from the token payload (not just the
iss/aud/client_id/exp fields needed for verification), flattened to
strings the same way AWS's real requestContext.authorizer.jwt.claims
does. enforceJwtAuthorizer returns them via a new JwtAuthorizerResult
(mirroring the existing AuthorizerResult record used by the v1/REST
CUSTOM-authorizer path) instead of a bare Response, and dispatchV2
threads them through buildV2ProxyEvent's new claims parameter, which
attaches requestContext.authorizer.jwt.claims when present.
Verified against kbdb's real template.yaml + Ginkgo functional suite:
was 17/49 passing on Builds (every write-path spec 500ing with "no
verified identity from API Gateway authorizer"); now 385/385 across
all 10 suites.
* fix(apigateway): split JWT scope claim into requestContext.authorizer.jwt.scopes
buildV2ProxyEvent's new requestContext.authorizer.jwt.claims population
(previous commit) carries every claim verbatim, including a raw "scope"
string when present. Real AWS HTTP API JWT authorizers split that
standard OAuth2 space-delimited scope claim (RFC 6749 §3.3) into its
own requestContext.authorizer.jwt.scopes array instead - callers read
scopes from there, not by parsing claims.scope themselves (confirmed
against AWS's documented example payload, which shows a scopes key
alongside claims even when null).
Adds the split as an additional field alongside claims when a "scope"
claim is present and non-blank; omitted entirely otherwise, matching
how the sibling claims/authorizer nodes are already conditionally
built.
* fix(apigateway): verify HTTP API v2 JWT authorizer token signatures
enforceJwtAuthorizer checked a token's iss/aud/exp claims but never verified
the token was actually signed by its issuer - parseJwtClaims only base64-decoded
the JWT payload segment, so any well-formed token whose claimed iss/aud matched
the authorizer's configuration was accepted regardless of whether it was ever
signed by that issuer at all. This predates the claims-propagation fix in this
branch, but that fix raises the stakes: those unverified claims are now exposed
to the downstream Lambda as requestContext.authorizer.jwt.claims, the exact
field real AWS-integrated code trusts as a verified identity.
Adds JwtSignatureVerifier: does real OIDC discovery (GET
{issuer}/.well-known/openid-configuration -> jwks_uri) + JWKS fetch, matches
the token's kid, and verifies its RS256 signature against the resolved key -
the same mechanism real HTTP API JWT authorizers use against a real issuer, not
a Floci-specific shortcut (WebIdentityTokenVerifier's Floci-known-key pattern
doesn't apply here, since a JWT authorizer's issuer is an arbitrary external
IdP). Per-issuer JWKS are cached for 10 minutes so repeat requests to the same
route don't refetch on every call.
Wired into enforceJwtAuthorizer ahead of the existing iss/aud/exp checks -
nothing in the payload is trusted, including those claims, until the signature
itself is proven valid. Any verification failure (bad/forged signature, no
matching kid, unsupported alg including "none", unreachable issuer, missing
issuer config) is a 401, matching every other rejection path here; there is no
fallback to unverified acceptance; a local emulator that can't reach the real
issuer must reject; silently accepting would reopen the same gap.
Rewrote HttpApiJwtAuthorizerQuerystringTest, which previously used unsigned
alg:none tokens against a nonexistent issuer.example.com and asserted they
were accepted - that assumption is exactly what this fix removes. It now signs
real RS256 tokens against a local discovery/JWKS fixture server and adds a
forged-signature case, plus new expired-token and wrong-audience cases
covering the iss/aud/exp checks now that they run after signature
verification. JwtSignatureVerifierTest covers the verifier directly: valid
signature, forged signature (same kid, different key), unknown kid, alg:none,
unreachable issuer, and missing issuer.
* fix(apigateway): HTTP_PROXY JWT claim mappings use the verified token
dispatchHttpProxyV2 independently re-extracted a bearer token from the
Authorization header and re-parsed its claims (unverified) for use in
$context.authorizer.claims.* request-parameter mappings, instead of reusing
the claims dispatchV2 already verified via enforceJwtAuthorizer. The
authorizer's gate itself was not bypassed - a forged/invalid token still
401s before dispatchHttpProxyV2 runs - but extractBearerToken only reads the
Authorization header, ignoring the authorizer's configured identitySource
(which can be a querystring parameter, per HttpApiJwtAuthorizerQuerystringTest).
A caller presenting a validly-signed token via the configured source, plus an
unrelated attacker-controlled Authorization header, had claim mappings resolve
from that second unverified token rather than the one actually checked -
flagged in review as an unverified-claims path the signature-verification fix
in this branch didn't close.
dispatchHttpProxyV2 now takes the already-verified jwtClaims map dispatchV2
computed, instead of re-deriving it. extractBearerToken and parseAllJwtClaims
are now unused and removed.
HttpProxyJwtClaimsMappingIntegrationTest covers this end-to-end: an HTTP_PROXY
integration mapping $context.authorizer.claims.sub to a backend header, hit
with a verified querystring token plus a spoofed Authorization header, and
confirms the backend receives the verified subject - not the spoofed one, and
not nothing when no Authorization header is present at all. Reverting the fix
locally reproduced both failure modes before writing this description.
* fix(apigateway): correct scope-claim comment in HTTP API v2 JWT event
The comment claimed callers never see a raw "scope" claim, but
jwtClaims.forEach(claimsNode::put) copies it into .claims unmodified
before .scopes is split out separately, matching real AWS behavior.
This commit is contained in:
10 files changed
+1047
-74
No files matched your search
+110
-52
@@ -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
|
||||
|
||||
+245
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user