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:
Jay authored and GitHub committed 2026-08-17 22:33:26 -04:00
1 parent 2f0ef45978
commit 0444753eb8
10 files changed
+1047 -74

No files matched your search

@@ -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);
@@ -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) {
@@ -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
);
}
@@ -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");
}
}
@@ -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
);
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}