fix(apigateway): include apiKeyId in the REQUEST authorizer identity context (#3143)

Real API Gateway sets both identity.apiKey and identity.apiKeyId so a
REQUEST authorizer can call GetApiKey by id. Floci only set apiKey,
so any authorizer reading apiKeyId always saw undefined and denied
every request, even with a valid usage-plan-bound key.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-06 15:29:36 -05:00
1 parent 5cf10ece18
commit dced3e7bec
3 files changed
+114 -23

No files matched your search

@@ -358,7 +358,7 @@ public class ApiGatewayExecuteController {
}
// 1. Authorizer
String resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers);
ResolvedApiKey resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers);
// AWS_IAM is verified before the CUSTOM authorizer path because it gates the request on the
// caller's signature rather than on a Lambda's verdict, and a method carries one
@@ -415,7 +415,7 @@ public class ApiGatewayExecuteController {
Stage stage,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body,
AuthorizerResult authorizerResult, String resolvedApiKey,
AuthorizerResult authorizerResult, ResolvedApiKey resolvedApiKey,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
String functionName = functionNameFromUri(integration.getUri());
if (functionName == null) {
@@ -448,7 +448,7 @@ public class ApiGatewayExecuteController {
String resourceId,
Stage stage,
MethodConfig method,
HttpHeaders headers, UriInfo uriInfo, String resolvedApiKey) {
HttpHeaders headers, UriInfo uriInfo, ResolvedApiKey resolvedApiKey) {
if ("CUSTOM".equals(method.getAuthorizationType())) {
String authorizerId = method.getAuthorizerId();
if (authorizerId == null) {
@@ -589,7 +589,7 @@ public class ApiGatewayExecuteController {
HttpHeaders headers, String region, String apiId, String stageName,
String httpMethod, String requestPath,
String resourcePath, String resourceId, Stage stage, UriInfo uriInfo,
String resolvedApiKey) {
ResolvedApiKey resolvedApiKey) {
// Recover the trailing slash the JAX-RS {proxy} binding strips, so the authorizer sees
// the same raw path the Lambda later receives from buildProxyEvent (AWS parity). Path
// matching and path-parameter extraction keep using the normalized requestPath.
@@ -639,15 +639,17 @@ public class ApiGatewayExecuteController {
ctx.put("requestId", UUID.randomUUID().toString());
ctx.put("requestTimeEpoch", System.currentTimeMillis());
// identity.apiKey: resolve from usage plans linked to this (apiId, stage)
// identity.apiKey / identity.apiKeyId: resolve from usage plans linked to this (apiId, stage)
ObjectNode identity = ctx.putObject("identity");
identity.put("sourceIp", "127.0.0.1");
String userAgent = headers.getHeaderString("User-Agent");
identity.put("userAgent", userAgent != null ? userAgent : "");
if (resolvedApiKey != null) {
identity.put("apiKey", resolvedApiKey);
identity.put("apiKey", resolvedApiKey.value());
identity.put("apiKeyId", resolvedApiKey.id());
} else {
identity.putNull("apiKey");
identity.putNull("apiKeyId");
}
identity.putNull("clientCert"); // null when mTLS is not configured (Floci does not support mTLS)
}
@@ -655,12 +657,13 @@ public class ApiGatewayExecuteController {
}
/**
* Resolves the API key value for a request by matching the {@code x-api-key} header
* Resolves the API key id and value for a request by matching the {@code x-api-key} header
* against usage plan keys linked to this (apiId, stageName) pair.
*
* <p>Returns the key value string if a matching enabled key is found, {@code null} otherwise.
* <p>Returns {@code null} when the header is missing or does not match any enabled key linked
* to this (apiId, stage) through a usage plan.
*/
private String resolveApiKeyForRequest(String region, String apiId, String stageName, HttpHeaders headers) {
private ResolvedApiKey resolveApiKeyForRequest(String region, String apiId, String stageName, HttpHeaders headers) {
String keyHeader = headers.getHeaderString("x-api-key");
if (keyHeader == null || keyHeader.isBlank()) {
return null;
@@ -679,13 +682,20 @@ public class ApiGatewayExecuteController {
if (apiGatewayService.findApiKey(region, planKey.getId())
.filter(ApiKey::isEnabled)
.isPresent()) {
return planKey.getValue();
return new ResolvedApiKey(planKey.getId(), planKey.getValue());
}
}
}
return null;
}
/**
* The id and value of an API key matched to a request via a usage plan. A REQUEST authorizer
* resolves {@code GetApiKey} by id (event.requestContext.identity.apiKeyId), while the key
* value is carried separately under identity.apiKey.
*/
private record ResolvedApiKey(String id, String value) {}
private String buildMethodArn(String region, String apiId, String stageName, String httpMethod, String requestPath) {
String normalizedPath = requestPath == null ? "" : requestPath.replaceFirst("^/", "");
String arnRegion = region == null ? regionResolver.getDefaultRegion() : region;
@@ -710,7 +720,7 @@ public class ApiGatewayExecuteController {
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId,
String principalId, Map<String, Object> authorizerContext,
String resolvedApiKey,
ResolvedApiKey resolvedApiKey,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
// The JAX-RS {proxy} binding strips a trailing slash, but a trailing slash is
// significant in the delivered path (routers treat /x and /x/ as distinct routes).
@@ -793,11 +803,13 @@ public class ApiGatewayExecuteController {
identity.put("userAgent", userAgent != null ? userAgent : "");
putOrNull(identity, "userArn", iamIdentity == null ? null : iamIdentity.userArn());
identity.putNull("clientCert"); // null when mTLS is not configured (Floci does not support mTLS)
// apiKey: use pre-resolved value from usage plan keys linked to this (apiId, stage)
// apiKey / apiKeyId: use the pre-resolved id and value from usage plan keys linked to this (apiId, stage)
if (resolvedApiKey != null) {
identity.put("apiKey", resolvedApiKey);
identity.put("apiKey", resolvedApiKey.value());
identity.put("apiKeyId", resolvedApiKey.id());
} else {
identity.putNull("apiKey");
identity.putNull("apiKeyId");
}
// authorizer context (set by CUSTOM authorizer)
@@ -58,6 +58,9 @@ class ApiGatewayApiKeyRevocationIntegrationTest {
body: JSON.stringify({
apiKey: event.requestContext && event.requestContext.identity
? event.requestContext.identity.apiKey
: null,
apiKeyId: event.requestContext && event.requestContext.identity
? event.requestContext.identity.apiKeyId
: null
})
});
@@ -168,8 +171,11 @@ class ApiGatewayApiKeyRevocationIntegrationTest {
@Test @Order(4)
void enabledKeyIsResolvedOnTheDataPlane() throws Exception {
assertEquals(keyValue, invokeAndReadApiKey(keyValue),
IdentityApiKey identity = invokeAndReadIdentity(keyValue);
assertEquals(keyValue, identity.apiKey(),
"an enabled key attached to a plan covering the stage must populate identity.apiKey");
assertEquals(keyId, identity.apiKeyId(),
"an enabled key attached to a plan covering the stage must populate identity.apiKeyId with the key's id");
}
@Test @Order(5)
@@ -181,8 +187,11 @@ class ApiGatewayApiKeyRevocationIntegrationTest {
.then().statusCode(200)
.body("enabled", org.hamcrest.Matchers.is(false));
assertNull(invokeAndReadApiKey(keyValue),
IdentityApiKey identity = invokeAndReadIdentity(keyValue);
assertNull(identity.apiKey(),
"a key disabled through UpdateApiKey must no longer populate identity.apiKey");
assertNull(identity.apiKeyId(),
"a key disabled through UpdateApiKey must no longer populate identity.apiKeyId");
}
@Test @Order(6)
@@ -194,8 +203,11 @@ class ApiGatewayApiKeyRevocationIntegrationTest {
.then().statusCode(200)
.body("enabled", org.hamcrest.Matchers.is(true));
assertEquals(keyValue, invokeAndReadApiKey(keyValue),
IdentityApiKey identity = invokeAndReadIdentity(keyValue);
assertEquals(keyValue, identity.apiKey(),
"re-enabling the key must restore data-plane resolution");
assertEquals(keyId, identity.apiKeyId(),
"re-enabling the key must restore identity.apiKeyId resolution");
}
@Test @Order(7)
@@ -221,13 +233,18 @@ class ApiGatewayApiKeyRevocationIntegrationTest {
@Test @Order(8)
void deletedKeyIsNotResolvedOnTheDataPlane() throws Exception {
assertNull(invokeAndReadApiKey(keyValue),
IdentityApiKey identity = invokeAndReadIdentity(keyValue);
assertNull(identity.apiKey(),
"a deleted key must no longer populate identity.apiKey");
assertNull(identity.apiKeyId(),
"a deleted key must no longer populate identity.apiKeyId");
}
// ──────────────────────────── Helpers ────────────────────────────
private static String invokeAndReadApiKey(String apiKeyHeader) throws Exception {
private record IdentityApiKey(String apiKey, String apiKeyId) {}
private static IdentityApiKey invokeAndReadIdentity(String apiKeyHeader) throws Exception {
String response = given()
.header("x-api-key", apiKeyHeader)
.when().get("/execute-api/" + apiId + "/prod/echo")
@@ -235,8 +252,12 @@ class ApiGatewayApiKeyRevocationIntegrationTest {
.extract().asString();
JsonNode body = OBJECT_MAPPER.readTree(response);
JsonNode apiKey = body.path("apiKey");
return apiKey.isNull() || apiKey.isMissingNode() ? null : apiKey.asText();
return new IdentityApiKey(textOrNull(body, "apiKey"), textOrNull(body, "apiKeyId"));
}
private static String textOrNull(JsonNode body, String field) {
JsonNode value = body.path(field);
return value.isNull() || value.isMissingNode() ? null : value.asText();
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
@@ -269,6 +269,8 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
"requestContext.identity.userAgent must be present");
assertTrue(ctx.path("identity").path("apiKey").isNull(),
"requestContext.identity.apiKey must be null when no matching usage plan key exists");
assertTrue(ctx.path("identity").path("apiKeyId").isNull(),
"requestContext.identity.apiKeyId must be null when no matching usage plan key exists");
assertTrue(ctx.path("identity").path("clientCert").isNull(),
"requestContext.identity.clientCert must be null (mTLS not supported)");
assertEquals("/items/{id}", ctx.path("resourcePath").asText(null));
@@ -750,6 +752,8 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
// ──────────────────────────── API Key Resolution ────────────────────────────
private static String apiKeyApiId;
private static String apiKeyKeyId;
private static String apiKeyDistinctKeyId;
@Test
@Order(60)
@@ -839,11 +843,27 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
.when().post("/apikeys")
.then().statusCode(201);
String keyId = given()
apiKeyKeyId = given()
.when().get("/apikeys")
.then().statusCode(200)
.extract().path("item.find { it.name == 'test-key' }.id");
// A second key with a distinct id (generateDistinctId=true), so its value cannot be
// mistaken for its id: this guards against an implementation that assumes id == value.
given().contentType(ContentType.JSON)
.body("""
{"name":"test-key-distinct","value":"my-distinct-api-key","enabled":true,"generateDistinctId":true}
""")
.when().post("/apikeys")
.then().statusCode(201);
apiKeyDistinctKeyId = given()
.when().get("/apikeys")
.then().statusCode(200)
.extract().path("item.find { it.name == 'test-key-distinct' }.id");
assertNotEquals("my-distinct-api-key", apiKeyDistinctKeyId,
"generateDistinctId must produce an id different from the key value");
String planId = given().contentType(ContentType.JSON)
.body("""
{"name":"test-plan","apiStages":[{"apiId":"%s","stage":"prod"}]}
@@ -855,7 +875,14 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
given().contentType(ContentType.JSON)
.body("""
{"keyId":"%s","keyType":"API_KEY"}
""".formatted(keyId))
""".formatted(apiKeyKeyId))
.when().post("/usageplans/" + planId + "/keys")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("""
{"keyId":"%s","keyType":"API_KEY"}
""".formatted(apiKeyDistinctKeyId))
.when().post("/usageplans/" + planId + "/keys")
.then().statusCode(201);
}
@@ -878,10 +905,37 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
assertEquals("my-secret-api-key",
event.path("requestContext").path("identity").path("apiKey").asText(null),
"identity.apiKey must equal the matched usage plan key value");
assertEquals(apiKeyKeyId,
event.path("requestContext").path("identity").path("apiKeyId").asText(null),
"identity.apiKeyId must equal the matched key's id, as GetApiKey expects");
}
@Test
@Order(62)
void apiKey_identityApiKeyIdDiffersFromValueWhenGenerateDistinctId() throws Exception {
String response = given()
.header("Authorization", "Bearer test")
.header("x-api-key", "my-distinct-api-key")
.when().get("/execute-api/" + apiKeyApiId + "/prod/secure")
.then().statusCode(200)
.extract().asString();
JsonNode payload = OBJECT_MAPPER.readTree(response);
String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null);
assertNotNull(receivedEventStr);
JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr);
JsonNode identity = event.path("requestContext").path("identity");
assertEquals("my-distinct-api-key", identity.path("apiKey").asText(null),
"identity.apiKey must equal the matched usage plan key value");
assertEquals(apiKeyDistinctKeyId, identity.path("apiKeyId").asText(null),
"identity.apiKeyId must equal the key's id even when it differs from its value");
assertNotEquals(identity.path("apiKey").asText(null), identity.path("apiKeyId").asText(null),
"apiKey and apiKeyId must not be conflated when generateDistinctId produced different values");
}
@Test
@Order(63)
void apiKey_identityApiKeyNullWhenNoHeaderPresent() throws Exception {
String response = given()
.header("Authorization", "Bearer test")
@@ -896,10 +950,12 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
assertTrue(event.path("requestContext").path("identity").path("apiKey").isNull(),
"identity.apiKey must be null when no x-api-key header is present");
assertTrue(event.path("requestContext").path("identity").path("apiKeyId").isNull(),
"identity.apiKeyId must be null when no x-api-key header is present");
}
@Test
@Order(63)
@Order(64)
void apiKey_identityApiKeyNullWhenHeaderDoesNotMatchAnyPlanKey() throws Exception {
String response = given()
.header("Authorization", "Bearer test")
@@ -915,6 +971,8 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
assertTrue(event.path("requestContext").path("identity").path("apiKey").isNull(),
"identity.apiKey must be null when x-api-key header does not match any plan key");
assertTrue(event.path("requestContext").path("identity").path("apiKeyId").isNull(),
"identity.apiKeyId must be null when x-api-key header does not match any plan key");
}
// ──────────────────────────── Cleanup ────────────────────────────