Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(apigateway): support Gateway Responses on REST APIs (#3326) (#3585)

Matheus André2ee3aa67c008
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index fe853d255d..7358369a64 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -56,6 +56,7 @@ duplicate override IDs.
| **Usage Plans** | CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan |
| **Usage Plan Keys** | CreateUsagePlanKey, GetUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey |
| **Request Validators** | CreateRequestValidator, GetRequestValidator, GetRequestValidators, UpdateRequestValidator, DeleteRequestValidator |
+| **Gateway Responses** | PutGatewayResponse, GetGatewayResponse, GetGatewayResponses, UpdateGatewayResponse, DeleteGatewayResponse |
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName |
| **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, UpdateBasePathMapping, DeleteBasePathMapping |
@@ -174,13 +175,55 @@ handling; a hand-rolled signer must include it.
> signed, known caller is let through. `principalOrgId` and `cognitoIdentity` are always null -
> Organizations membership and identity-pool federation are not modelled.
+### Gateway Responses
+
+A REST API's gateway responses customise what the gateway itself answers when it, rather than
+the integration, produces the response. All 21 AWS response types are accepted, keyed by
+`responseType`; `GetGatewayResponses` lists every type, reporting the ones never customised with
+`defaultResponse: true`, their AWS default `statusCode`, and the default
+`{"message":$context.error.messageString}` template. `PutGatewayResponse` is an upsert,
+`UpdateGatewayResponse` accepts `add`/`replace`/`remove` on `/statusCode`,
+`/responseParameters/<name>` and `/responseTemplates/<content-type>` (JSON-pointer escaped, e.g.
+`application~1json`), and `DeleteGatewayResponse` restores the default. The
+`x-amazon-apigateway-gateway-responses` OpenAPI extension is imported by `ImportRestApi` and
+`PutRestApi`, and `AWS::ApiGateway::GatewayResponse` is provisioned by CloudFormation.
+
+On the execute plane every gateway-generated answer resolves the customisation for its type,
+then for `DEFAULT_4XX` / `DEFAULT_5XX`, and applies the configured `statusCode`, the
+`gatewayresponse.header.*` parameters (`'static'`, `method.request.header.*`,
+`method.request.querystring.*`, `method.request.path.*`, `context.*`, `stageVariables.*`) and the
+`responseTemplates` (selected by the request's `Accept` header, falling back to
+`application/json`), with `$context.error.message`, `$context.error.messageString`,
+`$context.error.responseType` and `$context.error.validationErrorString` available to the template.
+This is what lets a browser read a `401`/`403`/`400` as such instead of as a CORS failure once
+`DEFAULT_4XX` maps `Access-Control-Allow-Origin`, exactly as the console's "Enable CORS" does.
+
+| Gateway-generated answer | `responseType` |
+|---|---|
+| No resource matches the path, or none declares the method (`403 Missing Authentication Token`) | `MISSING_AUTHENTICATION_TOKEN` |
+| `AWS_IAM` method without a signature | `MISSING_AUTHENTICATION_TOKEN` |
+| `AWS_IAM` signature malformed or mismatching | `INVALID_SIGNATURE` |
+| `AWS_IAM` signature outside the 5-minute window, or a presigned URL past its expiry | `EXPIRED_TOKEN` |
+| `AWS_IAM` access key the emulator never issued | `ACCESS_DENIED` |
+| Lambda authorizer returns `Deny` | `ACCESS_DENIED` |
+| Lambda authorizer fails or throws | `AUTHORIZER_FAILURE` |
+| Method with `apiKeyRequired` and no usable `x-api-key` (`403 Forbidden`) | `INVALID_API_KEY` |
+| Request validator rejects a parameter / the body | `BAD_REQUEST_PARAMETERS` / `BAD_REQUEST_BODY` |
+| `passthroughBehavior` rejects the request `Content-Type` (`415`) | `UNSUPPORTED_MEDIA_TYPE` |
+| Missing or unresolvable integration or URI, MOCK template that does not render | `API_CONFIGURATION_ERROR` |
+| Lambda proxy function error, malformed proxy payload, or missing function | `INTEGRATION_FAILURE` |
+
+A customised `statusCode` overrides the status Floci would otherwise send. Throttling, quota, request size and WAF answers are not produced on the execute plane, so
+`THROTTLED`, `QUOTA_EXCEEDED`, `REQUEST_TOO_LARGE` and `WAF_FILTERED` can be configured but never
+fire, and an `HTTP`/`HTTP_PROXY` backend's own status is relayed rather than treated as a gateway
+response.
+
### Not Implemented
These management-plane operations have no handler in v1. Calls will return `404` or an error:
- Authorizer testing: `TestInvokeAuthorizer`
- Model templates: `GetModelTemplate`
-- Gateway Responses (the entire family: `PutGatewayResponse`, `GetGatewayResponse`, etc.)
- Documentation parts and versions (the entire family, 10 operations)
- VPC Links (5 operations)
- Client Certificates (5 operations)
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 6ea5e81905..1839c60807 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -85,7 +85,7 @@ cross-resource references.
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
| Route 53 | `HostedZone`, `RecordSet` |
-| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
+| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
| AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey` |
| Step Functions | `StateMachine` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index ba1cfabda9..b8a2b7b3d3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
import io.github.hectorvent.floci.services.apigateway.model.EndpointType;
+import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
import io.github.hectorvent.floci.services.apigateway.model.MethodResponse;
import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;
@@ -872,6 +873,71 @@ public class ApiGatewayController {
return Response.accepted().build();
}
+ // ──────────────────────────── Gateway Responses (v1) ────────────────────────────
+
+ @PUT
+ @Path("/restapis/{apiId}/gatewayresponses/{responseType}")
+ public Response putGatewayResponse(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @PathParam("responseType") String responseType,
+ String body) {
+ String region = regionResolver.resolveRegion(headers);
+ try {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> request = body == null || body.isBlank()
+ ? new HashMap<>()
+ : objectMapper.readValue(body, Map.class);
+ GatewayResponse response = service.putGatewayResponse(region, apiId, responseType, request);
+ return Response.status(201).entity(toGatewayResponseNode(response).toString())
+ .type(MediaType.APPLICATION_JSON).build();
+ } catch (IOException e) {
+ throw new AwsException("BadRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/restapis/{apiId}/gatewayresponses")
+ public Response getGatewayResponses(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
+ String region = regionResolver.resolveRegion(headers);
+ List<GatewayResponse> responses = service.getGatewayResponses(region, apiId);
+ ObjectNode root = objectMapper.createObjectNode();
+ ArrayNode items = root.putArray("item");
+ responses.forEach(response -> items.add(toGatewayResponseNode(response)));
+ return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @GET
+ @Path("/restapis/{apiId}/gatewayresponses/{responseType}")
+ public Response getGatewayResponse(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @PathParam("responseType") String responseType) {
+ String region = regionResolver.resolveRegion(headers);
+ GatewayResponse response = service.getGatewayResponse(region, apiId, responseType);
+ return Response.ok(toGatewayResponseNode(response).toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @PATCH
+ @Path("/restapis/{apiId}/gatewayresponses/{responseType}")
+ public Response updateGatewayResponse(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @PathParam("responseType") String responseType,
+ String body) {
+ String region = regionResolver.resolveRegion(headers);
+ List<Map<String, String>> patchOperations = parsePatchOperations(body);
+ GatewayResponse response = service.updateGatewayResponse(region, apiId, responseType, patchOperations);
+ return Response.ok(toGatewayResponseNode(response).toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @DELETE
+ @Path("/restapis/{apiId}/gatewayresponses/{responseType}")
+ public Response deleteGatewayResponse(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @PathParam("responseType") String responseType) {
+ String region = regionResolver.resolveRegion(headers);
+ service.deleteGatewayResponse(region, apiId, responseType);
+ return Response.accepted().build();
+ }
+
// ──────────────────────────── Request Validators (v1) ────────────────────────────
@POST
@@ -2310,6 +2376,20 @@ public class ApiGatewayController {
return node;
}
+ private ObjectNode toGatewayResponseNode(GatewayResponse response) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("responseType", response.getResponseType());
+ if (response.getStatusCode() != null) {
+ node.put("statusCode", response.getStatusCode());
+ }
+ ObjectNode parameters = node.putObject("responseParameters");
+ response.getResponseParameters().forEach(parameters::put);
+ ObjectNode templates = node.putObject("responseTemplates");
+ response.getResponseTemplates().forEach(templates::put);
+ node.put("defaultResponse", response.isDefaultResponse());
+ return node;
+ }
+
private ObjectNode toRequestValidatorNode(RequestValidator v) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", v.getId());
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
index 5b8aed82d8..600d14e6b5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
+import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
+import io.github.hectorvent.floci.services.apigateway.model.GatewayResponseType;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
@@ -41,8 +43,12 @@ import jakarta.ws.rs.core.*;
import org.jboss.logging.Logger;
import java.net.URLDecoder;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
@@ -137,6 +143,21 @@ public class ApiGatewayExecuteController {
private record AuthorizerResult(Response errorResponse, String principalId, Map<String, Object> context) {}
+ /**
+ * What a gateway-generated error needs in order to render the REST API's gateway response for
+ * it: where the request landed and the raw request, for {@code method.request.*},
+ * {@code context.*} and {@code stageVariables.*} parameter sources. The resource is null until
+ * routing has matched one.
+ */
+ private record GatewayResponseScope(String region, String apiId, String stageName, Stage stage,
+ String httpMethod, String path, ApiGatewayResource resource,
+ HttpHeaders headers, UriInfo uriInfo, byte[] body) {
+ GatewayResponseScope withResource(ApiGatewayResource matched) {
+ return new GatewayResponseScope(region, apiId, stageName, stage, httpMethod, path, matched,
+ headers, uriInfo, body);
+ }
+ }
+
// ──────────────────────────── @connections API ────────────────────────────
private static final String CONNECTIONS_PREFIX = "@connections/";
@@ -327,12 +348,14 @@ public class ApiGatewayExecuteController {
}
String path = "/" + (proxy == null ? "" : proxy);
+ GatewayResponseScope scope = new GatewayResponseScope(region, apiId, stageName, stage, httpMethod, path,
+ null, headers, uriInfo, body);
// Find matching resource and method
List<ApiGatewayResource> resources = apiGatewayService.getResources(region, apiId);
List<ApiGatewayResource> matchedResources = matchResources(resources, path);
if (matchedResources.isEmpty()) {
- return restNoMatch();
+ return restNoMatch(scope);
}
ApiGatewayResource matched = null;
@@ -360,8 +383,9 @@ public class ApiGatewayExecuteController {
}
if (matched == null) {
- return restNoMatch();
+ return restNoMatch(scope);
}
+ scope = scope.withResource(matched);
// 1. Authorizer
ResolvedApiKey resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers);
@@ -374,32 +398,28 @@ public class ApiGatewayExecuteController {
ExecuteApiSigV4Authorizer.Result iamResult =
sigV4Authorizer.authorize(httpMethod, headers, uriInfo, body, routeContext.signedRequestPath());
if (!iamResult.authorized()) {
- return restIamRejection(iamResult);
+ return restIamRejection(scope, iamResult);
}
iamIdentity = iamResult.identity();
}
- AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey);
+ 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();
// 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
// no enabled key linked to this (apiId, stage) through a usage plan.
if (method.isApiKeyRequired() && resolvedApiKey == null) {
- return Response.status(403)
- .entity(jsonMessage("Forbidden"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.INVALID_API_KEY, 403, "Forbidden");
}
// 2. Request validation
- Response validationResponse = validateRequest(region, apiId, method, headers, uriInfo, body);
+ Response validationResponse = validateRequest(scope, region, apiId, method, headers, uriInfo, body);
if (validationResponse != null) return validationResponse;
Integration integration = method.getMethodIntegration();
if (integration == null) {
- return Response.status(500)
- .entity(jsonMessage("No integration configured"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, "No integration configured");
}
LOG.debugv("execute-api: {0} {1}/{2}{3} → {4}", httpMethod, apiId, stageName, path,
@@ -409,26 +429,24 @@ public class ApiGatewayExecuteController {
// report it rather than failing with an NPE inside the switch.
String integrationType = integration.getType();
if (integrationType == null || integrationType.isBlank()) {
- return Response.status(500)
- .entity(jsonMessage("No integration type configured"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "No integration type configured");
}
return switch (integrationType.toUpperCase(Locale.ROOT)) {
- case "AWS_PROXY" -> invokeProxy(region, apiId, httpMethod, path, proxy, stageName,
+ case "AWS_PROXY" -> invokeProxy(scope, region, apiId, httpMethod, path, proxy, stageName,
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey,
iamIdentity);
- case "AWS" -> invokeAwsIntegration(region, httpMethod, path, stageName,
+ case "AWS" -> invokeAwsIntegration(scope, region, httpMethod, path, stageName,
matched, integration, headers, uriInfo, body, authorizerResult);
- case "HTTP_PROXY" -> invokeHttpProxy(apiId, httpMethod, path, proxy, stageName,
+ case "HTTP_PROXY" -> invokeHttpProxy(scope, apiId, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
- case "HTTP" -> invokeHttpIntegration(apiId, httpMethod, path, proxy, stageName,
+ case "HTTP" -> invokeHttpIntegration(scope, apiId, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body, authorizerResult);
- case "MOCK" -> invokeMock(region, httpMethod, path, stageName,
+ case "MOCK" -> invokeMock(scope, region, httpMethod, path, stageName,
matched, integration, headers, uriInfo, body, authorizerResult);
- default -> Response.status(500)
- .entity(jsonMessage("Unsupported integration type: " + integration.getType()))
- .type(MediaType.APPLICATION_JSON).build();
+ default -> gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "Unsupported integration type: " + integration.getType());
};
}
@@ -439,7 +457,8 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── AWS_PROXY ────────────────────────────
- private Response invokeProxy(String region, String apiId, String httpMethod, String path, String proxy,
+ private Response invokeProxy(GatewayResponseScope scope, String region, String apiId, String httpMethod,
+ String path, String proxy,
String stageName, ApiGatewayResource resource,
Stage stage,
Integration integration, HttpHeaders headers,
@@ -448,9 +467,8 @@ public class ApiGatewayExecuteController {
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
String functionName = functionNameFromUri(integration.getUri());
if (functionName == null) {
- return Response.status(500)
- .entity(jsonMessage("Cannot resolve function from URI: " + integration.getUri()))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "Cannot resolve function from URI: " + integration.getUri());
}
String requestId = UUID.randomUUID().toString();
@@ -461,12 +479,18 @@ public class ApiGatewayExecuteController {
try {
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
InvocationType.RequestResponse);
- return buildProxyResponse(result, false);
+ Response response = buildProxyResponse(result, false);
+ if (response.getStatus() == 502 && isGatewayGeneratedProxyFailure(result)) {
+ // A function error or a payload that is not a proxy response is answered by the
+ // gateway itself, so a configured INTEGRATION_FAILURE / DEFAULT_5XX shapes it.
+ return gatewayResponseOr(response, scope, GatewayResponseType.INTEGRATION_FAILURE,
+ "Internal server error");
+ }
+ return response;
} catch (AwsException e) {
if (e.getHttpStatus() == 404) {
- return Response.status(404)
- .entity(jsonMessage("Function not found: " + functionName))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.INTEGRATION_FAILURE, 404,
+ "Function not found: " + functionName);
}
throw e;
}
@@ -482,15 +506,14 @@ public class ApiGatewayExecuteController {
* error statuses, which must not be remapped into a gateway error. Only
* {@code integration.request.*} parameter mapping applies on the way out.
*/
- private Response invokeHttpProxy(String apiId, String httpMethod, String path, String proxy,
- String stageName, ApiGatewayResource resource,
+ private Response invokeHttpProxy(GatewayResponseScope scope, String apiId, String httpMethod, String path,
+ String proxy, String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body) {
String uri = integration.getUri();
if (uri == null || uri.isBlank()) {
- return Response.status(500)
- .entity(jsonMessage("No integration URI configured"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "No integration URI configured");
}
// Two views of the same inbound data. The multi-value maps are what gets forwarded: a
@@ -590,16 +613,15 @@ public class ApiGatewayExecuteController {
* {@code selectionPattern} is matched against the backend's HTTP status code (for
* {@code AWS}/Lambda integrations it is matched against the error message instead).
*/
- private Response invokeHttpIntegration(String apiId, String httpMethod, String path, String proxy,
- String stageName, ApiGatewayResource resource,
+ private Response invokeHttpIntegration(GatewayResponseScope scope, String apiId, String httpMethod, String path,
+ String proxy, String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body,
AuthorizerResult authorizerResult) {
String uri = integration.getUri();
if (uri == null || uri.isBlank()) {
- return Response.status(500)
- .entity(jsonMessage("No integration URI configured"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "No integration URI configured");
}
String requestId = UUID.randomUUID().toString();
@@ -650,7 +672,7 @@ public class ApiGatewayExecuteController {
}
RequestTemplateResult requestTemplateResult =
- applyRequestTemplates(integration, incomingContentType, bodyStr, vtlCtx);
+ applyRequestTemplates(scope, integration, incomingContentType, bodyStr, vtlCtx);
if (requestTemplateResult.rejection() != null) return requestTemplateResult.rejection();
String transformedBody = requestTemplateResult.body();
@@ -712,7 +734,22 @@ public class ApiGatewayExecuteController {
defaultContentType);
}
- private AuthorizerResult invokeAuthorizer(String region, String apiId, String stageName,
+ private boolean isGatewayGeneratedProxyFailure(InvokeResult result) {
+ if (result.getFunctionError() != null) {
+ return true;
+ }
+ byte[] payload = result.getPayload();
+ if (payload == null || payload.length == 0) {
+ return false;
+ }
+ try {
+ return !objectMapper.readTree(payload).isObject();
+ } catch (IOException e) {
+ return true;
+ }
+ }
+
+ private AuthorizerResult invokeAuthorizer(GatewayResponseScope scope, String region, String apiId, String stageName,
String httpMethod, String requestPath, String resourcePath,
String resourceId,
Stage stage,
@@ -734,14 +771,16 @@ public class ApiGatewayExecuteController {
try {
InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse);
if (result.getFunctionError() != null) {
- return new AuthorizerResult(Response.status(403).build(), null, null);
+ return new AuthorizerResult(gatewayResponseOr(Response.status(403).build(), scope,
+ GatewayResponseType.AUTHORIZER_FAILURE, null), null, null);
}
JsonNode policy = objectMapper.readTree(result.getPayload());
String effect = policy.path("policyDocument").path("Statement").get(0).path("Effect").asText("Deny");
if ("Deny".equalsIgnoreCase(effect)) {
return new AuthorizerResult(
- Response.status(403).entity(jsonMessage("User is not authorized to access this resource")).build(),
+ gatewayResponse(scope, GatewayResponseType.ACCESS_DENIED, 403,
+ "User is not authorized to access this resource"),
null,
null);
}
@@ -750,13 +789,14 @@ public class ApiGatewayExecuteController {
return new AuthorizerResult(null, principalId, context);
} catch (Exception e) {
LOG.warnv("Authorizer failure: {0}", e.getMessage());
- return new AuthorizerResult(Response.status(500).build(), null, null);
+ return new AuthorizerResult(gatewayResponseOr(Response.status(500).build(), scope,
+ GatewayResponseType.AUTHORIZER_FAILURE, null), null, null);
}
}
return new AuthorizerResult(null, null, null);
}
- private Response validateRequest(String region, String apiId, MethodConfig method,
+ private Response validateRequest(GatewayResponseScope scope, String region, String apiId, MethodConfig method,
HttpHeaders headers, UriInfo uriInfo, byte[] body) {
String validatorId = method.getRequestValidatorId();
if (validatorId == null) return null;
@@ -780,16 +820,14 @@ public class ApiGatewayExecuteController {
if (paramKey.startsWith("method.request.querystring.")) {
String name = paramKey.substring("method.request.querystring.".length());
if (!queryParams.containsKey(name) || queryParams.getFirst(name) == null) {
- return Response.status(400)
- .entity(jsonMessage("Missing required request parameter in QUERY_STRING: '" + name + "'"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_PARAMETERS, 400,
+ "Missing required request parameter in QUERY_STRING: '" + name + "'");
}
} else if (paramKey.startsWith("method.request.header.")) {
String name = paramKey.substring("method.request.header.".length());
if (headers.getHeaderString(name) == null) {
- return Response.status(400)
- .entity(jsonMessage("Missing required request parameter in HEADER: '" + name + "'"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_PARAMETERS, 400,
+ "Missing required request parameter in HEADER: '" + name + "'");
}
}
}
@@ -814,9 +852,8 @@ public class ApiGatewayExecuteController {
if (schemaStr != null && !schemaStr.isBlank()) {
String bodyStr = body != null ? new String(body, StandardCharsets.UTF_8) : "";
if (bodyStr.isBlank()) {
- return Response.status(400)
- .entity(jsonMessage("Invalid request body"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
+ "Invalid request body");
}
JsonNode schemaNode = objectMapper.readTree(schemaStr);
JsonNode bodyNode = objectMapper.readTree(bodyStr);
@@ -828,17 +865,15 @@ public class ApiGatewayExecuteController {
var errors = schema.validate(bodyNode);
if (!errors.isEmpty()) {
String errorMsg = errors.iterator().next().getMessage();
- return Response.status(400)
- .entity(jsonMessage("Invalid request body: " + errorMsg))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
+ "Invalid request body: " + errorMsg, errorMsg);
}
}
} catch (AwsException e) {
// Model not found — skip body validation
} catch (Exception e) {
- return Response.status(400)
- .entity(jsonMessage("Invalid request body"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
+ "Invalid request body");
}
}
}
@@ -1264,16 +1299,15 @@ public class ApiGatewayExecuteController {
return result.isEmpty() ? null : result;
}
- private Response invokeAwsIntegration(String region, String httpMethod, String path,
+ private Response invokeAwsIntegration(GatewayResponseScope scope, String region, String httpMethod, String path,
String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body,
AuthorizerResult authorizerResult) {
AwsServiceRouter.IntegrationTarget target = serviceRouter.parseIntegrationUri(integration.getUri());
if (target == null) {
- return Response.status(500)
- .entity(jsonMessage("Cannot parse AWS integration URI: " + integration.getUri()))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "Cannot parse AWS integration URI: " + integration.getUri());
}
String requestId = UUID.randomUUID().toString();
@@ -1328,7 +1362,7 @@ public class ApiGatewayExecuteController {
// Content-Type negotiation and passthrough behavior
RequestTemplateResult requestTemplateResult =
- applyRequestTemplates(integration, incomingContentType, bodyStr, vtlCtx);
+ applyRequestTemplates(scope, integration, incomingContentType, bodyStr, vtlCtx);
if (requestTemplateResult.rejection() != null) return requestTemplateResult.rejection();
String transformedBody = requestTemplateResult.body();
@@ -1472,11 +1506,11 @@ public class ApiGatewayExecuteController {
* {@code passthroughBehavior} when no template matches. Shared by the {@code AWS} and
* {@code HTTP} (non-proxy) integration types, which negotiate identically.
*/
- private RequestTemplateResult applyRequestTemplates(Integration integration, String incomingContentType,
- String bodyStr, VtlTemplateEngine.VtlContext vtlCtx) {
- Response unsupportedMediaType = Response.status(415)
- .entity(jsonMessage("Unsupported Media Type"))
- .type(MediaType.APPLICATION_JSON).build();
+ private RequestTemplateResult applyRequestTemplates(GatewayResponseScope scope, Integration integration,
+ String incomingContentType, String bodyStr,
+ VtlTemplateEngine.VtlContext vtlCtx) {
+ Response unsupportedMediaType = gatewayResponse(scope, GatewayResponseType.UNSUPPORTED_MEDIA_TYPE, 415,
+ "Unsupported Media Type");
Map<String, String> requestTemplates = integration.getRequestTemplates();
if (requestTemplates == null || requestTemplates.isEmpty()) {
@@ -1667,8 +1701,8 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── MOCK ────────────────────────────
- private Response invokeMock(String region, String httpMethod, String path, String stageName,
- ApiGatewayResource resource, Integration integration,
+ private Response invokeMock(GatewayResponseScope scope, String region, String httpMethod, String path,
+ String stageName, ApiGatewayResource resource, Integration integration,
HttpHeaders headers, UriInfo uriInfo, byte[] body,
AuthorizerResult authorizerResult) {
String requestId = UUID.randomUUID().toString();
@@ -1709,17 +1743,13 @@ public class ApiGatewayExecuteController {
Integer mockStatus = resolveMockStatusCode(integration, resource, httpMethod, headers, bodyStr, vtlCtx);
if (mockStatus == null) {
// A request template that does not render is a configuration error on AWS too.
- return Response.status(500)
- .entity(jsonMessage("Internal server error"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, "Internal server error");
}
IntegrationResponse ir = selectMockIntegrationResponse(integrationResponses, mockStatus);
if (ir == null) {
LOG.warnv("execute-api: MOCK {0} {1} produced statusCode {2} but no integration response "
+ "matches it and none is the default", httpMethod, resource.getPath(), mockStatus);
- return Response.status(500)
- .entity(jsonMessage("Internal server error"))
- .type(MediaType.APPLICATION_JSON).build();
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, "Internal server error");
}
String template = ir.responseTemplates() != null
@@ -2329,7 +2359,7 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── AWS_IAM (SigV4) rejections ────────────────────────────
- private record RestIamError(String errorType, String message) {}
+ private record RestIamError(String errorType, String message, GatewayResponseType responseType) {}
/**
* Renders a failed AWS_IAM check the way a REST API does: always {@code 403}, with the message
@@ -2337,26 +2367,26 @@ public class ApiGatewayExecuteController {
* omits the canonical-string dump real AWS appends, which is a debugging aid rather than part of
* the contract; the reason is logged instead.
*/
- private Response restIamRejection(ExecuteApiSigV4Authorizer.Result result) {
+ private Response restIamRejection(GatewayResponseScope scope, ExecuteApiSigV4Authorizer.Result result) {
LOG.debugv("execute-api AWS_IAM rejected a REST request: {0} ({1})",
result.failure(), result.detail());
RestIamError error = switch (result.failure()) {
case MISSING -> new RestIamError("MissingAuthenticationTokenException",
- "Missing Authentication Token");
+ "Missing Authentication Token", GatewayResponseType.MISSING_AUTHENTICATION_TOKEN);
case MALFORMED -> new RestIamError("IncompleteSignatureException",
- "Incomplete Signature");
+ "Incomplete Signature", GatewayResponseType.INVALID_SIGNATURE);
case UNKNOWN_KEY -> new RestIamError("UnrecognizedClientException",
- "The security token included in the request is invalid.");
+ "The security token included in the request is invalid.", GatewayResponseType.ACCESS_DENIED);
case EXPIRED -> new RestIamError("InvalidSignatureException",
- "Signature expired");
+ "Signature expired", GatewayResponseType.EXPIRED_TOKEN);
case MISMATCH -> new RestIamError("InvalidSignatureException",
"The request signature we calculated does not match the signature you provided."
- + " Check your AWS Secret Access Key and signing method.");
+ + " Check your AWS Secret Access Key and signing method.",
+ GatewayResponseType.INVALID_SIGNATURE);
};
- return Response.status(403)
+ return gatewayResponseBuilder(scope, error.responseType(), 403, error.message(), null)
.header("x-amzn-ErrorType", error.errorType())
- .entity(jsonMessage(error.message()))
- .type(MediaType.APPLICATION_JSON).build();
+ .build();
}
/**
@@ -2371,12 +2401,15 @@ public class ApiGatewayExecuteController {
*
* <p>HTTP APIs are unaffected: they answer an unmatched route with {@code 404}
* {@code {"message":"Not Found"}}, which the v2 dispatch path continues to do.
+ *
+ * <p>Being gateway-generated, the answer is shaped by the API's
+ * {@code MISSING_AUTHENTICATION_TOKEN} (or {@code DEFAULT_4XX}) gateway response.
*/
- private Response restNoMatch() {
- return Response.status(403)
+ private Response restNoMatch(GatewayResponseScope scope) {
+ return gatewayResponseBuilder(scope, GatewayResponseType.MISSING_AUTHENTICATION_TOKEN, 403,
+ "Missing Authentication Token", null)
.header("x-amzn-ErrorType", "MissingAuthenticationTokenException")
- .entity(jsonMessage("Missing Authentication Token"))
- .type(MediaType.APPLICATION_JSON).build();
+ .build();
}
/**
@@ -2990,6 +3023,282 @@ public class ApiGatewayExecuteController {
}
}
+
+ // ──────────────────────────── Gateway responses ────────────────────────────
+
+ private static final String GATEWAY_RESPONSE_HEADER_PREFIX = "gatewayresponse.header.";
+ private static final DateTimeFormatter GATEWAY_REQUEST_TIME =
+ DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z");
+
+ /**
+ * The {@code {"message": ...}} answer a REST API gives when it, rather than the integration,
+ * produces the response, shaped by the API's gateway response for {@code type}: the customised
+ * type itself, else its DEFAULT_4XX / DEFAULT_5XX, else the plain body Floci always sent.
+ */
+ private Response gatewayResponse(GatewayResponseScope scope, GatewayResponseType type, int status,
+ String message) {
+ return gatewayResponse(scope, type, status, message, null);
+ }
+
+ private Response gatewayResponse(GatewayResponseScope scope, GatewayResponseType type, int status,
+ String message, String validationError) {
+ return gatewayResponseBuilder(scope, type, status, message, validationError).build();
+ }
+
+ private Response.ResponseBuilder gatewayResponseBuilder(GatewayResponseScope scope, GatewayResponseType type,
+ int status, String message, String validationError) {
+ GatewayResponse configured = apiGatewayService.resolveGatewayResponse(scope.region(), scope.apiId(),
+ type, status);
+ if (configured == null) {
+ return Response.status(status).entity(jsonMessage(message)).type(MediaType.APPLICATION_JSON);
+ }
+ return renderGatewayResponse(scope, configured, type, status, message, validationError);
+ }
+
+ /**
+ * For the sites whose uncustomised answer is not the {@code {"message"}} body (a bare status,
+ * or the Lambda payload passed through): the answer stays as it was unless the API customised
+ * a gateway response for it.
+ */
+ private Response gatewayResponseOr(Response fallback, GatewayResponseScope scope, GatewayResponseType type,
+ String message) {
+ GatewayResponse configured = apiGatewayService.resolveGatewayResponse(scope.region(), scope.apiId(),
+ type, fallback.getStatus());
+ if (configured == null) {
+ return fallback;
+ }
+ return renderGatewayResponse(scope, configured, type, fallback.getStatus(), message, null).build();
+ }
+
+ private Response.ResponseBuilder renderGatewayResponse(GatewayResponseScope scope, GatewayResponse configured,
+ GatewayResponseType type, int status, String message,
+ String validationError) {
+ int finalStatus = status;
+ if (configured.getStatusCode() != null) {
+ try {
+ finalStatus = Integer.parseInt(configured.getStatusCode());
+ } catch (NumberFormatException e) {
+ LOG.warnv("Gateway response {0} of API {1} carries a non-numeric statusCode {2}; keeping {3}",
+ configured.getResponseType(), scope.apiId(), configured.getStatusCode(), status);
+ }
+ }
+
+ Map<String, String> headerMap = gatewayRequestHeaders(scope.headers());
+ Map<String, String> queryMap = gatewayRequestQuery(scope.uriInfo());
+ Map<String, String> pathMap = gatewayRequestPathParams(scope);
+ Map<String, Object> context = gatewayResponseContext(scope, type, finalStatus, message, validationError);
+
+ String contentType = MediaType.APPLICATION_JSON;
+ String body = jsonMessage(message);
+ Map<String, String> templates = configured.getResponseTemplates();
+ if (!templates.isEmpty()) {
+ String selected = selectGatewayResponseTemplate(templates, scope.headers());
+ contentType = selected;
+ VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
+ scope.body() != null && scope.body().length > 0
+ ? new String(scope.body(), StandardCharsets.UTF_8) : null,
+ headerMap, queryMap, pathMap, scope.stageName(), scope.httpMethod(),
+ scope.resource() != null ? scope.resource().getPath() : null,
+ String.valueOf(context.get("requestId")), regionResolver.getAccountId(),
+ scope.stage() != null ? scope.stage().getVariables() : null, null, context);
+ try {
+ body = vtlEngine.evaluate(templates.get(selected), vtlCtx).body();
+ } catch (RuntimeException e) {
+ LOG.warnv("Gateway response {0} of API {1}: template for {2} failed to render ({3}); "
+ + "answering with the default body", configured.getResponseType(), scope.apiId(),
+ selected, e.getMessage());
+ }
+ }
+
+ Response.ResponseBuilder rb = Response.status(finalStatus);
+ for (Map.Entry<String, String> parameter : configured.getResponseParameters().entrySet()) {
+ if (!parameter.getKey().startsWith(GATEWAY_RESPONSE_HEADER_PREFIX)) {
+ continue;
+ }
+ String headerName = parameter.getKey().substring(GATEWAY_RESPONSE_HEADER_PREFIX.length());
+ String headerValue = resolveGatewayResponseParameter(parameter.getValue(), scope, context,
+ headerMap, queryMap, pathMap);
+ if (headerValue == null) {
+ continue;
+ }
+ if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(headerName)) {
+ contentType = headerValue;
+ } else {
+ rb.header(headerName, headerValue);
+ }
+ }
+ return rb.entity(body).type(contentType);
+ }
+
+ /**
+ * AWS picks the template whose content type the request's {@code Accept} header names, and
+ * falls back to {@code application/json}, then to the first template declared.
+ */
+ private static String selectGatewayResponseTemplate(Map<String, String> templates, HttpHeaders headers) {
+ String accept = headers != null ? headers.getHeaderString(HttpHeaders.ACCEPT) : null;
+ if (accept != null) {
+ for (String candidate : accept.split(",")) {
+ String mediaType = candidate.contains(";")
+ ? candidate.substring(0, candidate.indexOf(';')).trim()
+ : candidate.trim();
+ if (templates.containsKey(mediaType)) {
+ return mediaType;
+ }
+ }
+ }
+ if (templates.containsKey(MediaType.APPLICATION_JSON)) {
+ return MediaType.APPLICATION_JSON;
+ }
+ return templates.keySet().iterator().next();
+ }
+
+ private String resolveGatewayResponseParameter(String source, GatewayResponseScope scope,
+ Map<String, Object> context, Map<String, String> headerMap,
+ Map<String, String> queryMap, Map<String, String> pathMap) {
+ if (source == null) {
+ return null;
+ }
+ if (source.length() >= 2 && source.startsWith("'") && source.endsWith("'")) {
+ return source.substring(1, source.length() - 1);
+ }
+ if (source.startsWith("method.request.header.")) {
+ return headerMap.get(source.substring("method.request.header.".length()));
+ }
+ if (source.startsWith("method.request.multivalueheader.")) {
+ return joinedValues(scope.headers() != null ? scope.headers().getRequestHeaders() : null,
+ source.substring("method.request.multivalueheader.".length()));
+ }
+ if (source.startsWith("method.request.querystring.")) {
+ return queryMap.get(source.substring("method.request.querystring.".length()));
+ }
+ if (source.startsWith("method.request.multivaluequerystring.")) {
+ return joinedValues(scope.uriInfo() != null ? scope.uriInfo().getQueryParameters() : null,
+ source.substring("method.request.multivaluequerystring.".length()));
+ }
+ if (source.startsWith("method.request.path.")) {
+ return pathMap.get(source.substring("method.request.path.".length()));
+ }
+ if (source.startsWith("context.")) {
+ Object value = contextValue(context, source.substring("context.".length()));
+ return value != null ? String.valueOf(value) : null;
+ }
+ if (source.startsWith("stageVariables.")) {
+ Map<String, String> variables = scope.stage() != null ? scope.stage().getVariables() : null;
+ return variables != null ? variables.get(source.substring("stageVariables.".length())) : null;
+ }
+ return null;
+ }
+
+ private static String joinedValues(MultivaluedMap<String, String> values, String name) {
+ if (values == null) {
+ return null;
+ }
+ for (Map.Entry<String, List<String>> entry : values.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(name) && entry.getValue() != null && !entry.getValue().isEmpty()) {
+ return String.join(",", entry.getValue());
+ }
+ }
+ return null;
+ }
+
+ private static Object contextValue(Map<String, Object> context, String dottedPath) {
+ Object current = context;
+ for (String segment : dottedPath.split("\\.")) {
+ if (!(current instanceof Map<?, ?> map)) {
+ return null;
+ }
+ current = map.get(segment);
+ if (current == null) {
+ return null;
+ }
+ }
+ return current;
+ }
+
+ /**
+ * The {@code $context} a gateway response sees: the same request fields the proxy event
+ * carries, plus {@code error} with the message, its JSON-quoted form, the response type and the
+ * validator's detail, as AWS documents them.
+ */
+ private Map<String, Object> gatewayResponseContext(GatewayResponseScope scope, GatewayResponseType type,
+ int status, String message, String validationError) {
+ String requestId = UUID.randomUUID().toString();
+ String region = scope.region() != null ? scope.region() : regionResolver.getDefaultRegion();
+ ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
+
+ Map<String, Object> context = new LinkedHashMap<>();
+ context.put("accountId", regionResolver.getAccountId());
+ context.put("apiId", scope.apiId());
+ context.put("domainName", scope.apiId() + ".execute-api." + region + ".amazonaws.com");
+ context.put("domainPrefix", scope.apiId());
+ context.put("extendedRequestId", requestId);
+ context.put("httpMethod", scope.httpMethod());
+ context.put("path", "/" + scope.stageName() + scope.path());
+ context.put("protocol", "HTTP/1.1");
+ context.put("requestId", requestId);
+ context.put("requestTime", GATEWAY_REQUEST_TIME.format(now));
+ context.put("requestTimeEpoch", now.toInstant().toEpochMilli());
+ context.put("resourceId", scope.resource() != null ? scope.resource().getId() : "");
+ context.put("resourcePath", scope.resource() != null ? scope.resource().getPath() : "");
+ context.put("stage", scope.stageName());
+ context.put("status", status);
+
+ Map<String, Object> identity = new LinkedHashMap<>();
+ identity.put("sourceIp", "127.0.0.1");
+ identity.put("userAgent", scope.headers() != null ? scope.headers().getHeaderString("User-Agent") : null);
+ context.put("identity", identity);
+
+ String messageString;
+ try {
+ messageString = objectMapper.writeValueAsString(message);
+ } catch (IOException e) {
+ messageString = "null";
+ }
+ Map<String, Object> error = new LinkedHashMap<>();
+ error.put("message", message);
+ error.put("messageString", messageString);
+ error.put("responseType", type.name());
+ error.put("validationErrorString", validationError != null ? validationError : "");
+ context.put("error", error);
+ return context;
+ }
+
+ private static Map<String, String> gatewayRequestHeaders(HttpHeaders headers) {
+ Map<String, String> headerMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ if (headers == null || headers.getRequestHeaders() == null) {
+ return headerMap;
+ }
+ for (Map.Entry<String, List<String>> entry : headers.getRequestHeaders().entrySet()) {
+ if (entry.getValue() != null && !entry.getValue().isEmpty()) {
+ headerMap.put(entry.getKey(), entry.getValue().get(entry.getValue().size() - 1));
+ }
+ }
+ return headerMap;
+ }
+
+ private static Map<String, String> gatewayRequestQuery(UriInfo uriInfo) {
+ Map<String, String> queryMap = new HashMap<>();
+ if (uriInfo == null || uriInfo.getQueryParameters() == null) {
+ return queryMap;
+ }
+ for (Map.Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
+ if (entry.getValue() != null && !entry.getValue().isEmpty()) {
+ queryMap.put(entry.getKey(), entry.getValue().get(0));
+ }
+ }
+ return queryMap;
+ }
+
+ private Map<String, String> gatewayRequestPathParams(GatewayResponseScope scope) {
+ Map<String, String> pathMap = new HashMap<>();
+ if (scope.resource() == null || scope.resource().getPath() == null) {
+ return pathMap;
+ }
+ pathMap.putAll(extractPathParams(scope.resource().getPath(), scope.path()));
+ pathMap.putAll(greedyPathParam(scope.resource().getPath(), scope.path()));
+ return pathMap;
+ }
+
private String jsonMessage(String message) {
return objectMapper.createObjectNode().put("message", message).toString();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index ec2579664e..210ad0d6c8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -31,6 +31,8 @@ import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
+import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
+import io.github.hectorvent.floci.services.apigateway.model.GatewayResponseType;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
@@ -64,6 +66,7 @@ public class ApiGatewayService {
private final StorageBackend<String, UsagePlan> usagePlanStore;
private final StorageBackend<String, UsagePlanKey> usagePlanKeyStore;
private final StorageBackend<String, RequestValidator> requestValidatorStore;
+ private final StorageBackend<String, GatewayResponse> gatewayResponseStore;
private final StorageBackend<String, Model> modelStore;
private final StorageBackend<String, Account> accountStore;
private final StorageBackend<String, CustomDomain> domainStore;
@@ -113,6 +116,9 @@ public class ApiGatewayService {
this.requestValidatorStore = storageFactory.create("apigateway", "apigateway-validators.json",
new TypeReference<>() {
});
+ this.gatewayResponseStore = storageFactory.create("apigateway", "apigateway-gatewayresponses.json",
+ new TypeReference<>() {
+ });
this.modelStore = storageFactory.create("apigateway", "apigateway-models.json",
new TypeReference<>() {
});
@@ -305,6 +311,7 @@ public class ApiGatewayService {
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
+ gatewayResponseStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(gatewayResponseStore::delete);
LOG.infov("Deleted REST API: {0} in {1}", apiId, region);
}
@@ -1212,6 +1219,234 @@ public class ApiGatewayService {
usagePlanKeyStore.delete(usagePlanKeyPathKey(region, usagePlanId, keyId));
}
+
+ // ──────────────────────────── Gateway Responses ────────────────────────────
+
+ private static final String GATEWAY_RESPONSE_HEADER_PREFIX = "gatewayresponse.header.";
+ private static final List<String> GATEWAY_RESPONSE_PARAMETER_SOURCES = List.of(
+ "method.request.header.", "method.request.querystring.", "method.request.path.",
+ "method.request.multivalueheader.", "method.request.multivaluequerystring.",
+ "context.", "stageVariables.");
+
+ /**
+ * {@code PutGatewayResponse}: an upsert keyed by response type. A {@code statusCode} left out
+ * is stored as null, so the type's own default keeps applying on the execute plane and is what
+ * {@code GetGatewayResponse} reports, exactly as AWS does.
+ */
+ public GatewayResponse putGatewayResponse(String region, String apiId, String responseType,
+ Map<String, Object> request) {
+ getRestApi(region, apiId);
+ GatewayResponseType type = requireGatewayResponseType(responseType);
+ Map<String, Object> body = request != null ? request : Map.of();
+
+ GatewayResponse response = new GatewayResponse();
+ response.setResponseType(type.name());
+ response.setStatusCode(validatedGatewayStatusCode(body.get("statusCode")));
+ response.setResponseParameters(validatedGatewayResponseParameters(stringMap(body.get("responseParameters"))));
+ response.setResponseTemplates(stringMap(body.get("responseTemplates")));
+ response.setDefaultResponse(false);
+
+ gatewayResponseStore.put(gatewayResponseKey(region, apiId, type), response);
+ LOG.infov("Put gateway response {0} for API {1}", type, apiId);
+ return response.copy();
+ }
+
+ /** The customised response, or the AWS default (flagged {@code defaultResponse}) when there is none. */
+ public GatewayResponse getGatewayResponse(String region, String apiId, String responseType) {
+ getRestApi(region, apiId);
+ GatewayResponseType type = requireGatewayResponseType(responseType);
+ return gatewayResponseStore.get(gatewayResponseKey(region, apiId, type))
+ .map(GatewayResponse::copy)
+ .orElseGet(() -> GatewayResponse.defaultFor(type));
+ }
+
+ /** Every type, as AWS lists them: customised ones as stored, the rest as their defaults. */
+ public List<GatewayResponse> getGatewayResponses(String region, String apiId) {
+ getRestApi(region, apiId);
+ List<GatewayResponse> responses = new ArrayList<>();
+ for (GatewayResponseType type : GatewayResponseType.values()) {
+ responses.add(gatewayResponseStore.get(gatewayResponseKey(region, apiId, type))
+ .map(GatewayResponse::copy)
+ .orElseGet(() -> GatewayResponse.defaultFor(type)));
+ }
+ return responses;
+ }
+
+ /** Removes the customisation so the type falls back to its default. */
+ public void deleteGatewayResponse(String region, String apiId, String responseType) {
+ getRestApi(region, apiId);
+ GatewayResponseType type = requireGatewayResponseType(responseType);
+ String key = gatewayResponseKey(region, apiId, type);
+ if (gatewayResponseStore.get(key).isEmpty()) {
+ throw new AwsException("NotFoundException", "Gateway response not found", 404);
+ }
+ gatewayResponseStore.delete(key);
+ }
+
+ /**
+ * {@code UpdateGatewayResponse}. Paths are {@code /statusCode},
+ * {@code /responseParameters/<name>} and {@code /responseTemplates/<content-type>}, the latter
+ * with JSON-pointer escaping ({@code application~1json}). Patching a type that has no
+ * customisation yet starts from its default, as on AWS.
+ */
+ public GatewayResponse updateGatewayResponse(String region, String apiId, String responseType,
+ List<Map<String, String>> patchOperations) {
+ getRestApi(region, apiId);
+ GatewayResponseType type = requireGatewayResponseType(responseType);
+ if (patchOperations == null) {
+ throw new AwsException("BadRequestException", "Invalid patch operation", 400);
+ }
+ String key = gatewayResponseKey(region, apiId, type);
+ GatewayResponse updated = gatewayResponseStore.get(key)
+ .map(GatewayResponse::copy)
+ .orElseGet(() -> GatewayResponse.defaultFor(type));
+
+ for (Map<String, String> operation : patchOperations) {
+ if (operation == null) {
+ throw new AwsException("BadRequestException", "Invalid patch operation", 400);
+ }
+ String op = operation.get("op");
+ String path = operation.get("path");
+ String value = operation.get("value");
+ if (op == null || path == null) {
+ throw new AwsException("BadRequestException", "Invalid patch operation", 400);
+ }
+ boolean remove = "remove".equals(op);
+ if (!remove && !"add".equals(op) && !"replace".equals(op)) {
+ throw new AwsException("BadRequestException",
+ "Invalid patch operation '" + op + "'. Must be one of: add, remove, replace", 400);
+ }
+ if (!remove && value == null) {
+ throw new AwsException("BadRequestException", "Invalid patch operation", 400);
+ }
+
+ if ("/statusCode".equals(path)) {
+ updated.setStatusCode(remove ? null : validatedGatewayStatusCode(value));
+ } else if (path.startsWith("/responseParameters/")) {
+ String name = unescapeJsonPointer(path.substring("/responseParameters/".length()));
+ if (remove) {
+ updated.getResponseParameters().remove(name);
+ } else {
+ validatedGatewayResponseParameters(Map.of(name, value));
+ updated.getResponseParameters().put(name, value);
+ }
+ } else if (path.startsWith("/responseTemplates/")) {
+ String contentType = unescapeJsonPointer(path.substring("/responseTemplates/".length()));
+ if (remove) {
+ updated.getResponseTemplates().remove(contentType);
+ } else {
+ updated.getResponseTemplates().put(contentType, value);
+ }
+ } else {
+ throw new AwsException("BadRequestException", "Invalid patch path '" + path + "'", 400);
+ }
+ }
+
+ updated.setDefaultResponse(false);
+ gatewayResponseStore.put(key, updated);
+ return updated.copy();
+ }
+
+ /**
+ * The customisation the execute plane applies for a gateway-generated error: the type's own
+ * when it has one, otherwise the DEFAULT_4XX / DEFAULT_5XX of its class, otherwise null so the
+ * caller answers exactly as it did before gateway responses existed.
+ */
+ public GatewayResponse resolveGatewayResponse(String region, String apiId, GatewayResponseType type,
+ int statusCode) {
+ Optional<GatewayResponse> specific = gatewayResponseStore.get(gatewayResponseKey(region, apiId, type));
+ if (specific.isPresent()) {
+ return specific.get().copy();
+ }
+ if (type.isDefaultType()) {
+ return null;
+ }
+ return gatewayResponseStore.get(gatewayResponseKey(region, apiId, type.fallback(statusCode)))
+ .map(GatewayResponse::copy)
+ .orElse(null);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void importGatewayResponses(String region, String apiId, Object extension) {
+ if (!(extension instanceof Map<?, ?> definitions)) {
+ return;
+ }
+ for (Map.Entry<?, ?> entry : definitions.entrySet()) {
+ String responseType = String.valueOf(entry.getKey());
+ Map<String, Object> definition = entry.getValue() instanceof Map<?, ?> map
+ ? (Map<String, Object>) map
+ : Map.of();
+ Map<String, Object> request = new HashMap<>();
+ if (definition.get("statusCode") != null) {
+ request.put("statusCode", String.valueOf(definition.get("statusCode")));
+ }
+ request.put("responseParameters", definition.get("responseParameters"));
+ request.put("responseTemplates", definition.get("responseTemplates"));
+ putGatewayResponse(region, apiId, responseType, request);
+ }
+ }
+
+ private static GatewayResponseType requireGatewayResponseType(String responseType) {
+ return GatewayResponseType.fromName(responseType)
+ .orElseThrow(() -> new AwsException("BadRequestException",
+ "Invalid Gateway response type specified: " + responseType, 400));
+ }
+
+ private static String validatedGatewayStatusCode(Object statusCode) {
+ if (statusCode == null) {
+ return null;
+ }
+ String value = String.valueOf(statusCode);
+ if (!value.matches("[1-5]\\d\\d")) {
+ throw new AwsException("BadRequestException", "Invalid status code specified: " + value, 400);
+ }
+ return value;
+ }
+
+ private static Map<String, String> validatedGatewayResponseParameters(Map<String, String> parameters) {
+ for (Map.Entry<String, String> entry : parameters.entrySet()) {
+ String destination = entry.getKey();
+ String source = entry.getValue();
+ if (!destination.startsWith(GATEWAY_RESPONSE_HEADER_PREFIX)
+ || destination.length() == GATEWAY_RESPONSE_HEADER_PREFIX.length()) {
+ throw new AwsException("BadRequestException",
+ "Invalid mapping expression specified: " + destination, 400);
+ }
+ if (!isValidGatewayResponseParameterSource(source)) {
+ throw new AwsException("BadRequestException",
+ "Invalid mapping expression specified: " + source, 400);
+ }
+ }
+ return parameters;
+ }
+
+ private static boolean isValidGatewayResponseParameterSource(String source) {
+ if (source == null) {
+ return false;
+ }
+ if (source.length() >= 2 && source.startsWith("'") && source.endsWith("'")) {
+ return true;
+ }
+ for (String prefix : GATEWAY_RESPONSE_PARAMETER_SOURCES) {
+ if (source.startsWith(prefix) && source.length() > prefix.length()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static Map<String, String> stringMap(Object value) {
+ Map<String, String> out = new LinkedHashMap<>();
+ if (value instanceof Map<?, ?> map) {
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ if (entry.getKey() != null && entry.getValue() != null) {
+ out.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
+ }
+ }
+ }
+ return out;
+ }
+
// ──────────────────────────── Request Validators ────────────────────────────
public RequestValidator createRequestValidator(String region, String apiId, Map<String, Object> request) {
@@ -2110,11 +2345,12 @@ public class ApiGatewayService {
resourceStore.put(resourceKey(region, apiId, root.getId()), root);
}
- // Clear existing models, validators, and authorizers before rebuilding them from the spec.
+ // Clear existing models, validators, authorizers and gateway responses before rebuilding them from the spec.
String prefix = region + "::" + apiId + "::";
modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
authorizerStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(authorizerStore::delete);
+ gatewayResponseStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(gatewayResponseStore::delete);
// Update API metadata from spec
if (openAPI.getInfo() != null) {
@@ -2363,6 +2599,8 @@ public class ApiGatewayService {
if (defaultValidator != null && validatorNameToId.containsKey(defaultValidator)) {
validatorNameToId.put("__default__", validatorNameToId.get(defaultValidator));
}
+
+ importGatewayResponses(region, apiId, topExtensions.get("x-amazon-apigateway-gateway-responses"));
}
// Import security schemes: create an Authorizer for each x-amazon-apigateway-authorizer scheme
@@ -2663,6 +2901,10 @@ public class ApiGatewayService {
return region + "::" + apiId + "::" + validatorId;
}
+ private String gatewayResponseKey(String region, String apiId, GatewayResponseType type) {
+ return region + "::" + apiId + "::" + type.name();
+ }
+
private String modelKey(String region, String apiId, String modelName) {
return region + "::" + apiId + "::" + modelName;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
index 94bc21fde7..621eb95b5f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
@@ -134,6 +134,11 @@ public class VtlTemplateEngine {
map.put("authorizer", ctx.authorizer());
}
+ if (ctx.gatewayResponseContext() != null) {
+ // A gateway response sees the full request context plus $context.error.
+ map.putAll(ctx.gatewayResponseContext());
+ }
+
map.put("responseOverride", responseOverride);
return map;
@@ -172,7 +177,10 @@ public class VtlTemplateEngine {
// ────────── Context variable classes ──────────
/**
- * Request context for VTL evaluation.
+ * Request context for VTL evaluation. {@code gatewayResponseContext} is only set while a
+ * gateway response template renders: its entries are merged into {@code $context}, which is
+ * how {@code $context.error} ({@code message}, {@code messageString}, {@code responseType},
+ * {@code validationErrorString}), {@code $context.path} and the other request fields reach it.
*/
public record VtlContext(
String body,
@@ -185,8 +193,24 @@ public class VtlTemplateEngine {
String requestId,
String accountId,
Map<String, String> stageVariables,
- Map<String, Object> authorizer
- ) {}
+ Map<String, Object> authorizer,
+ Map<String, Object> gatewayResponseContext
+ ) {
+ public VtlContext(String body,
+ Map<String, String> headers,
+ Map<String, String> queryParams,
+ Map<String, String> pathParams,
+ String stage,
+ String httpMethod,
+ String resourcePath,
+ String requestId,
+ String accountId,
+ Map<String, String> stageVariables,
+ Map<String, Object> authorizer) {
+ this(body, headers, queryParams, pathParams, stage, httpMethod, resourcePath, requestId, accountId,
+ stageVariables, authorizer, null);
+ }
+ }
/**
* The {@code $input} variable available in API Gateway VTL templates.
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/GatewayResponse.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/GatewayResponse.java
new file mode 100644
index 0000000000..0cd90ef508
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/GatewayResponse.java
@@ -0,0 +1,88 @@
+package io.github.hectorvent.floci.services.apigateway.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A REST API's customisation of one {@link GatewayResponseType}: the status code, the
+ * {@code gatewayresponse.header.*} parameter mappings and the body templates the gateway applies
+ * whenever it answers a request itself instead of the integration.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class GatewayResponse {
+
+ public static final String DEFAULT_TEMPLATE = "{\"message\":$context.error.messageString}";
+
+ private String responseType;
+ private String statusCode;
+ private Map<String, String> responseParameters = new LinkedHashMap<>();
+ private Map<String, String> responseTemplates = new LinkedHashMap<>();
+ private boolean defaultResponse;
+
+ public GatewayResponse() {
+ }
+
+ /** The response AWS reports for a type that has never been customised. */
+ public static GatewayResponse defaultFor(GatewayResponseType type) {
+ GatewayResponse response = new GatewayResponse();
+ response.setResponseType(type.name());
+ response.setStatusCode(type.defaultStatusCode() != null ? String.valueOf(type.defaultStatusCode()) : null);
+ response.getResponseTemplates().put("application/json", DEFAULT_TEMPLATE);
+ response.setDefaultResponse(true);
+ return response;
+ }
+
+ public GatewayResponse copy() {
+ GatewayResponse copy = new GatewayResponse();
+ copy.setResponseType(responseType);
+ copy.setStatusCode(statusCode);
+ copy.setResponseParameters(new LinkedHashMap<>(responseParameters));
+ copy.setResponseTemplates(new LinkedHashMap<>(responseTemplates));
+ copy.setDefaultResponse(defaultResponse);
+ return copy;
+ }
+
+ public String getResponseType() {
+ return responseType;
+ }
+
+ public void setResponseType(String responseType) {
+ this.responseType = responseType;
+ }
+
+ public String getStatusCode() {
+ return statusCode;
+ }
+
+ public void setStatusCode(String statusCode) {
+ this.statusCode = statusCode;
+ }
+
+ public Map<String, String> getResponseParameters() {
+ return responseParameters;
+ }
+
+ public void setResponseParameters(Map<String, String> responseParameters) {
+ this.responseParameters = responseParameters != null ? responseParameters : new LinkedHashMap<>();
+ }
+
+ public Map<String, String> getResponseTemplates() {
+ return responseTemplates;
+ }
+
+ public void setResponseTemplates(Map<String, String> responseTemplates) {
+ this.responseTemplates = responseTemplates != null ? responseTemplates : new LinkedHashMap<>();
+ }
+
+ public boolean isDefaultResponse() {
+ return defaultResponse;
+ }
+
+ public void setDefaultResponse(boolean defaultResponse) {
+ this.defaultResponse = defaultResponse;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/GatewayResponseType.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/GatewayResponseType.java
new file mode 100644
index 0000000000..c5e6959f23
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/GatewayResponseType.java
@@ -0,0 +1,68 @@
+package io.github.hectorvent.floci.services.apigateway.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.Optional;
+
+/**
+ * The gateway response types of a REST API, with the status code AWS assigns each one when it
+ * has not been customised. {@code DEFAULT_4XX} and {@code DEFAULT_5XX} carry no status of their
+ * own: they are the fallback for every type of their class that has no customisation.
+ */
+@RegisterForReflection
+public enum GatewayResponseType {
+ ACCESS_DENIED(403),
+ API_CONFIGURATION_ERROR(500),
+ AUTHORIZER_CONFIGURATION_ERROR(500),
+ AUTHORIZER_FAILURE(500),
+ BAD_REQUEST_PARAMETERS(400),
+ BAD_REQUEST_BODY(400),
+ DEFAULT_4XX(null),
+ DEFAULT_5XX(null),
+ EXPIRED_TOKEN(403),
+ INTEGRATION_FAILURE(504),
+ INTEGRATION_TIMEOUT(504),
+ INVALID_API_KEY(403),
+ INVALID_SIGNATURE(403),
+ MISSING_AUTHENTICATION_TOKEN(403),
+ QUOTA_EXCEEDED(429),
+ REQUEST_TOO_LARGE(413),
+ RESOURCE_NOT_FOUND(404),
+ THROTTLED(429),
+ UNAUTHORIZED(401),
+ UNSUPPORTED_MEDIA_TYPE(415),
+ WAF_FILTERED(403);
+
+ private final Integer defaultStatusCode;
+
+ GatewayResponseType(Integer defaultStatusCode) {
+ this.defaultStatusCode = defaultStatusCode;
+ }
+
+ /** The status AWS answers with when the type is not customised; null for the two DEFAULT_ types. */
+ public Integer defaultStatusCode() {
+ return defaultStatusCode;
+ }
+
+ public boolean isDefaultType() {
+ return defaultStatusCode == null;
+ }
+
+ /** The DEFAULT_ type that stands in for this one when it has no customisation of its own. */
+ public GatewayResponseType fallback(int statusCode) {
+ int status = defaultStatusCode != null ? defaultStatusCode : statusCode;
+ return status >= 500 ? DEFAULT_5XX : DEFAULT_4XX;
+ }
+
+ public static Optional<GatewayResponseType> fromName(String name) {
+ if (name == null) {
+ return Optional.empty();
+ }
+ for (GatewayResponseType type : values()) {
+ if (type.name().equals(name)) {
+ return Optional.of(type);
+ }
+ }
+ return Optional.empty();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayGatewayResponseCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayGatewayResponseCfnProvisioner.java
new file mode 100644
index 0000000000..a72f8fc712
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayGatewayResponseCfnProvisioner.java
@@ -0,0 +1,142 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::ApiGateway::GatewayResponse}, backed by
+ * {@link ApiGatewayService}.
+ *
+ * <p>A gateway response has no id of its own on the management plane: it is addressed by REST API
+ * and response type, and {@code PutGatewayResponse} is an upsert. {@code Ref} and
+ * {@code Fn::GetAtt Id} report {@code <restApiId>-<responseType>}, which is also what delete
+ * needs. StatusCode, ResponseParameters and ResponseTemplates update in place through a fresh put;
+ * RestApiId and ResponseType are createOnly, so a change to either is refused as a replacement
+ * rather than silently customising a different type under the old id.
+ */
+@ApplicationScoped
+public class ApiGatewayGatewayResponseCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(ApiGatewayGatewayResponseCfnProvisioner.class);
+
+ private static final String TYPE = "AWS::ApiGateway::GatewayResponse";
+ private static final String NOT_FOUND = "NotFoundException";
+ private static final String ID_SEPARATOR = "-";
+
+ private final ApiGatewayService apiGatewayService;
+
+ @Inject
+ public ApiGatewayGatewayResponseCfnProvisioner(ApiGatewayService apiGatewayService) {
+ this.apiGatewayService = apiGatewayService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String restApiId = blankToNull(ctx.resolveOptional(props, "RestApiId"));
+ String responseType = blankToNull(ctx.resolveOptional(props, "ResponseType"));
+ if (restApiId == null || responseType == null) {
+ throw new AwsException("ValidationError",
+ TYPE + " requires both RestApiId and ResponseType.", 400);
+ }
+
+ if (ctx.isUpdate()) {
+ String[] prior = splitId(ctx.priorPhysicalId());
+ if (prior != null) {
+ rejectIfChanged("RestApiId", prior[0], restApiId);
+ rejectIfChanged("ResponseType", prior[1], responseType);
+ }
+ }
+
+ Map<String, Object> request = new HashMap<>();
+ String statusCode = blankToNull(ctx.resolveOptional(props, "StatusCode"));
+ if (statusCode != null) {
+ request.put("statusCode", statusCode);
+ }
+ request.put("responseParameters", resolveStringMap(props, "ResponseParameters", ctx));
+ request.put("responseTemplates", resolveStringMap(props, "ResponseTemplates", ctx));
+ apiGatewayService.putGatewayResponse(ctx.region(), restApiId, responseType, request);
+ record(r, restApiId, responseType);
+ }
+
+ private static void record(StackResource r, String restApiId, String responseType) {
+ String id = restApiId + ID_SEPARATOR + responseType;
+ r.setPhysicalId(id);
+ r.getAttributes().put("Id", id);
+ }
+
+ /**
+ * {@code [restApiId, responseType]}, or null when the id is not in that shape. The response
+ * type never contains a dash, so the last one is the separator whatever the API id looks like.
+ */
+ private static String[] splitId(String physicalId) {
+ if (physicalId == null) {
+ return null;
+ }
+ int separator = physicalId.lastIndexOf(ID_SEPARATOR);
+ if (separator <= 0 || separator == physicalId.length() - 1) {
+ return null;
+ }
+ return new String[] {physicalId.substring(0, separator), physicalId.substring(separator + 1)};
+ }
+
+ private static Map<String, String> resolveStringMap(JsonNode props, String name, ProvisionContext ctx) {
+ Map<String, String> out = new LinkedHashMap<>();
+ if (props == null || !props.has(name) || props.get(name).isNull()) {
+ return out;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get(name));
+ if (resolved == null || !resolved.isObject()) {
+ return out;
+ }
+ resolved.fields().forEachRemaining(field -> {
+ String value = ctx.engine().resolve(field.getValue());
+ if (value != null) {
+ out.put(field.getKey(), value);
+ }
+ });
+ return out;
+ }
+
+ private static void rejectIfChanged(String property, String existing, String requested) {
+ if (!Objects.equals(blankToNull(existing), blankToNull(requested))) {
+ throw new AwsException("ValidationError",
+ "Updating " + property + " requires resource replacement, which is not supported.", 400);
+ }
+ }
+
+ private static String blankToNull(String value) {
+ return value == null || value.isBlank() ? null : value;
+ }
+
+ /** Without this the customisation outlives the stack and keeps shaping the API's errors. */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ String[] parts = splitId(physicalId);
+ if (parts == null) {
+ LOG.warnv("Gateway response {0} has no <restApiId>-<responseType> physical id, leaving it in place",
+ physicalId);
+ return;
+ }
+ CfnDeletes.safeDelete("gateway response", physicalId,
+ () -> apiGatewayService.deleteGatewayResponse(region, parts[0], parts[1]), NOT_FOUND);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGatewayResponseIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGatewayResponseIntegrationTest.java
new file mode 100644
index 0000000000..f3eb2ac7ee
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGatewayResponseIntegrationTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
index 5d98507c01..1ee6da07ce 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
@@ -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(
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayGatewayResponseCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayGatewayResponseCfnIntegrationTest.java
new file mode 100644
index 0000000000..1f67498e3c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayGatewayResponseCfnIntegrationTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 95e9be9a01..0c6f581615 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -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));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayGatewayResponseCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayGatewayResponseCfnProvisionerTest.java
new file mode 100644
index 0000000000..6dd65adb12
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayGatewayResponseCfnProvisionerTest.java
@@ -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());
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index d0e70a068c..f15d69ee10 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -4,6 +4,7 @@ AWS::ApiGateway::Authorizer LEGACY_SWITCH
AWS::ApiGateway::BasePathMapping ApiGatewayDomainCfnProvisioner
AWS::ApiGateway::Deployment LEGACY_SWITCH
AWS::ApiGateway::DomainName ApiGatewayDomainCfnProvisioner
+AWS::ApiGateway::GatewayResponse ApiGatewayGatewayResponseCfnProvisioner
AWS::ApiGateway::Method LEGACY_SWITCH
AWS::ApiGateway::Resource LEGACY_SWITCH
AWS::ApiGateway::RestApi LEGACY_SWITCH
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index 5ef89a8b7f..12c2e81138 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -91,7 +91,7 @@ type_order:
AWS::ElasticLoadBalancingV2: [LoadBalancer, TargetGroup, Listener, ListenerRule]
AWS::AutoScaling: [LaunchConfiguration, AutoScalingGroup, LifecycleHook]
AWS::Route53: [HostedZone, RecordSet]
- AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping]
+ AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping, GatewayResponse]
AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment]
AWS::AppSync: [GraphQLApi, GraphQLSchema, DataSource, FunctionConfiguration, Resolver, ApiKey]
AWS::CodePipeline: [Pipeline, CustomActionType, Webhook]