mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
Add the PutGatewayResponse / GetGatewayResponse / GetGatewayResponses /
UpdateGatewayResponse / DeleteGatewayResponse family, keyed per REST API by
responseType across the 21 AWS types. Uncustomised types are reported with
defaultResponse=true, their AWS default statusCode and the default
{"message":$context.error.messageString} template; UpdateGatewayResponse
patches /statusCode, /responseParameters/<name> and
/responseTemplates/<content-type>, and DeleteGatewayResponse restores the
default.
ImportRestApi and PutRestApi read the x-amazon-apigateway-gateway-responses
extension, and AWS::ApiGateway::GatewayResponse is provisioned by a new
CloudFormation provisioner whose Ref / Fn::GetAtt Id is
<restApiId>-<responseType>.
On the execute plane every gateway-generated answer (unmatched path or
method, AWS_IAM and Lambda authorizer rejections, missing API key, request
validation, unsupported media type, integration configuration errors and
Lambda proxy failures) resolves the customisation for its type, then
DEFAULT_4XX / DEFAULT_5XX, and applies the configured statusCode, the
gatewayresponse.header.* parameters (static, method.request.*, context.*,
stageVariables.*) and the response templates, with $context.error.* exposed
to VTL. An expired SigV4 signature selects EXPIRED_TOKEN and a malformed or
mismatching one INVALID_SIGNATURE, as AWS keeps those two contracts apart.
This is what puts Access-Control-Allow-Origin on a browser-visible
401/403/400 so the frontend can read the real status instead of a CORS
failure. Without a customisation every answer is unchanged.
Closes #3326
This commit is contained in:
1 parent
6f05442218
commit
2ee3aa67c0
16 files changed
+2060
-100
No files matched your search
+548
@@ -0,0 +1,548 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
/**
|
||||
* Gateway responses of a REST API: the {@code PutGatewayResponse} family on the management plane,
|
||||
* the {@code x-amazon-apigateway-gateway-responses} OpenAPI extension, and their effect on the
|
||||
* execute plane whenever the gateway itself answers (an unmatched path, a rejected validation),
|
||||
* which is what puts CORS headers on a browser-visible 4XX.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayGatewayResponseIntegrationTest {
|
||||
|
||||
private static final String DEFAULT_TEMPLATE = "{\"message\":$context.error.messageString}";
|
||||
|
||||
private String apiId;
|
||||
|
||||
@BeforeEach
|
||||
void createRestApi() {
|
||||
apiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"gateway-responses-test\"}")
|
||||
.when().post("/restapis")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteRestApi() {
|
||||
if (apiId != null) {
|
||||
given().when().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── management plane ────────────────────────────
|
||||
|
||||
@Test
|
||||
void everyTypeIsListedAsItsDefaultUntilCustomised() {
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses")
|
||||
.then().statusCode(200)
|
||||
.body("item", hasSize(21))
|
||||
.body("item.responseType", containsInAnyOrder(
|
||||
"ACCESS_DENIED", "API_CONFIGURATION_ERROR", "AUTHORIZER_CONFIGURATION_ERROR",
|
||||
"AUTHORIZER_FAILURE", "BAD_REQUEST_PARAMETERS", "BAD_REQUEST_BODY", "DEFAULT_4XX",
|
||||
"DEFAULT_5XX", "EXPIRED_TOKEN", "INTEGRATION_FAILURE", "INTEGRATION_TIMEOUT",
|
||||
"INVALID_API_KEY", "INVALID_SIGNATURE", "MISSING_AUTHENTICATION_TOKEN", "QUOTA_EXCEEDED",
|
||||
"REQUEST_TOO_LARGE", "RESOURCE_NOT_FOUND", "THROTTLED", "UNAUTHORIZED",
|
||||
"UNSUPPORTED_MEDIA_TYPE", "WAF_FILTERED"))
|
||||
.body("item.findAll { it.defaultResponse == false }", hasSize(0));
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses/MISSING_AUTHENTICATION_TOKEN")
|
||||
.then().statusCode(200)
|
||||
.body("responseType", equalTo("MISSING_AUTHENTICATION_TOKEN"))
|
||||
.body("statusCode", equalTo("403"))
|
||||
.body("defaultResponse", equalTo(true))
|
||||
.body("responseParameters", equalTo(Map.of()))
|
||||
.body("responseTemplates.'application/json'", equalTo(DEFAULT_TEMPLATE));
|
||||
|
||||
// The two DEFAULT_ types have no status of their own.
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(200)
|
||||
.body("$", not(hasKey("statusCode")))
|
||||
.body("defaultResponse", equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putGetUpdateAndDeleteAGatewayResponse() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"responseParameters\":{"
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\","
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Headers\":\"'*'\"},"
|
||||
+ "\"responseTemplates\":{\"application/json\":\"{\\\"error\\\":$context.error.messageString}\"}}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(201)
|
||||
.body("responseType", equalTo("DEFAULT_4XX"))
|
||||
.body("defaultResponse", equalTo(false))
|
||||
.body("$", not(hasKey("statusCode")))
|
||||
.body("responseParameters.'gatewayresponse.header.Access-Control-Allow-Origin'", equalTo("'*'"))
|
||||
.body("responseTemplates.'application/json'", equalTo("{\"error\":$context.error.messageString}"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"statusCode\":\"404\"}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/MISSING_AUTHENTICATION_TOKEN")
|
||||
.then().statusCode(201)
|
||||
.body("statusCode", equalTo("404"))
|
||||
.body("responseTemplates", equalTo(Map.of()))
|
||||
.body("defaultResponse", equalTo(false));
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses")
|
||||
.then().statusCode(200)
|
||||
.body("item", hasSize(21))
|
||||
.body("item.findAll { it.defaultResponse == false }.responseType",
|
||||
containsInAnyOrder("DEFAULT_4XX", "MISSING_AUTHENTICATION_TOKEN"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":["
|
||||
+ "{\"op\":\"replace\",\"path\":\"/statusCode\",\"value\":\"400\"},"
|
||||
+ "{\"op\":\"add\",\"path\":\"/responseParameters/gatewayresponse.header.X-Trace\",\"value\":\"context.requestId\"},"
|
||||
+ "{\"op\":\"remove\",\"path\":\"/responseParameters/gatewayresponse.header.Access-Control-Allow-Headers\"},"
|
||||
+ "{\"op\":\"replace\",\"path\":\"/responseTemplates/application~1json\",\"value\":\"{}\"}"
|
||||
+ "]}")
|
||||
.when().patch("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(200)
|
||||
.body("statusCode", equalTo("400"))
|
||||
.body("responseParameters", equalTo(Map.of(
|
||||
"gatewayresponse.header.Access-Control-Allow-Origin", "'*'",
|
||||
"gatewayresponse.header.X-Trace", "context.requestId")))
|
||||
.body("responseTemplates", equalTo(Map.of("application/json", "{}")));
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(200)
|
||||
.body("statusCode", equalTo("400"))
|
||||
.body("responseParameters.'gatewayresponse.header.X-Trace'", equalTo("context.requestId"));
|
||||
|
||||
given()
|
||||
.when().delete("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(202);
|
||||
|
||||
// Deleting restores the default rather than removing the type.
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(200)
|
||||
.body("defaultResponse", equalTo(true))
|
||||
.body("responseParameters", equalTo(Map.of()));
|
||||
|
||||
given()
|
||||
.when().delete("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(404)
|
||||
.body("__type", equalTo("NotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchingAnUncustomisedTypeStartsFromItsDefault() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"add\","
|
||||
+ "\"path\":\"/responseParameters/gatewayresponse.header.Access-Control-Allow-Origin\","
|
||||
+ "\"value\":\"'*'\"}]}")
|
||||
.when().patch("/restapis/" + apiId + "/gatewayresponses/UNAUTHORIZED")
|
||||
.then().statusCode(200)
|
||||
.body("statusCode", equalTo("401"))
|
||||
.body("defaultResponse", equalTo(false))
|
||||
.body("responseParameters.'gatewayresponse.header.Access-Control-Allow-Origin'", equalTo("'*'"))
|
||||
.body("responseTemplates.'application/json'", equalTo(DEFAULT_TEMPLATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidInputIsRejected() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/NOT_A_TYPE")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/gatewayresponses/NOT_A_TYPE")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"statusCode\":\"abc\"}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"responseParameters\":{\"method.response.header.X\":\"'*'\"}}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"responseParameters\":{\"gatewayresponse.header.X\":\"integration.response.header.X\"}}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/responseType\",\"value\":\"X\"}]}")
|
||||
.when().patch("/restapis/" + apiId + "/gatewayresponses/DEFAULT_5XX")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
|
||||
given()
|
||||
.when().get("/restapis/does-not-exist/gatewayresponses")
|
||||
.then().statusCode(404)
|
||||
.body("__type", equalTo("NotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void openApiImportCreatesTheGatewayResponses() {
|
||||
String spec = """
|
||||
{
|
||||
"openapi": "3.0.1",
|
||||
"info": {"title": "gateway-responses-import", "version": "1"},
|
||||
"paths": {
|
||||
"/ping": {
|
||||
"get": {
|
||||
"responses": {"200": {"description": "ok"}},
|
||||
"x-amazon-apigateway-integration": {
|
||||
"type": "mock",
|
||||
"requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
|
||||
"responses": {"default": {"statusCode": "200"}}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"x-amazon-apigateway-gateway-responses": {
|
||||
"DEFAULT_4XX": {
|
||||
"responseParameters": {
|
||||
"gatewayresponse.header.Access-Control-Allow-Origin": "'*'"
|
||||
}
|
||||
},
|
||||
"UNAUTHORIZED": {
|
||||
"statusCode": 403,
|
||||
"responseTemplates": {"application/json": "{\\"nope\\": true}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String importedApiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.queryParam("mode", "import")
|
||||
.body(spec)
|
||||
.when().post("/restapis")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
try {
|
||||
given()
|
||||
.when().get("/restapis/" + importedApiId + "/gatewayresponses/DEFAULT_4XX")
|
||||
.then().statusCode(200)
|
||||
.body("defaultResponse", equalTo(false))
|
||||
.body("responseParameters.'gatewayresponse.header.Access-Control-Allow-Origin'", equalTo("'*'"));
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + importedApiId + "/gatewayresponses/UNAUTHORIZED")
|
||||
.then().statusCode(200)
|
||||
.body("defaultResponse", equalTo(false))
|
||||
.body("statusCode", equalTo("403"))
|
||||
.body("responseTemplates.'application/json'", equalTo("{\"nope\": true}"));
|
||||
|
||||
// PutRestApi rebuilds the API from the new spec, dropping customisations it no longer declares.
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.queryParam("mode", "overwrite")
|
||||
.body(spec.replace("\"UNAUTHORIZED\"", "\"ACCESS_DENIED\""))
|
||||
.when().put("/restapis/" + importedApiId)
|
||||
.then().statusCode(200);
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + importedApiId + "/gatewayresponses/UNAUTHORIZED")
|
||||
.then().statusCode(200)
|
||||
.body("defaultResponse", equalTo(true));
|
||||
given()
|
||||
.when().get("/restapis/" + importedApiId + "/gatewayresponses/ACCESS_DENIED")
|
||||
.then().statusCode(200)
|
||||
.body("defaultResponse", equalTo(false))
|
||||
.body("statusCode", equalTo("403"));
|
||||
} finally {
|
||||
given().when().delete("/restapis/" + importedApiId);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── execute plane ────────────────────────────
|
||||
|
||||
@Test
|
||||
void anUncustomisedApiAnswersExactlyAsBefore() {
|
||||
deployMockApi();
|
||||
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/missing")
|
||||
.then().statusCode(403)
|
||||
.contentType(ContentType.JSON)
|
||||
.header("x-amzn-ErrorType", equalTo("MissingAuthenticationTokenException"))
|
||||
.body("message", equalTo("Missing Authentication Token"))
|
||||
.header("Access-Control-Allow-Origin", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void default4xxPutsCorsHeadersOnAnUnmatchedRoute() {
|
||||
deployMockApi();
|
||||
putGatewayResponse("DEFAULT_4XX", "{\"responseParameters\":{"
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\","
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Headers\":\"'Content-Type,Authorization'\"}}");
|
||||
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/missing")
|
||||
.then().statusCode(403)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.header("Access-Control-Allow-Headers", equalTo("Content-Type,Authorization"))
|
||||
.header("x-amzn-ErrorType", equalTo("MissingAuthenticationTokenException"))
|
||||
.body("message", equalTo("Missing Authentication Token"));
|
||||
|
||||
// A path whose resource declares no usable method is the same gateway-generated answer.
|
||||
given()
|
||||
.when().delete("/execute-api/" + apiId + "/api/ping")
|
||||
.then().statusCode(403)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.body("message", equalTo("Missing Authentication Token"));
|
||||
|
||||
// The integration's own answer is untouched.
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/ping")
|
||||
.then().statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSpecificTypeWinsOverDefault4xxAndCanOverrideTheStatus() {
|
||||
deployMockApi();
|
||||
putGatewayResponse("DEFAULT_4XX", "{\"responseParameters\":{"
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\"}}");
|
||||
putGatewayResponse("MISSING_AUTHENTICATION_TOKEN", "{\"statusCode\":\"404\","
|
||||
+ "\"responseParameters\":{\"gatewayresponse.header.X-Origin\":\"method.request.header.Origin\","
|
||||
+ "\"gatewayresponse.header.X-Stage\":\"context.stage\","
|
||||
+ "\"gatewayresponse.header.X-Type\":\"context.error.responseType\","
|
||||
+ "\"gatewayresponse.header.X-Region\":\"stageVariables.region\","
|
||||
+ "\"gatewayresponse.header.X-Query\":\"method.request.querystring.q\"},"
|
||||
+ "\"responseTemplates\":{\"application/json\":"
|
||||
+ "\"{\\\"error\\\":$context.error.messageString,\\\"path\\\":\\\"$context.path\\\"}\"}}");
|
||||
|
||||
given()
|
||||
.header("Origin", "https://app.example")
|
||||
.queryParam("q", "1")
|
||||
.when().get("/restapis/" + apiId + "/api/_user_request_/missing")
|
||||
.then().statusCode(404)
|
||||
.header("X-Origin", equalTo("https://app.example"))
|
||||
.header("X-Stage", equalTo("api"))
|
||||
.header("X-Type", equalTo("MISSING_AUTHENTICATION_TOKEN"))
|
||||
.header("X-Region", equalTo("eu-west-1"))
|
||||
.header("X-Query", equalTo("1"))
|
||||
.header("Access-Control-Allow-Origin", nullValue())
|
||||
.body("error", equalTo("Missing Authentication Token"))
|
||||
.body("path", equalTo("/api/missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestValidationFailuresRenderBadRequestParameters() {
|
||||
deployMockApi();
|
||||
putGatewayResponse("BAD_REQUEST_PARAMETERS", "{\"responseTemplates\":{\"application/json\":"
|
||||
+ "\"{\\\"type\\\":\\\"$context.error.responseType\\\",\\\"message\\\":$context.error.messageString}\"},"
|
||||
+ "\"responseParameters\":{\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\"}}");
|
||||
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/validated")
|
||||
.then().statusCode(400)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.body("type", equalTo("BAD_REQUEST_PARAMETERS"))
|
||||
.body("message", equalTo("Missing required request parameter in QUERY_STRING: 'q'"));
|
||||
|
||||
given()
|
||||
.queryParam("q", "x")
|
||||
.when().get("/execute-api/" + apiId + "/api/validated")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingApiKeyRendersInvalidApiKey() {
|
||||
deployMockApi();
|
||||
putGatewayResponse("DEFAULT_4XX", "{\"responseParameters\":{"
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\"}}");
|
||||
putGatewayResponse("INVALID_API_KEY", "{\"statusCode\":\"401\",\"responseTemplates\":{\"application/json\":"
|
||||
+ "\"{\\\"type\\\":\\\"$context.error.responseType\\\",\\\"message\\\":$context.error.messageString}\"}}");
|
||||
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/keyed")
|
||||
.then().statusCode(401)
|
||||
.header("Access-Control-Allow-Origin", nullValue())
|
||||
.body("type", equalTo("INVALID_API_KEY"))
|
||||
.body("message", equalTo("Forbidden"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredAndInvalidSignaturesSelectTheirOwnTypes() throws Exception {
|
||||
deployMockApi();
|
||||
putGatewayResponse("INVALID_SIGNATURE", "{\"statusCode\":\"401\","
|
||||
+ "\"responseParameters\":{\"gatewayresponse.header.X-Type\":\"context.error.responseType\"},"
|
||||
+ "\"responseTemplates\":{\"application/json\":\"{\\\"reason\\\":\\\"invalid\\\"}\"}}");
|
||||
putGatewayResponse("EXPIRED_TOKEN", "{\"statusCode\":\"419\","
|
||||
+ "\"responseParameters\":{\"gatewayresponse.header.X-Type\":\"context.error.responseType\"},"
|
||||
+ "\"responseTemplates\":{\"application/json\":\"{\\\"reason\\\":\\\"expired\\\"}\"}}");
|
||||
String path = "/restapis/" + apiId + "/api/_user_request_/iam";
|
||||
|
||||
// A signature outside the accepted window is EXPIRED_TOKEN, not INVALID_SIGNATURE.
|
||||
given()
|
||||
.headers(signedHeaders(path, Instant.now().minus(2, ChronoUnit.HOURS)))
|
||||
.when().get(path)
|
||||
.then().statusCode(419)
|
||||
.header("x-amzn-ErrorType", equalTo("InvalidSignatureException"))
|
||||
.header("X-Type", equalTo("EXPIRED_TOKEN"))
|
||||
.body("reason", equalTo("expired"));
|
||||
|
||||
// A signature computed for another path is a mismatch: INVALID_SIGNATURE.
|
||||
given()
|
||||
.headers(signedHeaders("/restapis/" + apiId + "/api/_user_request_/ping", Instant.now()))
|
||||
.when().get(path)
|
||||
.then().statusCode(401)
|
||||
.header("X-Type", equalTo("INVALID_SIGNATURE"))
|
||||
.body("reason", equalTo("invalid"));
|
||||
|
||||
given()
|
||||
.headers(signedHeaders(path, Instant.now()))
|
||||
.when().get(path)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAcceptHeaderSelectsTheTemplate() {
|
||||
deployMockApi();
|
||||
putGatewayResponse("DEFAULT_4XX", "{\"responseTemplates\":{"
|
||||
+ "\"application/json\":\"{\\\"message\\\":$context.error.messageString}\","
|
||||
+ "\"text/plain\":\"$context.error.message\"}}");
|
||||
|
||||
given()
|
||||
.accept("text/plain")
|
||||
.when().get("/execute-api/" + apiId + "/api/missing")
|
||||
.then().statusCode(403)
|
||||
.contentType("text/plain")
|
||||
.body(equalTo("Missing Authentication Token"));
|
||||
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/missing")
|
||||
.then().statusCode(403)
|
||||
.contentType(ContentType.JSON)
|
||||
.body("message", equalTo("Missing Authentication Token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiConfigurationErrorsUseDefault5xx() {
|
||||
deployMockApi();
|
||||
putGatewayResponse("DEFAULT_5XX", "{\"responseParameters\":{"
|
||||
+ "\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\"}}");
|
||||
|
||||
// A method whose MOCK request template does not render is a configuration error.
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/broken")
|
||||
.then().statusCode(500)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.body("message", equalTo("Internal server error"));
|
||||
}
|
||||
|
||||
// ──────────────────────────── fixtures ────────────────────────────
|
||||
|
||||
private void putGatewayResponse(String responseType, String body) {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(body)
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/" + responseType)
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage {@code api} with five MOCK GETs: {@code /ping} answers 200, {@code /validated}
|
||||
* requires the {@code q} query parameter, {@code /broken} has a request template that does
|
||||
* not parse, {@code /keyed} requires an API key and {@code /iam} requires a SigV4 signature.
|
||||
*/
|
||||
private void deployMockApi() {
|
||||
String rootId = given()
|
||||
.when().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200)
|
||||
.extract().path("item[0].id");
|
||||
|
||||
String validatorId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"params\",\"validateRequestParameters\":true}")
|
||||
.when().post("/restapis/" + apiId + "/requestvalidators")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
|
||||
mockGet(rootId, "ping", "{\"authorizationType\":\"NONE\"}", "{\"statusCode\": 200}");
|
||||
mockGet(rootId, "validated", "{\"authorizationType\":\"NONE\",\"requestValidatorId\":\"" + validatorId
|
||||
+ "\",\"requestParameters\":{\"method.request.querystring.q\":true}}", "{\"statusCode\": 200}");
|
||||
mockGet(rootId, "broken", "{\"authorizationType\":\"NONE\"}", "#if(");
|
||||
mockGet(rootId, "keyed", "{\"authorizationType\":\"NONE\",\"apiKeyRequired\":true}", "{\"statusCode\": 200}");
|
||||
mockGet(rootId, "iam", "{\"authorizationType\":\"AWS_IAM\"}", "{\"statusCode\": 200}");
|
||||
|
||||
String deploymentId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"description\":\"v1\"}")
|
||||
.when().post("/restapis/" + apiId + "/deployments")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"stageName\":\"api\",\"deploymentId\":\"" + deploymentId
|
||||
+ "\",\"variables\":{\"region\":\"eu-west-1\"}}")
|
||||
.when().post("/restapis/" + apiId + "/stages")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private static Map<String, String> signedHeaders(String path, Instant signedAt) throws Exception {
|
||||
return ExecuteApiRequestSigner.signedHeaders("GET", path, Map.of(), "localhost:" + RestAssured.port,
|
||||
null, "test", "test", "us-east-1", signedAt);
|
||||
}
|
||||
|
||||
private void mockGet(String rootId, String pathPart, String methodBody, String requestTemplate) {
|
||||
String resourceId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"pathPart\":\"" + pathPart + "\"}")
|
||||
.when().post("/restapis/" + apiId + "/resources/" + rootId)
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
|
||||
given().contentType(ContentType.JSON).body(methodBody)
|
||||
.when().put(method).then().statusCode(201);
|
||||
given().contentType(ContentType.JSON).body("{\"responseParameters\":{}}")
|
||||
.when().put(method + "/responses/200").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\""
|
||||
+ requestTemplate.replace("\"", "\\\"") + "\"}}")
|
||||
.when().put(method + "/integration").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{}\"}}")
|
||||
.when().put(method + "/integration/responses/200").then().statusCode(201);
|
||||
}
|
||||
}
|
||||
+21
@@ -176,6 +176,27 @@ class VtlTemplateEngineTest {
|
||||
assertEquals("test-user|KEY-123|t-9|true|true", engine.evaluate(template, authorizerCtx).body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextErrorForGatewayResponses() {
|
||||
VtlTemplateEngine.VtlContext errorCtx = new VtlTemplateEngine.VtlContext(
|
||||
null, Map.of(), Map.of(), Map.of(), "prod", "GET", "/users",
|
||||
"req-123", "000000000000", Map.of(), null,
|
||||
Map.of("path", "/prod/users",
|
||||
"error", Map.of("message", "Missing Authentication Token",
|
||||
"messageString", "\"Missing Authentication Token\"",
|
||||
"responseType", "MISSING_AUTHENTICATION_TOKEN",
|
||||
"validationErrorString", "")));
|
||||
String template = "{\"message\":$context.error.messageString,"
|
||||
+ "\"raw\":\"$context.error.message\",\"type\":\"$context.error.responseType\","
|
||||
+ "\"path\":\"$context.path\",\"stage\":\"$context.stage\"}";
|
||||
|
||||
assertEquals("{\"message\":\"Missing Authentication Token\",\"raw\":\"Missing Authentication Token\","
|
||||
+ "\"type\":\"MISSING_AUTHENTICATION_TOKEN\",\"path\":\"/prod/users\",\"stage\":\"prod\"}",
|
||||
engine.evaluate(template, errorCtx).body());
|
||||
// Outside a gateway response $context.error is simply absent.
|
||||
assertEquals("$context.error", engine.evaluate("$context.error", ctx("{}")).body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariables() {
|
||||
VtlTemplateEngine.VtlContext svCtx = new VtlTemplateEngine.VtlContext(
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::ApiGateway::GatewayResponse} against a REST API created outside the
|
||||
* stack, the way SAM's {@code GatewayResponses} and CDK's {@code addGatewayResponse} put CORS
|
||||
* headers on gateway-generated 4XX answers. Asserts that {@code Ref} and {@code Fn::GetAtt Id}
|
||||
* resolve to {@code <restApiId>-<responseType>}, that the customisation takes effect on the
|
||||
* execute plane, that an update changes it in place, and that deleting the stack restores the
|
||||
* default without touching the API.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayGatewayResponseCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
|
||||
private static final String STACK = "apigw-gatewayresponse-cfn-it";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
"ApiId": {"Type": "String"},
|
||||
"Origin": {"Type": "String"},
|
||||
"StatusCode": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Cors4xx": {
|
||||
"Type": "AWS::ApiGateway::GatewayResponse",
|
||||
"Properties": {
|
||||
"RestApiId": {"Ref": "ApiId"},
|
||||
"ResponseType": "DEFAULT_4XX",
|
||||
"StatusCode": {"Ref": "StatusCode"},
|
||||
"ResponseParameters": {
|
||||
"gatewayresponse.header.Access-Control-Allow-Origin": {"Fn::Sub": "'${Origin}'"},
|
||||
"gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
|
||||
},
|
||||
"ResponseTemplates": {
|
||||
"application/json": "{\\"message\\":$context.error.messageString}"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"ResponseRef": {"Value": {"Ref": "Cors4xx"}},
|
||||
"ResponseId": {"Value": {"Fn::GetAtt": ["Cors4xx", "Id"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteAGatewayResponse() throws InterruptedException {
|
||||
String apiId = createMockApi(STACK);
|
||||
String deploymentId = createDeployment(apiId);
|
||||
createStage(apiId, "dev", deploymentId);
|
||||
try {
|
||||
cloudFormation("CreateStack", parameters(apiId, "https://app.example", "401"));
|
||||
String created = describeStacks("CREATE_COMPLETE");
|
||||
|
||||
assertEquals(apiId + "-DEFAULT_4XX", outputValue(created, "ResponseRef"));
|
||||
assertEquals(apiId + "-DEFAULT_4XX", outputValue(created, "ResponseId"));
|
||||
|
||||
getGatewayResponse(apiId)
|
||||
.statusCode(200)
|
||||
.body("defaultResponse", equalTo(false))
|
||||
.body("statusCode", equalTo("401"))
|
||||
.body("responseParameters.'gatewayresponse.header.Access-Control-Allow-Origin'",
|
||||
equalTo("'https://app.example'"))
|
||||
.body("responseParameters.'gatewayresponse.header.Access-Control-Allow-Headers'", equalTo("'*'"));
|
||||
|
||||
// The customisation shapes the gateway-generated answer to an unmatched route.
|
||||
given().when().get("/execute-api/" + apiId + "/dev/missing")
|
||||
.then().statusCode(401)
|
||||
.header("Access-Control-Allow-Origin", equalTo("https://app.example"))
|
||||
.header("Access-Control-Allow-Headers", equalTo("*"))
|
||||
.body("message", equalTo("Missing Authentication Token"));
|
||||
|
||||
cloudFormation("UpdateStack", parameters(apiId, "https://other.example", "404"));
|
||||
String updated = describeStacks("UPDATE_COMPLETE");
|
||||
|
||||
assertEquals(apiId + "-DEFAULT_4XX", outputValue(updated, "ResponseRef"));
|
||||
getGatewayResponse(apiId)
|
||||
.statusCode(200)
|
||||
.body("statusCode", equalTo("404"))
|
||||
.body("responseParameters.'gatewayresponse.header.Access-Control-Allow-Origin'",
|
||||
equalTo("'https://other.example'"));
|
||||
given().when().get("/execute-api/" + apiId + "/dev/missing")
|
||||
.then().statusCode(404)
|
||||
.header("Access-Control-Allow-Origin", equalTo("https://other.example"));
|
||||
|
||||
cloudFormation("DeleteStack", Map.of());
|
||||
awaitStackDeleted();
|
||||
|
||||
// The stack owned the customisation, not the API: the type is back to its default.
|
||||
getGatewayResponse(apiId).statusCode(200).body("defaultResponse", equalTo(true));
|
||||
given().when().get("/restapis/" + apiId).then().statusCode(200);
|
||||
given().when().get("/execute-api/" + apiId + "/dev/missing")
|
||||
.then().statusCode(403)
|
||||
.header("Access-Control-Allow-Origin", nullValue());
|
||||
} finally {
|
||||
given().when().delete("/restapis/" + apiId);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> parameters(String apiId, String origin, String statusCode) {
|
||||
return Map.of("ApiId", apiId, "Origin", origin, "StatusCode", statusCode);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, Map<String, String> parameters) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", STACK);
|
||||
if (!"DeleteStack".equals(action)) {
|
||||
request.formParam("TemplateBody", TEMPLATE);
|
||||
}
|
||||
int index = 1;
|
||||
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
|
||||
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
|
||||
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
|
||||
index++;
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
|
||||
private static void awaitStackDeleted() throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
String body = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (body.contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
fail("stack delete failed: " + body);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + STACK + " was not deleted within the timeout");
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
|
||||
private static ValidatableResponse getGatewayResponse(String apiId) {
|
||||
return given().when().get("/restapis/" + apiId + "/gatewayresponses/DEFAULT_4XX").then();
|
||||
}
|
||||
|
||||
/** A REST API whose GET /items is a MOCK integration, enough for a deployment and a stage. */
|
||||
private static String createMockApi(String name) {
|
||||
String apiId = given().contentType(ContentType.JSON).body("{\"name\":\"" + name + "\"}")
|
||||
.when().post("/restapis").then().statusCode(201).extract().path("id");
|
||||
String rootId = given().when().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200).extract().path("item[0].id");
|
||||
String resourceId = given().contentType(ContentType.JSON).body("{\"pathPart\":\"items\"}")
|
||||
.when().post("/restapis/" + apiId + "/resources/" + rootId).then().statusCode(201).extract().path("id");
|
||||
String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
|
||||
given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
|
||||
.when().put(method).then().statusCode(201);
|
||||
given().contentType(ContentType.JSON).body("{\"responseParameters\":{}}")
|
||||
.when().put(method + "/responses/200").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
|
||||
.when().put(method + "/integration").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{}\"}}")
|
||||
.when().put(method + "/integration/responses/200").then().statusCode(201);
|
||||
return apiId;
|
||||
}
|
||||
|
||||
private static String createDeployment(String apiId) {
|
||||
return given().contentType(ContentType.JSON).body("{\"description\":\"v1\"}")
|
||||
.when().post("/restapis/" + apiId + "/deployments").then().statusCode(201).extract().path("id");
|
||||
}
|
||||
|
||||
private static void createStage(String apiId, String stage, String deploymentId) {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"stageName\":\"" + stage + "\",\"deploymentId\":\"" + deploymentId + "\"}")
|
||||
.when().post("/restapis/" + apiId + "/stages").then().statusCode(201);
|
||||
}
|
||||
}
|
||||
+2
@@ -29,6 +29,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayApiKeyCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayGatewayResponseCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
|
||||
@@ -283,6 +284,7 @@ final class CfnProvisionerFixture {
|
||||
discovered.add(new ApiGatewayApiKeyCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayUsagePlanCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayGatewayResponseCfnProvisioner(apiGatewayService));
|
||||
}
|
||||
if (autoScalingService != null) {
|
||||
discovered.add(new AutoScalingGroupCfnProvisioner(autoScalingService));
|
||||
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The API Gateway gateway response CFN provisioner in isolation, against a mocked {@link ApiGatewayService}. */
|
||||
class ApiGatewayGatewayResponseCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String TYPE = "AWS::ApiGateway::GatewayResponse";
|
||||
|
||||
private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
|
||||
private final ApiGatewayGatewayResponseCfnProvisioner provisioner =
|
||||
new ApiGatewayGatewayResponseCfnProvisioner(apiGateway);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
return ctx(null);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private static StackResource resource(String priorPhysicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Cors4xx");
|
||||
r.setResourceType(TYPE);
|
||||
r.setPhysicalId(priorPhysicalId);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private ObjectNode props(String restApiId, String responseType, String statusCode) {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
if (restApiId != null) {
|
||||
props.put("RestApiId", restApiId);
|
||||
}
|
||||
if (responseType != null) {
|
||||
props.put("ResponseType", responseType);
|
||||
}
|
||||
if (statusCode != null) {
|
||||
props.put("StatusCode", statusCode);
|
||||
}
|
||||
props.putObject("ResponseParameters")
|
||||
.put("gatewayresponse.header.Access-Control-Allow-Origin", "'*'")
|
||||
.put("gatewayresponse.header.Access-Control-Allow-Headers", "'*'");
|
||||
props.putObject("ResponseTemplates").put("application/json", "{\"message\":$context.error.messageString}");
|
||||
return props;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPutsTheGatewayResponseAndRecordsTheCompositeId() {
|
||||
when(apiGateway.putGatewayResponse(eq(REGION), eq("api1"), eq("DEFAULT_4XX"), anyMap()))
|
||||
.thenReturn(new GatewayResponse());
|
||||
StackResource r = resource(null);
|
||||
|
||||
provisioner.provision(r, props("api1", "DEFAULT_4XX", "400"), ctx());
|
||||
|
||||
assertEquals("api1-DEFAULT_4XX", r.getPhysicalId());
|
||||
assertEquals("api1-DEFAULT_4XX", r.getAttributes().get("Id"));
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
|
||||
verify(apiGateway).putGatewayResponse(eq(REGION), eq("api1"), eq("DEFAULT_4XX"), request.capture());
|
||||
assertEquals("400", request.getValue().get("statusCode"));
|
||||
assertEquals(Map.of(
|
||||
"gatewayresponse.header.Access-Control-Allow-Origin", "'*'",
|
||||
"gatewayresponse.header.Access-Control-Allow-Headers", "'*'"),
|
||||
request.getValue().get("responseParameters"));
|
||||
assertEquals(Map.of("application/json", "{\"message\":$context.error.messageString}"),
|
||||
request.getValue().get("responseTemplates"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOmittedStatusCodeIsNotSent() {
|
||||
provisioner.provision(resource(null), props("api1", "DEFAULT_4XX", null), ctx());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
|
||||
verify(apiGateway).putGatewayResponse(eq(REGION), eq("api1"), eq("DEFAULT_4XX"), request.capture());
|
||||
assertFalse(request.getValue().containsKey("statusCode"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingRequiredPropertiesAreRefused() {
|
||||
AwsException noApi = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(null), props(null, "DEFAULT_4XX", null), ctx()));
|
||||
assertEquals("ValidationError", noApi.getErrorCode());
|
||||
|
||||
AwsException noType = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(null), props("api1", null, null), ctx()));
|
||||
assertEquals("ValidationError", noType.getErrorCode());
|
||||
verify(apiGateway, never()).putGatewayResponse(any(), any(), any(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRePutsUnderTheSameId() {
|
||||
StackResource r = resource("api1-DEFAULT_4XX");
|
||||
|
||||
provisioner.provision(r, props("api1", "DEFAULT_4XX", "404"), ctx("api1-DEFAULT_4XX"));
|
||||
|
||||
assertEquals("api1-DEFAULT_4XX", r.getPhysicalId());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
|
||||
verify(apiGateway).putGatewayResponse(eq(REGION), eq("api1"), eq("DEFAULT_4XX"), request.capture());
|
||||
assertEquals("404", request.getValue().get("statusCode"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheApiOrTheTypeIsRefusedAsReplacementWorthy() {
|
||||
AwsException apiChanged = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
resource("api1-DEFAULT_4XX"), props("api2", "DEFAULT_4XX", null), ctx("api1-DEFAULT_4XX")));
|
||||
assertTrue(apiChanged.getMessage().contains("RestApiId"));
|
||||
|
||||
AwsException typeChanged = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
resource("api1-DEFAULT_4XX"), props("api1", "DEFAULT_5XX", null), ctx("api1-DEFAULT_4XX")));
|
||||
assertTrue(typeChanged.getMessage().contains("ResponseType"));
|
||||
verify(apiGateway, never()).putGatewayResponse(any(), any(), any(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDelegatesToTheService() {
|
||||
provisioner.delete(TYPE, "api1-MISSING_AUTHENTICATION_TOKEN", REGION);
|
||||
|
||||
verify(apiGateway).deleteGatewayResponse(REGION, "api1", "MISSING_AUTHENTICATION_TOKEN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAResponseThatIsAlreadyGone() {
|
||||
doThrow(new AwsException("NotFoundException", "Gateway response not found", 404))
|
||||
.when(apiGateway).deleteGatewayResponse(REGION, "api1", "DEFAULT_4XX");
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, "api1-DEFAULT_4XX", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteLeavesAnUnparseableIdAlone() {
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, "no-separator-here-", REGION));
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, "", REGION));
|
||||
verify(apiGateway, never()).deleteGatewayResponse(any(), any(), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user