fix(apigateway): match measured JWT claim wire format and enforce route authorizationScopes (#2011)

behaviors still diverge from what real API Gateway delivers to a payload 2.0
AWS_PROXY Lambda (measured against a Cognito-backed HTTP API in ap-northeast-1,
2026-08-05; raw captures in #2011):

- Claim values: array claims rendered as their JSON text and null-valued claims
  as the string "null". Real events use the space-separated bracket form
  (cognito:groups -> "[admin poweruser]"), stringify scalars, omit null-valued
  claims entirely, and fall back to JSON text only for nested objects.
- jwt.scopes: any scope claim was split and surfaced. On real AWS a route
  without authorizationScopes renders "scopes": null even when the token
  carries a scope claim; a route with authorizationScopes surfaces the token's
  FULL scope list (scp array/string first, else scope split on whitespace),
  not the intersection with the route's scopes.
- Route.authorizationScopes did not exist, so scoped routes could not enforce
  anything. Routes now persist and return authorizationScopes on both
  management surfaces (REST and JSON 1.1), and enforcement rejects tokens
  whose scp/scope claim matches none of the route's scopes with
  403 {"message":"Forbidden"} after signature verification.

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
This commit is contained in:
mitsukado-shinagawaandmitsukado-shinagawa authored and GitHub committed 2026-08-19 20:03:33 -04:00
1 parent c33508651e
commit 498021087f
9 files changed
+609 -38

No files matched your search

@@ -2106,6 +2106,10 @@ public class ApiGatewayController {
node.put("routeKey", r.getRouteKey());
node.put("authorizationType", r.getAuthorizationType());
if (r.getAuthorizerId() != null) node.put("authorizerId", r.getAuthorizerId());
if (r.getAuthorizationScopes() != null && !r.getAuthorizationScopes().isEmpty()) {
ArrayNode scopes = node.putArray("authorizationScopes");
r.getAuthorizationScopes().forEach(scopes::add);
}
if (r.getTarget() != null) node.put("target", r.getTarget());
if (r.getRouteResponseSelectionExpression() != null) node.put("routeResponseSelectionExpression", r.getRouteResponseSelectionExpression());
return node;
@@ -1371,10 +1371,12 @@ public class ApiGatewayExecuteController {
}
Map<String, String> jwtClaims = null;
List<String> jwtScopes = null;
if ("JWT".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
JwtAuthorizerResult jwtResult = enforceJwtAuthorizer(region, apiId, route, headers, uriInfo);
if (jwtResult.errorResponse() != null) return jwtResult.errorResponse();
jwtClaims = jwtResult.claims();
jwtScopes = jwtResult.scopes();
}
if ("CUSTOM".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
@@ -1418,7 +1420,7 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(),
apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims);
apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims, jwtScopes);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
@@ -1585,7 +1587,14 @@ public class ApiGatewayExecuteController {
// 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) {}
// scopes is the validated token's full scope list when the route carries authorizationScopes,
// and null otherwise - real API Gateway only surfaces jwt.scopes on scoped routes (measured
// 2026-08, see enforceJwtAuthorizer).
private record JwtAuthorizerResult(Response errorResponse, Map<String, String> claims, List<String> scopes) {
JwtAuthorizerResult(Response errorResponse, Map<String, String> claims) {
this(errorResponse, claims, null);
}
}
private JwtAuthorizerResult enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers,
UriInfo uriInfo) {
@@ -1656,7 +1665,23 @@ public class ApiGatewayExecuteController {
}
}
return new JwtAuthorizerResult(null, claims.raw); // authorized
// Measured API Gateway behavior (2026-08, Cognito-backed HTTP API): a route with
// authorizationScopes rejects tokens whose scp/scope claim matches none of them with
// 403 {"message":"Forbidden"}, and surfaces the token's FULL scope list (not the
// intersection with the route's scopes) as jwt.scopes. Routes without
// authorizationScopes render jwt.scopes as null even when the token carries scopes.
List<String> routeScopes = route.getAuthorizationScopes();
List<String> tokenScopes = null;
if (routeScopes != null && !routeScopes.isEmpty()) {
tokenScopes = claims.scopes;
if (tokenScopes == null || tokenScopes.stream().noneMatch(routeScopes::contains)) {
return new JwtAuthorizerResult(Response.status(403)
.entity(jsonMessage("Forbidden"))
.type(MediaType.APPLICATION_JSON).build(), null);
}
}
return new JwtAuthorizerResult(null, claims.raw, tokenScopes); // authorized
}
// ──────────────────────────── HTTP API v2 Lambda REQUEST authorizer ────────────────────────────
@@ -1976,9 +2001,13 @@ public class ApiGatewayExecuteController {
// 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) {}
// `scopes` is the token's own scope list (scp claim first, else scope) or null when it has
// neither - kept separate from `raw` because scope matching needs the pre-rendered values.
// Package-private (like buildV2ProxyEvent) so the wire-format rendering is unit-testable.
record JwtClaims(String iss, String aud, String clientId, long exp,
Map<String, String> raw, List<String> scopes) {}
private JwtClaims parseJwtClaims(String token) {
JwtClaims parseJwtClaims(String token) {
try {
String[] parts = token.split("\\.");
if (parts.length < 2) return null;
@@ -1992,25 +2021,69 @@ public class ApiGatewayExecuteController {
String clientId = claims.path("client_id").asText(null);
long exp = claims.path("exp").asLong(0);
// 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.
// AWS's real requestContext.authorizer.jwt.claims flattens every claim to a string
// - mirrored here rather than dropping or restructuring anything, since callers may
// read any claim name, not just the ones this method itself validates. The exact
// per-type rendering is renderClaimValue's (measured, not JSON for arrays/nulls).
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());
String rendered = renderClaimValue(field.getValue());
if (rendered != null) raw.put(field.getKey(), rendered);
}
return new JwtClaims(iss, aud, clientId, exp, raw);
return new JwtClaims(iss, aud, clientId, exp, raw, deriveJwtScopes(claims));
} catch (Exception e) {
LOG.debugv("JWT parse error: {0}", e.getMessage());
return null;
}
}
/**
* Renders a claim value the way API Gateway's payload 2.0 JWT authorizer context does
* (measured against real HTTP APIs, 2026-08): strings as-is, numbers/booleans stringified,
* arrays as a space-separated bracket form (e.g. {@code cognito:groups} →
* {@code "[admin poweruser]"} - not JSON), null-valued claims omitted (returns null),
* nested objects as JSON text as a fallback.
*/
private static String renderClaimValue(JsonNode value) {
if (value == null || value.isNull()) return null;
if (value.isTextual()) return value.asText();
if (value.isArray()) {
StringBuilder sb = new StringBuilder("[");
for (JsonNode item : value) {
if (sb.length() > 1) sb.append(' ');
sb.append(item.isTextual() ? item.asText() : item.toString());
}
return sb.append(']').toString();
}
return value.toString();
}
/**
* Extracts the token's scope list from its payload: the {@code scp} claim (array, or
* space-separated string) wins, else the {@code scope} claim (either form - the string
* form is what Cognito access tokens use, e.g. {@code "read write"} → {@code [read, write]}).
* Returns null when the token carries neither - the claim pair API Gateway evaluates
* against a route's {@code authorizationScopes} and surfaces as {@code jwt.scopes}.
*/
private static List<String> deriveJwtScopes(JsonNode claims) {
for (String key : List.of("scp", "scope")) {
JsonNode value = claims.get(key);
if (value == null) continue;
if (value.isArray() && !value.isEmpty()) {
List<String> scopes = new java.util.ArrayList<>();
value.forEach(item -> scopes.add(item.isTextual() ? item.asText() : item.toString()));
return List.copyOf(scopes);
}
if (value.isTextual() && !value.asText().isBlank()) {
return List.of(value.asText().trim().split("\\s+"));
}
}
return null;
}
private static String padBase64(String base64) {
return switch (base64.length() % 4) {
case 2 -> base64 + "==";
@@ -2024,18 +2097,21 @@ public class ApiGatewayExecuteController {
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId) {
return buildV2ProxyEvent(httpMethod, path, routeKey, apiId, region, stageName,
headers, uriInfo, body, requestId, null);
headers, uriInfo, body, requestId, null, 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.
// route (Auth: NONE) or a CUSTOM/REQUEST authorizer. jwtScopes is non-null only when that
// route additionally carries authorizationScopes (see JwtAuthorizerResult). 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) {
byte[] body, String requestId, Map<String, String> jwtClaims,
List<String> jwtScopes) {
// The JAX-RS {proxy} binding strips a trailing slash, but rawPath is by contract the
// raw path and routers treat /x and /x/ as distinct routes. Recover it from the raw
// request URI for the event path fields. Route matching in dispatchV2 and the
@@ -2043,6 +2119,7 @@ public class ApiGatewayExecuteController {
// buildProxyEvent already does for REST (V1).
String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath());
ObjectNode event = objectMapper.createObjectNode();
event.put("version", "2.0");
event.put("routeKey", routeKey != null ? routeKey : "$default");
@@ -2091,23 +2168,24 @@ public class ApiGatewayExecuteController {
? 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.
// retains the token's claims, while jwt.scopes is null unless the route carries
// authorizationScopes - measured API Gateway (2026-08) renders "scopes": null on
// unscoped routes even when the token has a scope claim, and the token's full scope
// list (dispatch hands it over as jwtScopes) on scoped routes. 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()) {
if (jwtScopes == null) {
jwtNode.putNull("scopes");
} else {
ArrayNode scopesNode = jwtNode.putArray("scopes");
for (String scope : scopeClaim.trim().split("\\s+")) {
scopesNode.add(scope);
}
jwtScopes.forEach(scopesNode::add);
}
}
@@ -578,6 +578,10 @@ public class ApiGatewayV2JsonHandler {
node.put("RouteKey", r.getRouteKey());
node.put("AuthorizationType", r.getAuthorizationType());
if (r.getAuthorizerId() != null) node.put("AuthorizerId", r.getAuthorizerId());
if (r.getAuthorizationScopes() != null && !r.getAuthorizationScopes().isEmpty()) {
ArrayNode scopes = node.putArray("AuthorizationScopes");
r.getAuthorizationScopes().forEach(scopes::add);
}
if (r.getTarget() != null) node.put("Target", r.getTarget());
if (r.getRouteResponseSelectionExpression() != null) {
node.put("RouteResponseSelectionExpression", r.getRouteResponseSelectionExpression());
@@ -361,6 +361,9 @@ public class ApiGatewayV2Service {
route.setRouteKey((String) request.get("routeKey"));
route.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
route.setAuthorizerId((String) request.get("authorizerId"));
@SuppressWarnings("unchecked")
List<String> authorizationScopes = (List<String>) request.get("authorizationScopes");
route.setAuthorizationScopes(authorizationScopes);
route.setTarget((String) request.get("target"));
route.setRouteResponseSelectionExpression((String) request.get("routeResponseSelectionExpression"));
@@ -396,6 +399,11 @@ public class ApiGatewayV2Service {
if (request.containsKey("authorizerId") && request.get("authorizerId") != null) {
route.setAuthorizerId((String) request.get("authorizerId"));
}
if (request.containsKey("authorizationScopes") && request.get("authorizationScopes") != null) {
@SuppressWarnings("unchecked")
List<String> authorizationScopes = (List<String>) request.get("authorizationScopes");
route.setAuthorizationScopes(authorizationScopes);
}
if (request.containsKey("target") && request.get("target") != null) {
route.setTarget((String) request.get("target"));
}
@@ -10,6 +10,7 @@ public class Route {
private String routeKey;
private String authorizationType; // NONE, AWS_IAM, CUSTOM, JWT
private String authorizerId;
private java.util.List<String> authorizationScopes;
private String target; // integrations/{integrationId}
private String routeResponseSelectionExpression;
@@ -27,6 +28,9 @@ public class Route {
public String getAuthorizerId() { return authorizerId; }
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
public java.util.List<String> getAuthorizationScopes() { return authorizationScopes; }
public void setAuthorizationScopes(java.util.List<String> authorizationScopes) { this.authorizationScopes = authorizationScopes; }
public String getTarget() { return target; }
public void setTarget(String target) { this.target = target; }
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@@ -57,7 +58,7 @@ class BuildV2ProxyEventJwtClaimsTest {
String json = controller.buildV2ProxyEvent(
"POST", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-1", claims);
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-1", claims, null);
JsonNode event = new ObjectMapper().readTree(json);
JsonNode jwtClaims = event.at("/requestContext/authorizer/jwt/claims");
@@ -67,42 +68,52 @@ class BuildV2ProxyEventJwtClaimsTest {
}
@Test
void populatesAuthorizerJwtScopesFromSpaceDelimitedScopeClaim() throws Exception {
void populatesAuthorizerJwtScopesHandedOverByDispatch() throws Exception {
Map<String, String> claims = new LinkedHashMap<>();
claims.put("sub", "user_01ABC");
claims.put("scope", "read:things write:things");
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);
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-4", claims,
List.of("read:things", "write:things"));
JsonNode event = new ObjectMapper().readTree(json);
JsonNode scopes = event.at("/requestContext/authorizer/jwt/scopes");
JsonNode jwt = event.at("/requestContext/authorizer/jwt");
JsonNode scopes = jwt.get("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());
assertEquals("read:things write:things", jwt.at("/claims/scope").asText(),
"the raw scope claim itself stays in claims (matches real AWS events)");
}
@Test
void omitsScopesWhenScopeClaimAbsent() throws Exception {
void rendersScopesAsExplicitNullWhenDispatchHandsNone() throws Exception {
// Measured against real API Gateway (2026-08): a route WITHOUT authorizationScopes
// renders "scopes": null even when the token carries a scope claim, so the builder
// must not derive scopes from the claims map on its own.
Map<String, String> claims = new LinkedHashMap<>();
claims.put("sub", "user_01ABC");
claims.put("scope", "aws.cognito.signin.user.admin");
String json = controller.buildV2ProxyEvent(
"POST", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-5", claims);
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-5", claims, null);
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");
JsonNode jwt = event.at("/requestContext/authorizer/jwt");
assertTrue(jwt.has("scopes") && jwt.get("scopes").isNull(),
"scopes must be an explicit null for routes without authorizationScopes");
assertEquals("aws.cognito.signin.user.admin", jwt.at("/claims/scope").asText());
}
@Test
void omitsAuthorizerNodeWhenClaimsAreNull() throws Exception {
String json = controller.buildV2ProxyEvent(
"GET", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-2", null);
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-2", null, null);
JsonNode event = new ObjectMapper().readTree(json);
assertFalse(event.get("requestContext").has("authorizer"),
@@ -113,7 +124,7 @@ class BuildV2ProxyEventJwtClaimsTest {
void omitsAuthorizerNodeWhenClaimsAreEmpty() throws Exception {
String json = controller.buildV2ProxyEvent(
"GET", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-3", Map.of());
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-3", Map.of(), null);
JsonNode event = new ObjectMapper().readTree(json);
assertFalse(event.get("requestContext").has("authorizer"),
@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* Verifies that {@link ApiGatewayExecuteController#parseJwtClaims} flattens claim values into
* the exact strings real API Gateway delivers at {@code requestContext.authorizer.jwt.claims}
* (payload 2.0, measured against a Cognito-backed HTTP API 2026-08): strings as-is,
* numbers/booleans stringified, array claims in the space-separated bracket form
* ({@code cognito:groups} → {@code "[admin poweruser]"}, not JSON), null-valued claims omitted,
* nested objects as JSON text — plus the scp/scope-derived scope list used for
* {@code authorizationScopes} matching.
*/
class JwtClaimsWireFormatTest {
private ApiGatewayExecuteController controller;
@BeforeEach
void setUp() {
controller = new ApiGatewayExecuteController(
null, null, null,
null, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null
);
}
private static String unsignedToken(String claimsJson) {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
String header = enc.encodeToString("{\"alg\":\"RS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
String payload = enc.encodeToString(claimsJson.getBytes(StandardCharsets.UTF_8));
return header + "." + payload + ".sig";
}
@Test
void rendersClaimValuesInMeasuredWireFormat() {
ApiGatewayExecuteController.JwtClaims claims = controller.parseJwtClaims(unsignedToken("""
{
"sub": "user-123",
"exp": 9999999999,
"email_verified": true,
"cognito:groups": ["admin", "poweruser"],
"nickname": null,
"address": {"country": "JP"}
}
"""));
assertNotNull(claims);
assertEquals("user-123", claims.raw().get("sub"));
assertEquals("9999999999", claims.raw().get("exp"),
"numeric claims are stringified in the 2.0 payload");
assertEquals("true", claims.raw().get("email_verified"),
"boolean claims are stringified in the 2.0 payload");
assertEquals("[admin poweruser]", claims.raw().get("cognito:groups"),
"array claims use API Gateway's space-separated bracket form, not JSON");
assertFalse(claims.raw().containsKey("nickname"),
"null-valued claims are omitted, not rendered as \"null\"");
assertEquals("{\"country\":\"JP\"}", claims.raw().get("address"),
"nested object claims fall back to JSON text");
}
@Test
void derivesScopesFromScpArrayFirst() {
ApiGatewayExecuteController.JwtClaims claims = controller.parseJwtClaims(unsignedToken("""
{"sub": "u", "scp": ["orders/read", "orders/write"], "scope": "ignored"}
"""));
assertNotNull(claims);
assertEquals(List.of("orders/read", "orders/write"), claims.scopes(),
"the scp claim wins over scope when both are present");
}
@Test
void derivesScopesFromSpaceSeparatedScopeClaim() {
ApiGatewayExecuteController.JwtClaims claims = controller.parseJwtClaims(unsignedToken("""
{"sub": "u", "scope": "read write"}
"""));
assertNotNull(claims);
assertEquals(List.of("read", "write"), claims.scopes(),
"the Cognito access-token form: a space-separated scope string");
}
@Test
void scopesAreNullWhenTokenCarriesNeitherClaim() {
ApiGatewayExecuteController.JwtClaims claims = controller.parseJwtClaims(unsignedToken("""
{"sub": "u"}
"""));
assertNotNull(claims);
assertNull(claims.scopes(), "no scp/scope claim (the Cognito ID-token case) → null");
}
}
@@ -0,0 +1,306 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.io.ByteArrayOutputStream;
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.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
/**
* End-to-end coverage for JWT authorizer scope handling on HTTP API (v2) routes,
* matching behavior verified against real API Gateway (2026-08):
* <ul>
* <li>a route without {@code authorizationScopes} renders {@code jwt.scopes} as null
* even when the token carries a {@code scope} claim;</li>
* <li>a route with {@code authorizationScopes} surfaces the token's FULL scope list
* (not the intersection with the route's scopes) as a JSON array;</li>
* <li>a token whose scope claim matches none of the route's scopes is rejected with
* 403 {@code {"message":"Forbidden"}} (Cognito ID tokens have no scope claim);</li>
* <li>array claims like {@code cognito:groups} render in the space-separated bracket
* form ({@code "[admin poweruser]"}).</li>
* </ul>
*
* <p>Tokens are real RS256-signed JWTs verified against a local fixture issuer serving
* {@code /.well-known/openid-configuration} and a JWKS document, the same pattern as
* {@link HttpApiJwtAuthorizerQuerystringTest} — {@code JwtSignatureVerifier} rejects
* anything else before the scope checks run.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class HttpApiJwtAuthorizerScopesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String BACKEND_FN = "httpv2-jwt-scopes-backend-fn";
private static final String AUDIENCE = "test-client";
private static final String KEY_ID = "scopes-test-key-1";
private static HttpServer issuerServer;
private static String issuer;
private static RSAPrivateKey privateKey;
private static RSAPublicKey publicKey;
private static String httpApiId;
private static String integrationId;
private static String unscopedRouteId;
private static String scopedRouteId;
// ──────────────────────────── Fixture issuer ────────────────────────────
@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);
}
}
// ──────────────────────────── Setup ────────────────────────────
@Test
@Order(1)
void setup() throws Exception {
httpApiId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"http-v2-jwt-scopes-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 zipBase64 = Base64.getEncoder().encodeToString(zipEntries(Map.of("index.js", """
exports.handler = async (event) => ({
statusCode: 200,
body: JSON.stringify({ authorizer: (event.requestContext || {}).authorizer || null })
});
""")));
given()
.contentType(ContentType.JSON)
.body("""
{"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}
""".formatted(BACKEND_FN, zipBase64))
.when().post("/2015-03-31/functions")
.then().statusCode(201);
given().contentType(ContentType.JSON).body("{}")
.when().post("/2015-03-31/functions/" + BACKEND_FN + "/invocations")
.then().statusCode(200);
integrationId = given()
.contentType(ContentType.JSON)
.body("""
{"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST","payloadFormatVersion":"2.0"}
""".formatted(BACKEND_FN))
.when().post("/v2/apis/" + httpApiId + "/integrations")
.then().statusCode(201)
.extract().path("integrationId");
String authorizerId = given()
.contentType(ContentType.JSON)
.body("""
{
"authorizerType":"JWT",
"name":"jwt-scopes-auth",
"identitySource":["$request.header.Authorization"],
"jwtConfiguration":{"issuer":"%s","audience":["%s"]}
}
""".formatted(issuer, AUDIENCE))
.when().post("/v2/apis/" + httpApiId + "/authorizers")
.then().statusCode(201)
.extract().path("authorizerId");
unscopedRouteId = given()
.contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /unscoped","authorizationType":"JWT","authorizerId":"%s","target":"integrations/%s"}
""".formatted(authorizerId, integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(201)
.extract().path("routeId");
scopedRouteId = given()
.contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /scoped","authorizationType":"JWT","authorizerId":"%s","authorizationScopes":["read","admin/other"],"target":"integrations/%s"}
""".formatted(authorizerId, integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(201)
.extract().path("routeId");
}
// ──────────────────────────── Tests ────────────────────────────
@Test
@Order(10)
void unscopedRouteRendersScopesNullDespiteScopeClaim() throws Exception {
String body = given()
.header("Authorization", "Bearer " + signedToken(Map.of(
"iss", issuer, "aud", AUDIENCE, "exp", farFuture(),
"scope", "read write",
"cognito:groups", java.util.List.of("admin", "poweruser"))))
.when().get("/execute-api/" + httpApiId + "/test/unscoped")
.then().statusCode(200)
.extract().asString();
JsonNode jwt = MAPPER.readTree(body).path("authorizer").path("jwt");
assertTrue(jwt.get("scopes").isNull(),
"route without authorizationScopes must render scopes: null even for a scoped token");
assertEquals("read write", jwt.path("claims").get("scope").asText());
assertEquals("[admin poweruser]", jwt.path("claims").get("cognito:groups").asText());
}
@Test
@Order(11)
void scopedRouteSurfacesFullTokenScopeList() throws Exception {
String body = given()
.header("Authorization", "Bearer " + signedToken(Map.of(
"iss", issuer, "aud", AUDIENCE, "exp", farFuture(),
"scope", "read write")))
.when().get("/execute-api/" + httpApiId + "/test/scoped")
.then().statusCode(200)
.extract().asString();
JsonNode scopes = MAPPER.readTree(body).path("authorizer").path("jwt").get("scopes");
assertTrue(scopes.isArray());
assertEquals(2, scopes.size(),
"the token's full scope list is surfaced, not the intersection with the route's scopes");
assertEquals("read", scopes.get(0).asText());
assertEquals("write", scopes.get(1).asText());
}
@Test
@Order(12)
void scopedRouteRejectsTokenWithoutMatchingScope() throws Exception {
// No scope claim at all (the Cognito ID-token case)
given()
.header("Authorization", "Bearer " + signedToken(Map.of(
"iss", issuer, "aud", AUDIENCE, "exp", farFuture())))
.when().get("/execute-api/" + httpApiId + "/test/scoped")
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
// Scope claim present but matching none of the route's scopes
given()
.header("Authorization", "Bearer " + signedToken(Map.of(
"iss", issuer, "aud", AUDIENCE, "exp", farFuture(),
"scope", "something.else")))
.when().get("/execute-api/" + httpApiId + "/test/scoped")
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
}
// ──────────────────────────── Cleanup ────────────────────────────
@Test
@Order(999)
void cleanup() {
if (unscopedRouteId != null) given().when().delete("/v2/apis/" + httpApiId + "/routes/" + unscopedRouteId);
if (scopedRouteId != null) given().when().delete("/v2/apis/" + httpApiId + "/routes/" + scopedRouteId);
if (httpApiId != null) given().when().delete("/v2/apis/" + httpApiId);
int statusCode = given()
.when().delete("/2015-03-31/functions/" + BACKEND_FN)
.then().extract().statusCode();
assertTrue(statusCode == 204 || statusCode == 404);
}
// ──────────────────────────── Helpers ────────────────────────────
private static String signedToken(Map<String, Object> claims) throws Exception {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
String header = enc.encodeToString(
("{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"" + KEY_ID + "\"}").getBytes(StandardCharsets.UTF_8));
String payload = enc.encodeToString(MAPPER.writeValueAsBytes(claims));
String signingInput = header + "." + payload;
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
return signingInput + "." + enc.encodeToString(signature.sign());
}
private static long farFuture() {
return (System.currentTimeMillis() / 1000) + 3600;
}
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);
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, String> entry : entries.entrySet()) {
zos.putNextEntry(new ZipEntry(entry.getKey()));
zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
}
return baos.toByteArray();
}
}
@@ -70,6 +70,61 @@ class RouteAuthorizerIdResponseTest {
.body("items.authorizerId", hasItem(authorizerId));
}
@Test
void authorizationScopesPersistedAndReturned() {
String apiId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"authz-route-scopes","protocolType":"HTTP"}
""")
.when().post("/v2/apis")
.then().statusCode(201)
.extract().path("apiId");
String authorizerId = given()
.contentType(ContentType.JSON)
.body("""
{
"authorizerType":"JWT",
"name":"jwt-authz-scopes",
"identitySource":["$request.header.Authorization"],
"jwtConfiguration":{"issuer":"https://example.com","audience":["api"]}
}
""")
.when().post("/v2/apis/" + apiId + "/authorizers")
.then().statusCode(201)
.extract().path("authorizerId");
String routeId = given()
.contentType(ContentType.JSON)
.body("""
{
"routeKey":"GET /scoped",
"authorizationType":"JWT",
"authorizerId":"%s",
"authorizationScopes":["orders/read","orders/write"]
}
""".formatted(authorizerId))
.when().post("/v2/apis/" + apiId + "/routes")
.then().statusCode(201)
.body("authorizationScopes", equalTo(java.util.List.of("orders/read", "orders/write")))
.extract().path("routeId");
given()
.when().get("/v2/apis/" + apiId + "/routes/" + routeId)
.then().statusCode(200)
.body("authorizationScopes", equalTo(java.util.List.of("orders/read", "orders/write")));
given()
.contentType(ContentType.JSON)
.body("""
{"authorizationScopes":["orders/admin"]}
""")
.when().patch("/v2/apis/" + apiId + "/routes/" + routeId)
.then().statusCode(200)
.body("authorizationScopes", equalTo(java.util.List.of("orders/admin")));
}
@Test
void authorizerIdReturnedAfterUpdate() {
String apiId = given()