mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(apigateway): keep a REST API's apiKeySource and honor AUTHORIZER (#7382)
This commit is contained in:
1 parent
80eee041d5
commit
93cc09cf7e
8 files changed
+311
-29
No files matched your search
@@ -176,6 +176,19 @@ deleted, or not bound to the stage by a usage plan, with `403` `{"message":"Forb
|
||||
`x-amzn-ErrorType: ForbiddenException`, as AWS does. The header stays when the API customises its
|
||||
`INVALID_API_KEY` gateway response.
|
||||
|
||||
#### API key source
|
||||
|
||||
A REST API's `apiKeySource` is set with `CreateRestApi`, a `replace /apiKeySource` patch on
|
||||
`UpdateRestApi`, or an imported `x-amazon-apigateway-api-key-source`, and defaults to `HEADER`. Any
|
||||
other value is refused with `BadRequestException`. A stage export leaves the extension out, as AWS's
|
||||
does.
|
||||
|
||||
With `AUTHORIZER`, the `x-api-key` header is not read. The key is the `usageIdentifierKey` the
|
||||
method's Lambda authorizer returns, checked against usage plans as above, and reported as
|
||||
`requestContext.identity.apiKey` and `apiKeyId` to a Lambda proxy integration. The authorizer's own
|
||||
event carries no key, since none is known before it runs. A method that requires a key and is not
|
||||
behind a Lambda authorizer then always answers `403`.
|
||||
|
||||
### REST Lambda Authorizers
|
||||
|
||||
TOKEN and REQUEST authorizers must return a nonempty `principalId` and an IAM policy. Floci
|
||||
|
||||
+4
-6
@@ -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
|
||||
|
||||
+25
-12
@@ -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())
|
||||
|
||||
+36
-7
@@ -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");
|
||||
|
||||
+14
-2
@@ -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;
|
||||
}
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A REST API's {@code apiKeySource}: kept on create, on a {@code /apiKeySource} patch and from an
|
||||
* imported {@code x-amazon-apigateway-api-key-source}, and, set to {@code AUTHORIZER}, taking a
|
||||
* request's API key from the Lambda authorizer's {@code usageIdentifierKey} instead of the
|
||||
* {@code x-api-key} header.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html">RestApi</a>
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayApiKeySourceIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String AUTHORIZER = "api-key-source-authorizer";
|
||||
private static final String BACKEND = "api-key-source-backend";
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private String apiId;
|
||||
private String keyId;
|
||||
private String planId;
|
||||
|
||||
@BeforeEach
|
||||
void reset() {
|
||||
apiId = null;
|
||||
keyId = null;
|
||||
planId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes whatever the test got as far as creating, even when an assertion failed first: an API
|
||||
* key and a usage plan outlive the REST API they were set up for. Deleting the key also
|
||||
* detaches it from the plan.
|
||||
*/
|
||||
@AfterEach
|
||||
void deleteFixtures() {
|
||||
if (keyId != null) {
|
||||
given().delete("/apikeys/" + keyId).then().statusCode(202);
|
||||
}
|
||||
if (planId != null) {
|
||||
given().delete("/usageplans/" + planId).then().statusCode(202);
|
||||
}
|
||||
if (apiId != null) {
|
||||
given().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSourceIsKeptOnCreateAndPatchAndDefaultsToHeader() {
|
||||
apiId = given().contentType(ContentType.JSON).body(Map.of("name", "key-source", "apiKeySource", "AUTHORIZER"))
|
||||
.post("/restapis").then().statusCode(201)
|
||||
.body("apiKeySource", equalTo("AUTHORIZER"))
|
||||
.extract().path("id");
|
||||
given().get("/restapis/" + apiId).then().statusCode(200).body("apiKeySource", equalTo("AUTHORIZER"));
|
||||
|
||||
patch("HEADER").statusCode(200).body("apiKeySource", equalTo("HEADER"));
|
||||
given().get("/restapis/" + apiId).then().body("apiKeySource", equalTo("HEADER"));
|
||||
patch("AUTHORIZER").statusCode(200).body("apiKeySource", equalTo("AUTHORIZER"));
|
||||
|
||||
patch("QUERY").statusCode(400).body("message", equalTo("API key source must be HEADER or AUTHORIZER."));
|
||||
given().get("/restapis/" + apiId).then().body("apiKeySource", equalTo("AUTHORIZER"));
|
||||
// A refused source leaves the operations before it in the same request unapplied too.
|
||||
given().contentType(ContentType.JSON)
|
||||
.body(Map.of("patchOperations", List.of(
|
||||
Map.of("op", "replace", "path", "/name", "value", "renamed"),
|
||||
Map.of("op", "replace", "path", "/apiKeySource", "value", "QUERY"))))
|
||||
.patch("/restapis/" + apiId).then().statusCode(400);
|
||||
given().get("/restapis/" + apiId).then()
|
||||
.body("name", equalTo("key-source"), "apiKeySource", equalTo("AUTHORIZER"));
|
||||
|
||||
given().contentType(ContentType.JSON).body(Map.of("name", "key-source-bad", "apiKeySource", "header"))
|
||||
.post("/restapis").then().statusCode(400);
|
||||
|
||||
String defaulted = given().contentType(ContentType.JSON).body(Map.of("name", "key-source-default"))
|
||||
.post("/restapis").then().statusCode(201)
|
||||
.body("apiKeySource", equalTo("HEADER"))
|
||||
.extract().path("id");
|
||||
given().delete("/restapis/" + defaulted).then().statusCode(202);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportedDefinitionSetsTheSource() {
|
||||
String definition = """
|
||||
{
|
||||
"openapi": "3.0.1",
|
||||
"info": {"title": "imported-key-source", "version": "1"},
|
||||
"x-amazon-apigateway-api-key-source": "AUTHORIZER",
|
||||
"paths": {}
|
||||
}
|
||||
""";
|
||||
apiId = given().contentType(ContentType.JSON).body(definition)
|
||||
.post("/restapis?mode=import").then().statusCode(201)
|
||||
.body("apiKeySource", equalTo("AUTHORIZER"))
|
||||
.extract().path("id");
|
||||
given().get("/restapis/" + apiId).then().body("apiKeySource", equalTo("AUTHORIZER"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withAuthorizerAsSourceTheKeyComesFromTheAuthorizerNotTheHeader() throws Exception {
|
||||
apiId = given().contentType(ContentType.JSON).body(Map.of("name", "key-from-authorizer", "apiKeySource", "AUTHORIZER"))
|
||||
.post("/restapis").then().statusCode(201).extract().path("id");
|
||||
String rootId = given().get("/restapis/" + apiId + "/resources").then().extract().path("item[0].id");
|
||||
String resourceId = given().contentType(ContentType.JSON).body(Map.of("pathPart", "orders"))
|
||||
.post("/restapis/" + apiId + "/resources/" + rootId).then().statusCode(201).extract().path("id");
|
||||
String authorizerId = given().contentType(ContentType.JSON).body(Map.of("name", "tenant", "type", "TOKEN",
|
||||
"authorizerUri", invocationUri(AUTHORIZER), "authorizerResultTtlInSeconds", 0,
|
||||
"identitySource", "method.request.header.Authorization"))
|
||||
.post("/restapis/" + apiId + "/authorizers").then().statusCode(201).extract().path("id");
|
||||
String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
|
||||
given().contentType(ContentType.JSON)
|
||||
.body(Map.of("authorizationType", "CUSTOM", "authorizerId", authorizerId, "apiKeyRequired", true))
|
||||
.put(method).then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body(Map.of("type", "AWS_PROXY", "httpMethod", "POST", "uri", invocationUri(BACKEND)))
|
||||
.put(method + "/integration").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON).body(Map.of("stageName", "prod"))
|
||||
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
|
||||
|
||||
keyId = given().contentType(ContentType.JSON).body(Map.of("name", "tenant-key", "enabled", true))
|
||||
.post("/apikeys").then().statusCode(201).extract().path("id");
|
||||
String keyValue = given().get("/apikeys/" + keyId + "?includeValue=true").then().extract().path("value");
|
||||
planId = given().contentType(ContentType.JSON)
|
||||
.body(Map.of("name", "tenant-plan", "apiStages", List.of(Map.of("apiId", apiId, "stage", "prod"))))
|
||||
.post("/usageplans").then().statusCode(201).extract().path("id");
|
||||
given().contentType(ContentType.JSON).body(Map.of("keyId", keyId, "keyType", "API_KEY"))
|
||||
.post("/usageplans/" + planId + "/keys").then().statusCode(201);
|
||||
|
||||
// The authorizer returns the bearer token as the key to meter the request with.
|
||||
when(lambdaService.invokeTarget(eq(REGION), eq(functionArn(AUTHORIZER)), any(byte[].class),
|
||||
eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
|
||||
String token = mapper.readTree((byte[]) invocation.getArgument(2)).path("authorizationToken").asText();
|
||||
Map<String, Object> output = new HashMap<>();
|
||||
output.put("principalId", "tenant");
|
||||
output.put("policyDocument", Map.of("Version", "2012-10-17", "Statement", List.of(
|
||||
Map.of("Effect", "Allow", "Action", "execute-api:Invoke", "Resource", "*"))));
|
||||
if (!"none".equals(token)) {
|
||||
output.put("usageIdentifierKey", token);
|
||||
}
|
||||
return new InvokeResult(200, null, mapper.writeValueAsBytes(output), null, "authorizer-request");
|
||||
});
|
||||
when(lambdaService.invokeTarget(eq(REGION), eq(functionArn(BACKEND)), any(byte[].class),
|
||||
eq(InvocationType.RequestResponse))).thenAnswer(invocation -> {
|
||||
String apiKeyId = mapper.readTree((byte[]) invocation.getArgument(2))
|
||||
.path("requestContext").path("identity").path("apiKeyId").asText();
|
||||
return new InvokeResult(200, null, mapper.writeValueAsBytes(Map.of("statusCode", 200,
|
||||
"body", mapper.writeValueAsString(Map.of("apiKeyId", apiKeyId)))), null, "backend-request");
|
||||
});
|
||||
|
||||
String orders = "/execute-api/" + apiId + "/prod/orders";
|
||||
given().header("Authorization", keyValue).get(orders).then().statusCode(200).body("apiKeyId", equalTo(keyId));
|
||||
// The header is not read: a valid key in x-api-key does not stand in for the authorizer's.
|
||||
given().header("Authorization", "none").header("x-api-key", keyValue).get(orders).then().statusCode(403)
|
||||
.header("x-amzn-ErrorType", equalTo("ForbiddenException"));
|
||||
given().header("Authorization", "not-a-key").get(orders).then().statusCode(403);
|
||||
}
|
||||
|
||||
private ValidatableResponse patch(String source) {
|
||||
return given().contentType(ContentType.JSON)
|
||||
.body(Map.of("patchOperations", List.of(Map.of("op", "replace", "path", "/apiKeySource", "value", source))))
|
||||
.patch("/restapis/" + apiId).then();
|
||||
}
|
||||
|
||||
private static String functionArn(String function) {
|
||||
return "arn:aws:lambda:" + REGION + ":000000000000:function:" + function;
|
||||
}
|
||||
|
||||
private static String invocationUri(String function) {
|
||||
return "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + functionArn(function)
|
||||
+ "/invocations";
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -11,8 +11,8 @@ import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
/**
|
||||
* RestApi response members that clients read but that a caller never supplies:
|
||||
* rootResourceId, apiKeySource and disableExecuteApiEndpoint.
|
||||
* RestApi response members that clients read even when a caller does not supply them:
|
||||
* rootResourceId, and the defaults of apiKeySource and disableExecuteApiEndpoint.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/apigateway/latest/api/API_GetRestApi.html">GetRestApi</a>
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user