fix(apigateway): keep a REST API's apiKeySource and honor AUTHORIZER (#7382)

This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-11-03 08:39:29 -04:00
1 parent 80eee041d5
commit 93cc09cf7e
8 files changed
+311 -29

No files matched your search

@@ -2278,12 +2278,10 @@ public class ApiGatewayController {
service.findRootResourceId(region, api.getId()).ifPresent(id -> node.put("rootResourceId", id));
}
// Neither member is settable on a REST API here: createRestApi ignores both and
// updateRestApi patches only /name and /description, so the emulated value is always
// the AWS default. Report the defaults rather than omitting them, because a client
// that reads an absent member back as "" or null sees it as a difference from the
// configuration it just sent and never converges.
node.put("apiKeySource", "HEADER");
node.put("apiKeySource", api.getApiKeySource());
// Not settable on a REST API here, so the emulated value is always the AWS default.
// Report it rather than omitting it, because a client that reads an absent member back
// as null sees it as a difference from the configuration it just sent and never converges.
node.put("disableExecuteApiEndpoint", false);
// AWS returns the policy JSON-escaped inside the string ({\"Version\":...}), and the
@@ -186,7 +186,12 @@ public class ApiGatewayExecuteController {
static final Pattern ELB_LISTENER_ARN = Pattern.compile(
"^arn:" + AwsArnUtils.PARTITION_REGEX + ":elasticloadbalancing:([^:]+):[^:]*:listener/(?:app|net)/.+$");
private record AuthorizerResult(Response errorResponse, String principalId, Map<String, Object> context) {}
private record AuthorizerResult(Response errorResponse, String principalId, Map<String, Object> context,
String usageIdentifierKey) {
AuthorizerResult(Response errorResponse, String principalId, Map<String, Object> context) {
this(errorResponse, principalId, context, null);
}
}
/**
* What a gateway-generated error needs in order to render the REST API's gateway response for
@@ -472,8 +477,11 @@ public class ApiGatewayExecuteController {
}
scope = scope.withResource(matched);
// 1. Authorizer
ResolvedApiKey resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers);
// 1. Authorizer. With apiKeySource AUTHORIZER the x-api-key header is not read: the key is
// the usageIdentifierKey the Lambda authorizer returns, resolved once it has run.
boolean keyFromAuthorizer = apiGatewayService.getRestApi(region, apiId).readsApiKeyFromAuthorizer();
ResolvedApiKey resolvedApiKey = keyFromAuthorizer ? null
: resolveApiKey(region, apiId, stageName, headers.getHeaderString("x-api-key"));
// 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
@@ -491,9 +499,13 @@ public class ApiGatewayExecuteController {
scope = scope.withIdentity(resolvedApiKey, iamIdentity);
AuthorizerResult authorizerResult = invokeAuthorizer(scope, region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey);
if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse();
if (keyFromAuthorizer) {
resolvedApiKey = resolveApiKey(region, apiId, stageName, authorizerResult.usageIdentifierKey());
scope = scope.withIdentity(resolvedApiKey, iamIdentity);
}
// API Gateway checks the API key requirement after authorization but before request
// validation and throttling. resolvedApiKey is null when the header is missing or matches
// validation and throttling. resolvedApiKey is null when the key is missing or matches
// no enabled key linked to this (apiId, stage) through a usage plan.
if (method.isApiKeyRequired() && resolvedApiKey == null) {
return gatewayResponse(scope, GatewayResponseType.INVALID_API_KEY, 403, "Forbidden");
@@ -1116,7 +1128,8 @@ public class ApiGatewayExecuteController {
if (!restLambdaAuthorizer.permits(verified, methodArn, conditions)) {
return authorizerError(scope, GatewayResponseType.ACCESS_DENIED, 403);
}
return new AuthorizerResult(null, verified.principalId(), verified.context());
return new AuthorizerResult(null, verified.principalId(), verified.context(),
verified.usageIdentifierKey());
} catch (Exception exception) {
LOG.warnv("Authorizer failure: {0}", exception.getMessage());
return authorizerError(scope, GatewayResponseType.AUTHORIZER_FAILURE, 500);
@@ -1376,15 +1389,15 @@ public class ApiGatewayExecuteController {
}
/**
* 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.
* Resolves the API key id and value for a request by matching the key value it carries (the
* {@code x-api-key} header, or a Lambda authorizer's {@code usageIdentifierKey}) against usage
* plan keys linked to this (apiId, stageName) pair.
*
* <p>Returns {@code null} when the header is missing or does not match any enabled key linked
* <p>Returns {@code null} when the value is missing or does not match any enabled key linked
* to this (apiId, stage) through a usage plan.
*/
private ResolvedApiKey resolveApiKeyForRequest(String region, String apiId, String stageName, HttpHeaders headers) {
String keyHeader = headers.getHeaderString("x-api-key");
if (keyHeader == null || keyHeader.isBlank()) {
private ResolvedApiKey resolveApiKey(String region, String apiId, String stageName, String keyValue) {
if (keyValue == null || keyValue.isBlank()) {
return null;
}
// Find all usage plans that include this (apiId, stage) pair
@@ -1395,7 +1408,7 @@ public class ApiGatewayExecuteController {
// Check if any key in this plan matches the header value. The usage plan key holds a copy
// of the value, so the key itself must still exist and be enabled for the match to count.
for (UsagePlanKey planKey : apiGatewayService.getUsagePlanKeys(region, plan.getId())) {
if (!keyHeader.equals(planKey.getValue())) {
if (!keyValue.equals(planKey.getValue())) {
continue;
}
if (apiGatewayService.findApiKey(region, planKey.getId())
@@ -325,6 +325,9 @@ public class ApiGatewayService implements ResourceProvider {
if (request.get("policy") instanceof String policy && !policy.isEmpty()) {
api.setPolicy(policy);
}
if (request.get("apiKeySource") != null) {
api.setApiKeySource(apiKeySource(request.get("apiKeySource")));
}
EndpointConfiguration endpointConfiguration = new EndpointConfiguration();
if (request.get(EPC_KEY) instanceof Map<?, ?> epMap) {
@@ -376,6 +379,14 @@ public class ApiGatewayService implements ResourceProvider {
return api;
}
/** A valid {@code apiKeySource}: {@code HEADER} or {@code AUTHORIZER}, as AWS spells them. */
private static String apiKeySource(Object value) {
if (RestApi.API_KEY_SOURCE_HEADER.equals(value) || RestApi.API_KEY_SOURCE_AUTHORIZER.equals(value)) {
return (String) value;
}
throw new AwsException("BadRequestException", "API key source must be HEADER or AUTHORIZER.", 400);
}
/** The endpoint type {@code value} names, in any case. */
private static EndpointType endpointType(String value) {
try {
@@ -3165,17 +3176,31 @@ public class ApiGatewayService implements ResourceProvider {
RestApi api = getRestApi(region, apiId);
if (patchOperations != null) {
// Worked out before anything is set: the store hands back the live API, and a rejected
// endpoint change must leave it as it was.
// endpoint change or API key source must leave it as it was.
EndpointConfiguration endpointConfiguration = patchEndpointConfiguration(api, patchOperations, region);
for (Map<String, String> op : patchOperations) {
if (!"replace" .equals(op.get("op"))) continue;
if ("replace".equals(op.get("op")) && "/apiKeySource".equals(op.get("path"))) {
apiKeySource(op.get("value"));
}
}
for (Map<String, String> op : patchOperations) {
if (!"replace" .equals(op.get("op"))) {
continue;
}
String path = op.getOrDefault("path", "");
String value = op.get("value");
if ("/name" .equals(path)) api.setName(value);
else if ("/description" .equals(path)) api.setDescription(value);
// aws_api_gateway_rest_api_policy writes the policy this way, and clears it by
// replacing it with an empty string.
else if ("/policy" .equals(path)) api.setPolicy(value == null || value.isEmpty() ? null : value);
if ("/name" .equals(path)) {
api.setName(value);
} else if ("/description" .equals(path)) {
api.setDescription(value);
} else if ("/policy" .equals(path)) {
// aws_api_gateway_rest_api_policy writes the policy this way, and clears it by
// replacing it with an empty string.
api.setPolicy(value == null || value.isEmpty() ? null : value);
} else if ("/apiKeySource" .equals(path)) {
// aws_api_gateway_rest_api sends this for a changed api_key_source.
api.setApiKeySource(apiKeySource(value));
}
}
if (endpointConfiguration != null) {
api.setEndpointConfiguration(endpointConfiguration);
@@ -4161,6 +4186,10 @@ public class ApiGatewayService implements ResourceProvider {
if (policy != null) {
api.setPolicy(JSON.valueToTree(policy).toString());
}
Object keySource = topExtensions.get("x-amazon-apigateway-api-key-source");
if (keySource != null) {
api.setApiKeySource(apiKeySource(keySource));
}
apiStore.put(apiKey(region, apiId), api);
Map<String, Object> validators = (Map<String, Object>) topExtensions
.get("x-amazon-apigateway-request-validators");
@@ -47,10 +47,20 @@ public class RestLambdaAuthorizer {
}
}
record Result(String principalId, String policyDocument, Map<String, Object> context) {
/**
* What a Lambda authorizer returned. {@code usageIdentifierKey} is the API key a REST API whose
* {@code apiKeySource} is {@code AUTHORIZER} meters and checks the request with; null when the
* authorizer returned none.
*/
record Result(String principalId, String policyDocument, Map<String, Object> context,
String usageIdentifierKey) {
Result {
context = Map.copyOf(context);
}
Result(String principalId, String policyDocument, Map<String, Object> context) {
this(principalId, policyDocument, context, null);
}
}
private record Entry(Result result, Instant expiresAt) { }
@@ -63,7 +73,9 @@ public class RestLambdaAuthorizer {
}
JsonNode policy = output.path("policyDocument");
AuthorizerPolicyEvaluator.validate(policy);
return new Result(output.path("principalId").asText(), policy.toString(), parseContext(output.get("context")));
JsonNode usageIdentifierKey = output.path("usageIdentifierKey");
return new Result(output.path("principalId").asText(), policy.toString(), parseContext(output.get("context")),
usageIdentifierKey.isTextual() ? usageIdentifierKey.asText() : null);
}
private Map<String, Object> parseContext(JsonNode context) {
@@ -12,6 +12,9 @@ import java.util.Map;
@RegisterForReflection
public class RestApi {
public static final String API_KEY_SOURCE_HEADER = "HEADER";
public static final String API_KEY_SOURCE_AUTHORIZER = "AUTHORIZER";
private String id;
private String name;
private String description;
@@ -23,8 +26,26 @@ public class RestApi {
private List<String> binaryMediaTypes = new ArrayList<>();
/** Resource policy document, stored exactly as the caller sent it. */
private String policy;
/**
* Where a request's API key is read from: {@code HEADER} (the {@code x-api-key} header, AWS's
* default) or {@code AUTHORIZER} (the {@code usageIdentifierKey} a Lambda authorizer returns).
*/
private String apiKeySource = API_KEY_SOURCE_HEADER;
private List<String> warnings = new ArrayList<>();
public String getApiKeySource() {
return apiKeySource;
}
/** {@code null} keeps the default, {@code HEADER}. */
public void setApiKeySource(String apiKeySource) {
this.apiKeySource = apiKeySource != null ? apiKeySource : API_KEY_SOURCE_HEADER;
}
public boolean readsApiKeyFromAuthorizer() {
return API_KEY_SOURCE_AUTHORIZER.equals(apiKeySource);
}
public List<String> getWarnings() {
return warnings;
}