From 8eaf5bf59cd67c70a15c11a85c8d3a353df79be3 Mon Sep 17 00:00:00 2001 From: Tyler Webb <85189637+T-Webb1@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:44:22 -0800 Subject: [PATCH] feat(apigatewayv2): support IntegrationSubtype and invoke SQS-SendMessage on HTTP APIs (#7969) CreateIntegration, UpdateIntegration, GetIntegration(s), OpenAPI import and AWS::ApiGatewayV2::Integration now carry IntegrationSubtype. A subtype is accepted only on an HTTP API AWS_PROXY integration with payload format 1.0 (the default when a subtype is set), and its RequestParameters must map every required member of the action and nothing it does not take. SQS-SendMessage is the supported subtype. The JSON 1.1 path keeps RequestParameters keys as sent, since subtype parameters are PascalCase member names. An HTTP API route whose AWS_PROXY integration has an IntegrationSubtype now runs that AWS service action instead of resolving a Lambda function from the integration URI. RequestParameters are mapped at invoke time: static values, whole expressions such as $request.body, $request.body., $request.header/querystring/path, $context and $stageVariables, and expressions embedded as ${request.header.X}. Region selects the action's region. A required parameter that maps to nothing answers 400 MissingParameter. The response is 200 with the action's result in the Response/Result envelope; an action error keeps its status. Lambda AWS_PROXY and HTTP_PROXY dispatch are unchanged. Every subtype AWS defines is now known, with its required and optional parameters from the AWS reference, so create and update validate all of them instead of rejecting the ones Floci does not invoke. Only SQS-SendMessage carries a service action. The subtype check is a package-private static method, and OpenAPI import and reimport run it over every x-amazon-apigateway-integration while planning, before any route or integration is deleted or created. $request.body. read a scalar through json-path as a JsonNode and threw ClassCastException, which escaped as a 500. The value is now read as an Object and converted, and resolution runs inside the dispatch error handling. MessageAttributes and MessageSystemAttributes are parsed as JSON templates first and expressions are resolved only inside their string values, so a header holding quotes or braces stays one literal string instead of adding attributes. Subtype parameters also resolve accountId, apiId, domainName, httpMethod, path, requestTime, requestTimeEpoch, routeKey and stage from $context. A subtype without a service action answers 500 at invoke. UpdateIntegration keeps a field the request leaves out, so an AWS::ApiGatewayV2::Integration update that drops IntegrationSubtype kept the old one. The provisioner now clears it explicitly, records the prior subtype in the rollback snapshot and restores it when the update fails. A number or boolean value is read as its text, and an object or array value is a 400 BadRequestException instead of an unchecked conversion error. Adds invoke cases for $request.body., a header that tries to break out of its MessageAttributes value, and $context variables; a stored-but-not-invoked SQS-PurgeQueue integration; a reimport with an invalid subtype that leaves the API unchanged; and number and object RequestParameters values on the JSON protocol. Queue creation now sits inside the cleanup block. A MessageAttributes or MessageSystemAttributes value that does not parse as a JSON object was interpolated as raw text, so a request value could add or change members of the attributes object. It is now an InvalidParameterValue 400; whole source expressions such as $request.body.attributes or ${request.body.attributes} still resolve as before. - A required parameter mapped to null or a blank string is rejected like a missing one. - A MessageAttributes or MessageSystemAttributes value must be a JSON object or a source expression. - Number and boolean RequestParameters values sent to the REST endpoints are read as text, and object or array values are a 400 instead of a ClassCastException. - UpdateIntegration that adds a subtype to an integration without one, and sends no PayloadFormatVersion, stores 1.0 as CreateIntegration does. - The create, update and OpenAPI import paths share one payload format default. - $context.requestId is the request's gateway id, honouring a valid x-amzn-RequestId override, instead of a fresh UUID. - $context.domainName is the Host the request arrived on, falling back to the execute-api host, and $context.domainPrefix, extendedRequestId and protocol resolve. - $context.path carries the stage prefix for a named stage, as HTTP API authorizer identity sources do. - An integration without a Region parameter calls the service in the API's region, or the default region when the request carried none. An x-amazon-apigateway-integration in an AWS::ApiGatewayV2::Api Body dropped integrationSubtype and requestParameters, so the API was created with a plain AWS_PROXY integration that never reached the service action. Both are now passed to CreateIntegration, which validates them as it does for every other caller. The PayloadFormatVersion default for AWS::ApiGatewayV2::Integration uses the shared helper. The rollback snapshot restored the subtype only when the integration had one, so a failed update that added a subtype left it in place. The snapshot's subtype is now restored as recorded, null included, and a subtype change no longer marks the update as one whose other fields cannot be rolled back. The template reader now fails on trailing tokens, so a value such as {"a":1} trailing no longer passes CreateIntegration and then has its tail dropped. The call-time check on a resolved JSON parameter uses the same reader instead of the application ObjectMapper, so create and invoke accept the same values. A parameter value starting with $ was taken as an expression even when it named no source, such as "$5 off" or the typo $request.heder.x, so it passed CreateIntegration and resolved to nothing on every call. CreateIntegration, UpdateIntegration and OpenAPI import now answer it with a BadRequestException. The accepted sources are $request.header., $request.querystring., $request.path., $request.body and $request.body., $context. and $stageVariables., checked for a whole-value expression, each embedded ${...} expression, and the string values of a JSON parameter's object. A $ elsewhere in a value stays static text, so mixed templates are unchanged. UpdateIntegration replaced RequestParameters wholesale, so an update that set one optional parameter on an SQS-SendMessage integration dropped QueueUrl and MessageBody and then failed the required-parameter check. AWS merges: a named key is added or replaced, a key sent as an empty string is removed, and an omitted key is kept. The merge applies to every HTTP API integration, and the subtype check runs on the merged map. The AWS::ApiGatewayV2::Api Body path passed requestParameters through as objects, so an object-valued MessageAttributes was rejected as not a string. It now reads every value with the importer's own conversion: a number or boolean as its text, and an object or array as its JSON text. A whitespace-only value is a valid SQS message body, and how API Gateway treats one is unmeasured, so create now applies the same isEmpty check invoke does instead of rejecting blank values. ApiGatewayV2Service.stringParameters already reads number and boolean values as text and rejects object and array values, so the handler no longer converts them too. --- docs/services/api-gateway.md | 57 ++ .../apigateway/ApiGatewayController.java | 3 + .../ApiGatewayExecuteController.java | 99 ++++ .../apigatewayv2/ApiGatewayV2JsonHandler.java | 24 +- .../ApiGatewayV2OpenApiImporter.java | 51 +- .../apigatewayv2/ApiGatewayV2Service.java | 165 +++++- .../apigatewayv2/model/Integration.java | 5 + .../model/IntegrationSubtype.java | 108 ++++ .../proxy/AwsServiceIntegrationMapper.java | 323 +++++++++++ .../ApiGatewayV2CfnProvisioner.java | 31 +- ...atewayV2SqsSendMessageIntegrationTest.java | 521 ++++++++++++++++++ .../ApiGatewayV2CfnProvisionerTest.java | 30 + ...yV2IntegrationSettingsIntegrationTest.java | 20 + .../cloudformation/writable-property-gaps.tsv | 1 - 14 files changed, 1414 insertions(+), 24 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/apigatewayv2/model/IntegrationSubtype.java create mode 100644 src/main/java/io/floci/aws/services/apigatewayv2/proxy/AwsServiceIntegrationMapper.java create mode 100644 src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2SqsSendMessageIntegrationTest.java diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index d47a88a066..62f7edb8fd 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -838,6 +838,63 @@ authorizer's context into request headers, query strings, and paths. For a retur `requestParameters`. String, numeric, and boolean context values are rendered as text. This works with format `1.0` policy responses and format `2.0` simple responses. +HTTP API `AWS_PROXY` integrations accept every `integrationSubtype` AWS defines: +`EventBridge-PutEvents`, `SQS-SendMessage`, `SQS-ReceiveMessage`, `SQS-DeleteMessage`, +`SQS-PurgeQueue`, `AppConfig-GetConfiguration`, `Kinesis-PutRecord`, +`StepFunctions-StartExecution`, `StepFunctions-StartSyncExecution` and +`StepFunctions-StopExecution`. `requestParameters` name the action's inputs, and create, update +and OpenAPI import and reimport check them against that subtype's required and optional +parameters from the AWS reference. They reject a required parameter that is missing, null or +empty, any other parameter name, a JSON parameter such as `MessageAttributes` that is neither a +JSON object nor a whole expression, a name that is not a subtype, a subtype on a non-`AWS_PROXY` +integration or a WebSocket API, and a `payloadFormatVersion` other than `1.0`. `1.0` is the default +when a subtype is set, including on an update that adds a subtype to an integration that had none. +A number or boolean parameter value is stored as its text, and an object or array value is +rejected. `UpdateIntegration` merges `requestParameters` into the stored ones for every HTTP API +integration, as AWS does: a key it names is added or replaced, a key whose value is an empty string +is removed, and a key it leaves out is kept. The subtype check runs on the merged parameters, so an +update that sets only `DelaySeconds` keeps `QueueUrl` and `MessageBody`, and one that sets `QueueUrl` +to an empty string is rejected. Import and reimport check every integration in the document before changing anything, +so a rejected reimport leaves the API as it was. CloudFormation carries `IntegrationSubtype` and +`RequestParameters` from an `AWS::ApiGatewayV2::Integration` and from the +`x-amazon-apigateway-integration` extension of an `AWS::ApiGatewayV2::Api` `Body`. OpenAPI import +and a CloudFormation `Body` read a `requestParameters` value the same way: a number or boolean as +its text, and an object or array as its JSON text, so an object `MessageAttributes` is accepted and +an array one is rejected as not a JSON object. A CloudFormation +update that drops `IntegrationSubtype` removes it from the integration, and a failed update that +added one rolls back to an integration without it. + +Only `SQS-SendMessage` is invoked: each request is sent to an SQS queue instead of a Lambda +function. A request that reaches any other subtype answers `500` with +`{"message":"Internal Server Error"}`. For `SQS-SendMessage`, `QueueUrl` and `MessageBody` are +required, and `DelaySeconds`, `MessageAttributes`, `MessageDeduplicationId`, `MessageGroupId`, +`MessageSystemAttributes` and `Region` are optional. A value is a static string, a whole +expression, or text with expressions embedded as `${request.header.Authorization}`. The +expressions are `$request.body`, `$request.body.`, `$request.header.`, +`$request.querystring.`, `$request.path.`, `$stageVariables.`, and these +`$context` variables: `accountId`, `apiId`, `domainName`, `domainPrefix`, `extendedRequestId`, +`httpMethod`, `path`, `protocol`, `requestTime`, `requestTimeEpoch`, `routeKey`, `stage`, +`requestId`, `identity.sourceIp`, `authorizer.` and `authorizer.claims.`. `requestId` +and `domainName` are the values the rest of the gateway reports for the request, and `path` +starts with the stage name, as in `/test/send`, except on the `$default` stage. An expression +with any other source is rejected with `400 BadRequestException` on create, update and import, +including one embedded as `${...}` or inside a JSON parameter's string values. A `$` inside static +text without braces, as in `price $5`, stays literal. A `$context` variable outside the list +resolves to nothing, or to an empty string where it is embedded. `MessageAttributes` +and `MessageSystemAttributes` are JSON object templates: expressions are resolved only inside +their string values, so a header holding quotes or braces stays one string value and cannot add +attributes. This differs from AWS, which substitutes the raw text into the template before +parsing it: a value that is meant to add JSON structure becomes one string here. A JSON parameter +that is a whole expression and resolves to anything but a JSON object answers `400` with +`InvalidParameterValue`. `Region` selects the queue's region; when it is absent or resolves to an +empty string, the API's region is used. `QueueUrl` is sent as resolved, so a mapped value can +name any queue in the emulator. A sent message answers `200` with +`{"SendMessageResponse":{"ResponseMetadata":{"RequestId":...},"SendMessageResult":{...}}}`; a +required parameter that resolves to nothing, such as an empty body for `$request.body`, answers +`400` with `{"Error":{"Code":"MissingParameter",...}}` (a value of only whitespace is sent as it is, +since SQS accepts it), and an SQS error is relayed in the same +shape with its status. `credentialsArn` is stored but not enforced, as for every other integration. + A Lambda proxy integration's response is read as AWS reads it (measured): a function that raises, a format 1.0 result that is not an object with a `statusCode`, and a `statusCode` that is not a whole number from 100 to 599 (text that spells one, such as `"201"`, is taken) are answered `500` with diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java index 3a8bb742b6..44e462bcc6 100644 --- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java @@ -2866,6 +2866,9 @@ public class ApiGatewayController { ObjectNode node = objectMapper.createObjectNode(); node.put("integrationId", i.getIntegrationId()); node.put("integrationType", i.getIntegrationType()); + if (i.getIntegrationSubtype() != null) { + node.put("integrationSubtype", i.getIntegrationSubtype()); + } if (i.getConnectionType() != null) node.put("connectionType", i.getConnectionType()); if (i.getConnectionId() != null) node.put("connectionId", i.getConnectionId()); node.put("payloadFormatVersion", i.getPayloadFormatVersion()); diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java index bad9465fd1..aa4f25435f 100644 --- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java @@ -42,7 +42,9 @@ import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service; import io.floci.aws.services.apigatewayv2.JwtSignatureVerifier; import io.floci.aws.services.apigatewayv2.model.Api; import io.floci.aws.services.apigatewayv2.model.Authorizer; +import io.floci.aws.services.apigatewayv2.model.IntegrationSubtype; import io.floci.aws.services.apigatewayv2.model.Route; +import io.floci.aws.services.apigatewayv2.proxy.AwsServiceIntegrationMapper; import io.floci.aws.services.apigatewayv2.proxy.CloudMapInstanceResolver; import io.floci.aws.services.apigatewayv2.proxy.HttpApiForwardedHeaders; import io.floci.aws.services.apigatewayv2.websocket.ConnectionInfo; @@ -142,6 +144,7 @@ public class ApiGatewayExecuteController { private final RestLambdaAuthorizer restLambdaAuthorizer; private final AuthorizerPolicyEvaluator authorizerPolicyEvaluator; private final CloudMapInstanceResolver cloudMapInstanceResolver; + private final AwsServiceIntegrationMapper awsServiceIntegrationMapper; @Inject public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer, @@ -170,6 +173,7 @@ public class ApiGatewayExecuteController { .build(); this.vtlEngine = vtlEngine; this.serviceRouter = serviceRouter; + this.awsServiceIntegrationMapper = new AwsServiceIntegrationMapper(objectMapper); this.webSocketConnectionManager = webSocketConnectionManager; this.elbV2Service = elbV2Service; this.sqsQueryHandler = sqsQueryHandler; @@ -2915,6 +2919,11 @@ public class ApiGatewayExecuteController { apiId, stageName, jwtClaims, lambdaAuthorizerContext, region); } + if (integration.getIntegrationSubtype() != null && !integration.getIntegrationSubtype().isEmpty()) { + return dispatchAwsServiceV2(integration, route, httpMethod, path, headers, uriInfo, body, + apiId, stageName, stageVariables, jwtClaims, lambdaAuthorizerContext, region); + } + String functionName = functionNameFromUri(integration.getIntegrationUri()); if (functionName == null) { return Response.status(500) @@ -2948,6 +2957,96 @@ public class ApiGatewayExecuteController { } } + /** + * Runs an integration subtype's AWS service action with the request parameters mapped from the + * request, and answers 200 with the action's result, or the action's error and status. + */ + private Response dispatchAwsServiceV2(io.floci.aws.services.apigatewayv2.model.Integration integration, + Route route, String httpMethod, String path, + HttpHeaders headers, UriInfo uriInfo, byte[] body, + String apiId, String stageName, Map stageVariables, + Map jwtClaims, ObjectNode lambdaAuthorizerContext, + String region) { + IntegrationSubtype subtype = IntegrationSubtype.fromName(integration.getIntegrationSubtype()).orElse(null); + if (subtype == null || !subtype.isInvocable()) { + LOG.warnv("execute-api v2: integration subtype {0} is not implemented", + integration.getIntegrationSubtype()); + return httpApiError(500, "Internal Server Error"); + } + + Map requestHeaders = new LinkedHashMap<>(); + for (Map.Entry> e : headers.getRequestHeaders().entrySet()) { + if (!e.getValue().isEmpty()) { + requestHeaders.put(e.getKey(), String.join(",", e.getValue())); + } + } + Map queryParams = new LinkedHashMap<>(); + for (Map.Entry> e : uriInfo.getQueryParameters().entrySet()) { + if (!e.getValue().isEmpty()) { + queryParams.put(e.getKey(), String.join(",", e.getValue())); + } + } + Map pathParams = extractV2PathParams(route.getRouteKey(), path); + Map claims = jwtClaims != null ? Map.copyOf(jwtClaims) : Map.of(); + Map authorizerContext = lambdaAuthorizerContext == null + ? Map.of() : objectMapper.convertValue(lambdaAuthorizerContext, MAP_TYPE); + String requestId = routeContext.requestId(headers); + io.floci.aws.services.apigatewayv2.proxy.RequestContext ctx = + new io.floci.aws.services.apigatewayv2.proxy.RequestContext( + apiId, stageName, httpMethod, path, pathParams.getOrDefault("proxy", ""), + route.getRouteKey(), requestId, routeContext.sourceIp(), + requestHeaders, queryParams, pathParams, body, claims, authorizerContext); + + Instant requestTime = routeContext.requestTime(); + String hostRegion = region != null ? region : regionResolver.getDefaultRegion(); + String domain = restDomainName(apiId, hostRegion, headers); + Map contextVariables = new LinkedHashMap<>(); + contextVariables.put("accountId", regionResolver.getAccountId()); + contextVariables.put("apiId", apiId); + contextVariables.put("domainName", domain); + contextVariables.put("domainPrefix", domain.split("\\.")[0]); + contextVariables.put("extendedRequestId", routeContext.extendedRequestId()); + contextVariables.put("httpMethod", httpMethod); + contextVariables.put("path", ("$default".equals(stageName) ? "" : "/" + stageName) + path); + contextVariables.put("protocol", "HTTP/1.1"); + contextVariables.put("requestTime", GATEWAY_REQUEST_TIME.format(requestTime.atZone(ZoneOffset.UTC))); + contextVariables.put("requestTimeEpoch", Long.toString(requestTime.toEpochMilli())); + contextVariables.put("routeKey", route.getRouteKey()); + contextVariables.put("stage", stageName); + + LOG.debugv("execute-api v2: {0} {1}/{2}{3} → {4}", httpMethod, apiId, stageName, path, + subtype.subtypeName()); + + try { + Map parameters = awsServiceIntegrationMapper.resolveParameters(subtype, + integration.getRequestParameters(), ctx, stageVariables, contextVariables); + String serviceRegion = parameters.get(IntegrationSubtype.REGION_PARAMETER); + if (serviceRegion == null || serviceRegion.isEmpty()) { + serviceRegion = hostRegion; + } + ObjectNode actionRequest = awsServiceIntegrationMapper.actionRequest(subtype, parameters); + Response serviceResponse = serviceRouter.invoke(subtype.service(), subtype.action(), actionRequest, + serviceRegion); + Object entity = serviceResponse.getEntity(); + if (serviceResponse.getStatus() >= 300) { + String code = entity instanceof AwsErrorResponse error ? error.type() : "InternalFailure"; + String message = entity instanceof AwsErrorResponse error ? error.message() : null; + return awsServiceErrorV2(code, message, serviceResponse.getStatus(), requestId); + } + JsonNode result = entity instanceof JsonNode node ? node : objectMapper.valueToTree(entity); + return Response.ok(awsServiceIntegrationMapper.actionResponse(subtype, result, requestId).toString()) + .type(MediaType.APPLICATION_JSON).build(); + } catch (AwsException e) { + return awsServiceErrorV2(e.getErrorCode(), e.getMessage(), e.getHttpStatus(), requestId); + } + } + + private Response awsServiceErrorV2(String code, String message, int status, String requestId) { + return Response.status(status) + .entity(awsServiceIntegrationMapper.actionError(code, message, status, requestId).toString()) + .type(MediaType.APPLICATION_JSON).build(); + } + private final io.floci.aws.services.apigatewayv2.proxy.HttpProxyInvoker httpProxyInvoker = new io.floci.aws.services.apigatewayv2.proxy.HttpProxyInvoker(); diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2JsonHandler.java b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2JsonHandler.java index 47d3f6d9c2..b5addf95bb 100644 --- a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2JsonHandler.java +++ b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2JsonHandler.java @@ -240,9 +240,7 @@ public class ApiGatewayV2JsonHandler { private Response handleCreateIntegration(JsonNode request, String region) { String apiId = request.path("ApiId").asText(); - @SuppressWarnings("unchecked") - Map map = toLowerCamelCase(objectMapper.convertValue(request, Map.class)); - Integration integration = service.createIntegration(region, apiId, map); + Integration integration = service.createIntegration(region, apiId, integrationRequest(request)); return Response.status(201).entity(toIntegrationNode(integration).toString()).build(); } @@ -264,10 +262,23 @@ public class ApiGatewayV2JsonHandler { private Response handleUpdateIntegration(JsonNode request, String region) { String apiId = request.path("ApiId").asText(); String integrationId = request.path("IntegrationId").asText(); + Integration integration = service.updateIntegration(region, apiId, integrationId, integrationRequest(request)); + return Response.ok(toIntegrationNode(integration).toString()).build(); + } + + /** + * The integration request with lower-camel-case member names. RequestParameters keys keep + * their case, since an integration subtype's parameters are named by its action's members. + */ + private Map integrationRequest(JsonNode request) { @SuppressWarnings("unchecked") Map map = toLowerCamelCase(objectMapper.convertValue(request, Map.class)); - Integration integration = service.updateIntegration(region, apiId, integrationId, map); - return Response.ok(toIntegrationNode(integration).toString()).build(); + JsonNode requestParameters = request.get("RequestParameters"); + if (requestParameters != null && requestParameters.isObject()) { + map.put("requestParameters", + objectMapper.convertValue(requestParameters, new TypeReference>() {})); + } + return map; } // ──────────────────────────── Stage ──────────────────────────── @@ -640,6 +651,9 @@ public class ApiGatewayV2JsonHandler { ObjectNode node = objectMapper.createObjectNode(); node.put("IntegrationId", i.getIntegrationId()); node.put("IntegrationType", i.getIntegrationType()); + if (i.getIntegrationSubtype() != null) { + node.put("IntegrationSubtype", i.getIntegrationSubtype()); + } if (i.getConnectionType() != null) node.put("ConnectionType", i.getConnectionType()); if (i.getConnectionId() != null) node.put("ConnectionId", i.getConnectionId()); node.put("PayloadFormatVersion", i.getPayloadFormatVersion()); diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2OpenApiImporter.java b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2OpenApiImporter.java index 6e95b86ec4..f08273e90e 100644 --- a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2OpenApiImporter.java +++ b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2OpenApiImporter.java @@ -1,5 +1,7 @@ package io.floci.aws.services.apigatewayv2; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.services.apigatewayv2.model.Api; import io.floci.aws.services.apigatewayv2.model.Authorizer; @@ -19,6 +21,7 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -42,6 +45,7 @@ import java.util.stream.Collectors; public class ApiGatewayV2OpenApiImporter { private static final Logger LOG = Logger.getLogger(ApiGatewayV2OpenApiImporter.class); + private static final ObjectMapper MAP_VALUE_WRITER = new ObjectMapper(); private static final String EXT_INTEGRATION = "x-amazon-apigateway-integration"; private static final String EXT_AUTHORIZER = "x-amazon-apigateway-authorizer"; @@ -185,6 +189,7 @@ public class ApiGatewayV2OpenApiImporter { // rejected reimport leave the previous definition intact. List authorizerSpecs = authorizerSpecs(openAPI); collectUnresolvedSecurity(openAPI, authorizerSpecs, warnings); + validateIntegrationSubtypes(openAPI); if (failOnWarnings && !warnings.isEmpty()) { throw new AwsException("BadRequestException", @@ -659,6 +664,28 @@ public class ApiGatewayV2OpenApiImporter { // ──────────────────────────── Integrations ──────────────────────────── + /** + * Validates every integration's subtype as CreateIntegration will, while planning, so a document + * with an invalid subtype is rejected before an import or reimport changes anything. + */ + private static void validateIntegrationSubtypes(OpenAPI openAPI) { + forEachImportedOperation(openAPI, (method, path, operation) -> { + Map definition = extensionAsMap( + operation == null ? null : operation.getExtensions(), EXT_INTEGRATION); + if (definition == null) { + return; + } + Map request = toIntegrationRequest(definition); + String integrationSubtype = (String) request.get("integrationSubtype"); + @SuppressWarnings("unchecked") + Map requestParameters = (Map) request.get("requestParameters"); + ApiGatewayV2Service.validateIntegrationSubtype("HTTP", (String) request.get("integrationType"), + integrationSubtype, (String) request.getOrDefault("payloadFormatVersion", + ApiGatewayV2Service.defaultPayloadFormatVersion(integrationSubtype)), + requestParameters); + }); + } + private static Map toIntegrationRequest(Map definition) { Map request = new HashMap<>(); @@ -666,6 +693,7 @@ public class ApiGatewayV2OpenApiImporter { if (type != null) { request.put("integrationType", type.toUpperCase(Locale.ROOT)); } + putIfPresent(request, "integrationSubtype", stringValue(definition.get("integrationSubtype"))); putIfPresent(request, "credentialsArn", stringValue(definition.get("credentials"))); putIfPresent(request, "integrationUri", stringValue(definition.get("uri"))); putIfPresent(request, "integrationMethod", stringValue(definition.get("httpMethod"))); @@ -741,9 +769,28 @@ public class ApiGatewayV2OpenApiImporter { if (!(source.get(key) instanceof Map map) || map.isEmpty()) { return; } + target.put(key, stringValues(map)); + } + + /** + * The map with every value read as text the way an imported {@code x-amazon-apigateway-integration} + * reads it: a number or boolean as its text, and an object or array as its JSON text. + */ + public static Map stringValues(Map map) { Map copy = new LinkedHashMap<>(); - map.forEach((k, v) -> copy.put(String.valueOf(k), v == null ? null : String.valueOf(v))); - target.put(key, copy); + map.forEach((k, v) -> copy.put(String.valueOf(k), mapValue(v))); + return copy; + } + + private static String mapValue(Object value) { + if (!(value instanceof Map) && !(value instanceof Collection)) { + return value == null ? null : String.valueOf(value); + } + try { + return MAP_VALUE_WRITER.writeValueAsString(value); + } catch (JsonProcessingException e) { + return String.valueOf(value); + } } private static void copyStringList(Map source, Map target, String key) { diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java index 2b06cbf5a5..ef3fe09922 100644 --- a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java +++ b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java @@ -14,6 +14,7 @@ import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.core.storage.StorageOperations; import io.floci.aws.services.apigatewayv2.model.*; +import io.floci.aws.services.apigatewayv2.proxy.AwsServiceIntegrationMapper; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -749,14 +750,23 @@ public class ApiGatewayV2Service { // ──────────────────────────── Integration CRUD ──────────────────────────── public Integration createIntegration(String region, String apiId, Map request) { - getApi(region, apiId); + Api api = getApi(region, apiId); + String integrationSubtype = (String) request.get("integrationSubtype"); + String payloadFormatVersion = request.get("payloadFormatVersion") != null + ? (String) request.get("payloadFormatVersion") + : defaultPayloadFormatVersion(integrationSubtype); + Map requestParameters = stringParameters(request.get("requestParameters")); + validateIntegrationSubtype(api.getProtocolType(), (String) request.get("integrationType"), + integrationSubtype, payloadFormatVersion, requestParameters); + Integration integration = new Integration(); integration.setIntegrationId(shortId(8)); integration.setIntegrationType((String) request.get("integrationType")); + integration.setIntegrationSubtype(integrationSubtype); integration.setCredentialsArn((String) request.get("credentialsArn")); integration.setIntegrationUri((String) request.get("integrationUri")); integration.setConnectionType((String) request.get("connectionType")); - integration.setPayloadFormatVersion((String) request.getOrDefault("payloadFormatVersion", "2.0")); + integration.setPayloadFormatVersion(payloadFormatVersion); integration.setIntegrationMethod((String) request.get("integrationMethod")); integration.setTemplateSelectionExpression((String) request.get("templateSelectionExpression")); @@ -772,8 +782,6 @@ public class ApiGatewayV2Service { Map responseTemplates = (Map) request.get("responseTemplates"); integration.setResponseTemplates(responseTemplates); - @SuppressWarnings("unchecked") - Map requestParameters = (Map) request.get("requestParameters"); integration.setRequestParameters(requestParameters); integration.setConnectionId((String) request.get("connectionId")); @@ -808,6 +816,19 @@ public class ApiGatewayV2Service { public Integration updateIntegration(String region, String apiId, String integrationId, Map request) { Integration integration = getIntegration(region, apiId, integrationId); + Map requestParameters = mergedParameters(integration.getRequestParameters(), + stringParameters(request.get("requestParameters"))); + String payloadFormatVersion = (String) request.get("payloadFormatVersion"); + if (payloadFormatVersion == null) { + payloadFormatVersion = request.get("integrationSubtype") != null + && integration.getIntegrationSubtype() == null + ? defaultPayloadFormatVersion((String) request.get("integrationSubtype")) + : integration.getPayloadFormatVersion(); + } + validateIntegrationSubtype(getApi(region, apiId).getProtocolType(), + updatedValue(request, "integrationType", integration.getIntegrationType()), + updatedValue(request, "integrationSubtype", integration.getIntegrationSubtype()), + payloadFormatVersion, requestParameters); if (request.get("credentialsArn") != null) { integration.setCredentialsArn((String) request.get("credentialsArn")); @@ -815,15 +836,16 @@ public class ApiGatewayV2Service { if (request.containsKey("integrationType") && request.get("integrationType") != null) { integration.setIntegrationType((String) request.get("integrationType")); } + if (request.get("integrationSubtype") != null) { + integration.setIntegrationSubtype((String) request.get("integrationSubtype")); + } if (request.containsKey("integrationUri") && request.get("integrationUri") != null) { integration.setIntegrationUri((String) request.get("integrationUri")); } if (request.containsKey("connectionType") && request.get("connectionType") != null) { integration.setConnectionType((String) request.get("connectionType")); } - if (request.containsKey("payloadFormatVersion") && request.get("payloadFormatVersion") != null) { - integration.setPayloadFormatVersion((String) request.get("payloadFormatVersion")); - } + integration.setPayloadFormatVersion(payloadFormatVersion); if (request.containsKey("integrationMethod") && request.get("integrationMethod") != null) { integration.setIntegrationMethod((String) request.get("integrationMethod")); } @@ -843,11 +865,7 @@ public class ApiGatewayV2Service { Map responseTemplates = (Map) request.get("responseTemplates"); integration.setResponseTemplates(responseTemplates); } - if (request.containsKey("requestParameters") && request.get("requestParameters") != null) { - @SuppressWarnings("unchecked") - Map requestParameters = (Map) request.get("requestParameters"); - integration.setRequestParameters(requestParameters); - } + integration.setRequestParameters(requestParameters); if (request.containsKey("connectionId") && request.get("connectionId") != null) { integration.setConnectionId((String) request.get("connectionId")); } @@ -856,6 +874,129 @@ public class ApiGatewayV2Service { return integration; } + @SuppressWarnings("unchecked") + private static T updatedValue(Map request, String key, T stored) { + Object value = request.get(key); + return value != null ? (T) value : stored; + } + + /** + * The payload format version an integration gets when the request leaves it out: 1.0 for an + * integration with a subtype, which supports only 1.0, and 2.0 otherwise. + */ + public static String defaultPayloadFormatVersion(String integrationSubtype) { + return integrationSubtype != null ? "1.0" : "2.0"; + } + + /** + * The stored RequestParameters with the update's entries merged in, as UpdateIntegration applies + * them: an entry whose value is the empty string removes that key, and every other entry adds or + * replaces it. An update without RequestParameters keeps the stored map, and a merge that removes + * every key leaves none. + */ + private static Map mergedParameters(Map stored, Map update) { + if (update == null) { + return stored; + } + Map merged = stored != null ? new LinkedHashMap<>(stored) : new LinkedHashMap<>(); + update.forEach((key, value) -> { + if ("".equals(value)) { + merged.remove(key); + } else { + merged.put(key, value); + } + }); + return merged.isEmpty() ? null : merged; + } + + /** + * RequestParameters with every number or boolean value read as its text. An object or array + * value is a {@code BadRequestException}. + */ + private static Map stringParameters(Object requestParameters) { + if (!(requestParameters instanceof Map map)) { + return null; + } + Map parameters = new LinkedHashMap<>(); + map.forEach((key, value) -> { + if (value instanceof Map || value instanceof Collection) { + throw new AwsException("BadRequestException", + "RequestParameters value for " + key + " must be a string.", 400); + } + parameters.put(String.valueOf(key), value == null ? null : String.valueOf(value)); + }); + return parameters; + } + + /** + * Rejects an integration subtype the way CreateIntegration does: only on an HTTP API + * {@code AWS_PROXY} integration with payload format 1.0, a subtype AWS defines, every required + * parameter mapped to a non-empty value, every JSON parameter either a source expression or a + * JSON object, every source expression one the gateway reads, and no parameter the subtype's + * action does not take. OpenAPI import runs it over every integration before it changes anything. + */ + static void validateIntegrationSubtype(String protocolType, String integrationType, String integrationSubtype, + String payloadFormatVersion, Map requestParameters) { + if (integrationSubtype == null) { + return; + } + if ("WEBSOCKET".equals(protocolType)) { + throw new AwsException("BadRequestException", + "IntegrationSubtype is supported only for HTTP APIs.", 400); + } + if (!"AWS_PROXY".equals(integrationType)) { + throw new AwsException("BadRequestException", + "IntegrationSubtype is supported only for AWS_PROXY integrations.", 400); + } + IntegrationSubtype subtype = IntegrationSubtype.fromName(integrationSubtype) + .orElseThrow(() -> new AwsException("BadRequestException", + "Unsupported IntegrationSubtype: " + integrationSubtype, 400)); + if (!"1.0".equals(payloadFormatVersion)) { + throw new AwsException("BadRequestException", + "PayloadFormatVersion must be 1.0 for an integration with an IntegrationSubtype.", 400); + } + Map parameters = requestParameters != null ? requestParameters : Map.of(); + for (String required : subtype.requiredParameters()) { + String value = parameters.get(required); + if (value == null || value.isEmpty()) { + throw new AwsException("BadRequestException", + "Missing required parameter " + required + " for IntegrationSubtype " + + subtype.subtypeName() + ".", 400); + } + } + for (Map.Entry parameter : parameters.entrySet()) { + if (!subtype.accepts(parameter.getKey())) { + throw new AwsException("BadRequestException", + "Parameter " + parameter.getKey() + " is not supported for IntegrationSubtype " + + subtype.subtypeName() + ".", 400); + } + if (subtype.isJsonParameter(parameter.getKey()) + && !AwsServiceIntegrationMapper.isValidJsonParameter(parameter.getValue())) { + throw new AwsException("BadRequestException", + "Parameter " + parameter.getKey() + " must be a JSON object or a source expression.", 400); + } + String unsupported = AwsServiceIntegrationMapper.unsupportedExpression(parameter.getValue(), + subtype.isJsonParameter(parameter.getKey())); + if (unsupported != null) { + throw new AwsException("BadRequestException", + "Parameter " + parameter.getKey() + " has an unsupported source expression: " + + unsupported + ".", 400); + } + } + } + + /** + * Sets the integration subtype exactly as given, null included. UpdateIntegration keeps a field + * the request leaves out, so it cannot remove a subtype that CloudFormation dropped. + */ + public Integration replaceIntegrationSubtype(String region, String apiId, String integrationId, + String integrationSubtype) { + Integration integration = getIntegration(region, apiId, integrationId); + integration.setIntegrationSubtype(integrationSubtype); + integrationStore.put(integrationKey(region, apiId, integrationId), integration); + return integration; + } + /** * Sets the connection type and id exactly as given, null included. UpdateIntegration keeps a * field the request leaves out, so it cannot remove a connection that CloudFormation dropped. diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/model/Integration.java b/src/main/java/io/floci/aws/services/apigatewayv2/model/Integration.java index 829e0a9c03..00495cfbb5 100644 --- a/src/main/java/io/floci/aws/services/apigatewayv2/model/Integration.java +++ b/src/main/java/io/floci/aws/services/apigatewayv2/model/Integration.java @@ -10,6 +10,7 @@ import java.util.Map; public class Integration { private String integrationId; private String integrationType; // AWS_PROXY, HTTP_PROXY + private String integrationSubtype; private String connectionType; // INTERNET, VPC_LINK private String integrationUri; private String payloadFormatVersion; // 1.0, 2.0 @@ -33,6 +34,7 @@ public class Integration { this.credentialsArn = src.credentialsArn; this.integrationId = src.integrationId; this.integrationType = src.integrationType; + this.integrationSubtype = src.integrationSubtype; this.connectionType = src.connectionType; this.integrationUri = src.integrationUri; this.payloadFormatVersion = src.payloadFormatVersion; @@ -51,6 +53,9 @@ public class Integration { public String getIntegrationType() { return integrationType; } public void setIntegrationType(String integrationType) { this.integrationType = integrationType; } + public String getIntegrationSubtype() { return integrationSubtype; } + public void setIntegrationSubtype(String integrationSubtype) { this.integrationSubtype = integrationSubtype; } + public String getConnectionType() { return connectionType; } public void setConnectionType(String connectionType) { this.connectionType = connectionType; } diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/model/IntegrationSubtype.java b/src/main/java/io/floci/aws/services/apigatewayv2/model/IntegrationSubtype.java new file mode 100644 index 0000000000..221634c915 --- /dev/null +++ b/src/main/java/io/floci/aws/services/apigatewayv2/model/IntegrationSubtype.java @@ -0,0 +1,108 @@ +package io.floci.aws.services.apigatewayv2.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * An HTTP API {@code AWS_PROXY} integration that calls an AWS service action directly instead of + * a Lambda function. The request parameters name the action's input members: {@code required} + * must all be mapped, {@code optional} may be, and nothing else is accepted. {@code Region} is + * accepted by every subtype and selects the region the action runs in. + * + *

Every subtype AWS defines is known, so each is validated when an integration is created or + * updated. Only a subtype with a {@link #service()} is invoked; the others are stored and answer + * an error when a request reaches them. + */ +@RegisterForReflection +public enum IntegrationSubtype { + EVENTBRIDGE_PUT_EVENTS("EventBridge-PutEvents", + List.of("Detail", "DetailType", "Source"), + List.of("Time", "EventBusName", "Resources", "Region", "TraceHeader")), + SQS_SEND_MESSAGE("SQS-SendMessage", "sqs", "SendMessage", + List.of("QueueUrl", "MessageBody"), + List.of("DelaySeconds", "MessageAttributes", "MessageDeduplicationId", "MessageGroupId", + "MessageSystemAttributes", "Region"), + Set.of("DelaySeconds"), + Set.of("MessageAttributes", "MessageSystemAttributes"), + List.of("MD5OfMessageAttributes", "MD5OfMessageBody", "MD5OfMessageSystemAttributes", + "MessageId", "SequenceNumber")), + SQS_RECEIVE_MESSAGE("SQS-ReceiveMessage", + List.of("QueueUrl"), + List.of("AttributeNames", "MaxNumberOfMessages", "MessageAttributeNames", "ReceiveRequestAttemptId", + "VisibilityTimeout", "WaitTimeSeconds", "Region")), + SQS_DELETE_MESSAGE("SQS-DeleteMessage", + List.of("ReceiptHandle", "QueueUrl"), + List.of("Region")), + SQS_PURGE_QUEUE("SQS-PurgeQueue", + List.of("QueueUrl"), + List.of("Region")), + APPCONFIG_GET_CONFIGURATION("AppConfig-GetConfiguration", + List.of("Application", "Environment", "Configuration", "ClientId"), + List.of("ClientConfigurationVersion", "Region")), + KINESIS_PUT_RECORD("Kinesis-PutRecord", + List.of("StreamName", "Data", "PartitionKey"), + List.of("SequenceNumberForOrdering", "ExplicitHashKey", "Region")), + STEPFUNCTIONS_START_EXECUTION("StepFunctions-StartExecution", + List.of("StateMachineArn"), + List.of("Name", "Input", "Region")), + STEPFUNCTIONS_START_SYNC_EXECUTION("StepFunctions-StartSyncExecution", + List.of("StateMachineArn"), + List.of("Name", "Input", "Region", "TraceHeader")), + STEPFUNCTIONS_STOP_EXECUTION("StepFunctions-StopExecution", + List.of("ExecutionArn"), + List.of("Cause", "Error", "Region")); + + public static final String REGION_PARAMETER = "Region"; + + private final String subtypeName; + private final String service; + private final String action; + private final List requiredParameters; + private final List optionalParameters; + private final Set integerParameters; + private final Set jsonParameters; + private final List resultMembers; + + IntegrationSubtype(String subtypeName, List requiredParameters, List optionalParameters) { + this(subtypeName, null, null, requiredParameters, optionalParameters, Set.of(), Set.of(), List.of()); + } + + IntegrationSubtype(String subtypeName, String service, String action, List requiredParameters, + List optionalParameters, Set integerParameters, + Set jsonParameters, List resultMembers) { + this.subtypeName = subtypeName; + this.service = service; + this.action = action; + this.requiredParameters = requiredParameters; + this.optionalParameters = optionalParameters; + this.integerParameters = integerParameters; + this.jsonParameters = jsonParameters; + this.resultMembers = resultMembers; + } + + public static Optional fromName(String name) { + for (IntegrationSubtype subtype : values()) { + if (subtype.subtypeName.equals(name)) { + return Optional.of(subtype); + } + } + return Optional.empty(); + } + + public boolean accepts(String parameter) { + return requiredParameters.contains(parameter) || optionalParameters.contains(parameter); + } + + public boolean isInvocable() { return service != null; } + public String subtypeName() { return subtypeName; } + public String service() { return service; } + public String action() { return action; } + public List requiredParameters() { return requiredParameters; } + public List optionalParameters() { return optionalParameters; } + public boolean isIntegerParameter(String parameter) { return integerParameters.contains(parameter); } + public boolean isJsonParameter(String parameter) { return jsonParameters.contains(parameter); } + public List resultMembers() { return resultMembers; } +} diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/proxy/AwsServiceIntegrationMapper.java b/src/main/java/io/floci/aws/services/apigatewayv2/proxy/AwsServiceIntegrationMapper.java new file mode 100644 index 0000000000..8a9515bb58 --- /dev/null +++ b/src/main/java/io/floci/aws/services/apigatewayv2/proxy/AwsServiceIntegrationMapper.java @@ -0,0 +1,323 @@ +package io.floci.aws.services.apigatewayv2.proxy; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.JsonPathException; +import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; +import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.apigatewayv2.model.IntegrationSubtype; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Maps an HTTP API request onto the input of an {@link IntegrationSubtype}'s AWS service action, + * and the action's result onto the response API Gateway returns. + * + *

A parameter value is a static string, a whole source expression such as + * {@code $request.body}, or a string with source expressions embedded as {@code ${request.header.X}}. + * Beyond the sources {@link ContextValueResolver} reads, it resolves {@code $request.body}, + * {@code $request.body.}, {@code $stageVariables.} and the {@code $context.} + * values the caller supplies. An embedded expression that resolves to nothing is replaced by the + * empty string. + */ +public class AwsServiceIntegrationMapper { + + private static final Pattern EMBEDDED_EXPRESSION = Pattern.compile("\\$\\{([^}]+)}"); + private static final String BODY = "$request.body"; + private static final String STAGE_VARIABLES = "$stageVariables."; + private static final String CONTEXT = "$context."; + private static final List SOURCE_PREFIXES = List.of("$request.header.", "$request.querystring.", + "$request.path.", BODY + ".", CONTEXT, STAGE_VARIABLES); + private static final ObjectMapper TEMPLATE_READER = new ObjectMapper() + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private final ObjectMapper objectMapper; + private final Configuration jsonPathConfiguration; + private final ContextValueResolver contextValueResolver = new ContextValueResolver(); + + public AwsServiceIntegrationMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + this.jsonPathConfiguration = Configuration.builder() + .jsonProvider(new JacksonJsonNodeJsonProvider(objectMapper)) + .mappingProvider(new JacksonMappingProvider(objectMapper)) + .build(); + } + + /** + * Resolves every parameter value, keeping null for a source that is absent. A JSON parameter + * whose value is a JSON object is parsed before anything is resolved, and expressions are + * resolved only inside its string values, so a request value cannot add or change members. A + * JSON parameter that is neither a whole source expression nor a JSON object is an + * {@code InvalidParameterValue} error. {@code contextVariables} holds the + * {@code $context.} values of this request. + */ + public Map resolveParameters(IntegrationSubtype subtype, Map parameters, + RequestContext ctx, Map stageVariables, + Map contextVariables) { + Map resolved = new LinkedHashMap<>(); + if (parameters == null) { + return resolved; + } + Sources sources = new Sources(ctx, stageVariables, contextVariables); + parameters.forEach((name, value) -> { + if (!subtype.isJsonParameter(name) || value == null || isWholeExpression(value)) { + resolved.put(name, resolveValue(value, sources)); + return; + } + JsonNode template = jsonTemplate(value); + if (template == null) { + throw new AwsException("InvalidParameterValue", + "Value for parameter " + name + " is invalid. Reason: Must be a JSON object.", 400); + } + resolved.put(name, resolveLeaves(template, sources).toString()); + }); + return resolved; + } + + /** + * Whether a JSON parameter value can be mapped: absent, a whole source expression such as + * {@code $request.body.attributes} or {@code ${request.body.attributes}}, or a JSON object. + */ + public static boolean isValidJsonParameter(String value) { + return value == null || isWholeExpression(value) || jsonTemplate(value) != null; + } + + /** + * The first source expression in a parameter value that names no source the mapper reads, or null when there is + * none. A value starting with {@code $} is one whole expression, {@code ${...}} marks an embedded one, and a + * {@code $} anywhere else is static text. For a JSON parameter holding a JSON object, the expressions are those in + * its string values. + */ + public static String unsupportedExpression(String value, boolean jsonParameter) { + if (value == null) { + return null; + } + if (jsonParameter && !isWholeExpression(value)) { + JsonNode template = jsonTemplate(value); + return template == null ? null : unsupportedLeafExpression(template); + } + if (value.startsWith("$") && !value.startsWith("${")) { + return isSupportedSource(value) ? null : value; + } + Matcher m = EMBEDDED_EXPRESSION.matcher(value); + while (m.find()) { + String expression = "$" + m.group(1); + if (!isSupportedSource(expression)) { + return expression; + } + } + return null; + } + + private static String unsupportedLeafExpression(JsonNode node) { + if (node.isTextual()) { + return unsupportedExpression(node.asText(), false); + } + for (JsonNode child : node) { + String unsupported = unsupportedLeafExpression(child); + if (unsupported != null) { + return unsupported; + } + } + return null; + } + + private static boolean isSupportedSource(String expression) { + if (expression.equals(BODY)) { + return true; + } + for (String prefix : SOURCE_PREFIXES) { + if (expression.startsWith(prefix) && expression.length() > prefix.length()) { + return true; + } + } + return false; + } + + private static boolean isWholeExpression(String value) { + return (value.startsWith("$") && !value.startsWith("${")) + || EMBEDDED_EXPRESSION.matcher(value).matches(); + } + + private record Sources(RequestContext ctx, Map stageVariables, + Map contextVariables) {} + + private static JsonNode jsonTemplate(String value) { + try { + JsonNode node = TEMPLATE_READER.readTree(value); + return node != null && node.isObject() ? node : null; + } catch (JsonProcessingException e) { + return null; + } + } + + private JsonNode resolveLeaves(JsonNode node, Sources sources) { + if (node.isTextual()) { + String resolved = resolveValue(node.asText(), sources); + return TextNode.valueOf(resolved != null ? resolved : ""); + } + if (node.isObject()) { + ObjectNode copy = objectMapper.createObjectNode(); + node.properties().forEach(e -> copy.set(e.getKey(), resolveLeaves(e.getValue(), sources))); + return copy; + } + if (node.isArray()) { + ArrayNode copy = objectMapper.createArrayNode(); + node.forEach(element -> copy.add(resolveLeaves(element, sources))); + return copy; + } + return node; + } + + private String resolveValue(String value, Sources sources) { + if (value == null) { + return null; + } + if (value.startsWith("$") && !value.startsWith("${")) { + return resolveExpression(value, sources); + } + Matcher m = EMBEDDED_EXPRESSION.matcher(value); + StringBuilder out = new StringBuilder(); + while (m.find()) { + String resolved = resolveExpression("$" + m.group(1), sources); + m.appendReplacement(out, Matcher.quoteReplacement(resolved != null ? resolved : "")); + } + m.appendTail(out); + return out.toString(); + } + + private String resolveExpression(String expression, Sources sources) { + RequestContext ctx = sources.ctx(); + if (expression.equals(BODY)) { + return bodyText(ctx); + } + if (expression.startsWith(BODY + ".")) { + return bodyPath(ctx, expression.substring(BODY.length() + 1)); + } + if (expression.startsWith(STAGE_VARIABLES)) { + Map stageVariables = sources.stageVariables(); + return stageVariables == null ? null : stageVariables.get(expression.substring(STAGE_VARIABLES.length())); + } + if (expression.startsWith(CONTEXT) && sources.contextVariables() != null) { + String value = sources.contextVariables().get(expression.substring(CONTEXT.length())); + if (value != null) { + return value; + } + } + return contextValueResolver.resolve(expression, ctx); + } + + private static String bodyText(RequestContext ctx) { + return ctx.body() == null ? "" : new String(ctx.body(), StandardCharsets.UTF_8); + } + + private String bodyPath(RequestContext ctx, String path) { + String body = bodyText(ctx); + if (body.isBlank()) { + return null; + } + JsonNode value; + try { + Object read = JsonPath.using(jsonPathConfiguration).parse(body).read("$." + path); + value = read instanceof JsonNode node ? node : objectMapper.valueToTree(read); + } catch (JsonPathException | IllegalArgumentException | ClassCastException e) { + return null; + } + if (value == null || value.isNull() || value.isMissingNode()) { + return null; + } + return value.isValueNode() ? value.asText() : value.toString(); + } + + /** + * The action's JSON input from the resolved parameters. A required parameter that resolved to + * nothing is a {@code MissingParameter} error, an optional one is left out, and {@code Region} + * is not an input member. Integer members are sent as numbers when they read as one, and JSON + * members must hold a JSON object. + */ + public ObjectNode actionRequest(IntegrationSubtype subtype, Map resolved) { + for (String required : subtype.requiredParameters()) { + String value = resolved.get(required); + if (value == null || value.isEmpty()) { + throw new AwsException("MissingParameter", + "The request must contain the parameter " + required + ".", 400); + } + } + ObjectNode request = objectMapper.createObjectNode(); + resolved.forEach((name, value) -> { + if (value == null || value.isEmpty() || IntegrationSubtype.REGION_PARAMETER.equals(name)) { + return; + } + if (subtype.isIntegerParameter(name)) { + putInteger(request, name, value); + } else if (subtype.isJsonParameter(name)) { + request.set(name, jsonObject(name, value)); + } else { + request.put(name, value); + } + }); + return request; + } + + private static void putInteger(ObjectNode request, String name, String value) { + try { + request.put(name, Integer.parseInt(value.trim())); + } catch (NumberFormatException e) { + request.put(name, value); + } + } + + private static JsonNode jsonObject(String name, String value) { + JsonNode node = jsonTemplate(value); + if (node == null) { + throw new AwsException("InvalidParameterValue", + "Value for parameter " + name + " is invalid. Reason: Must be a JSON object.", 400); + } + return node; + } + + /** + * The action's result in the response envelope API Gateway returns for it: + * {@code {"Response":{"ResponseMetadata":{"RequestId":...},"Result":{...}}}}, + * every result member present and null when the action did not return it. + */ + public ObjectNode actionResponse(IntegrationSubtype subtype, JsonNode result, String requestId) { + ObjectNode root = objectMapper.createObjectNode(); + ObjectNode response = root.putObject(subtype.action() + "Response"); + response.putObject("ResponseMetadata").put("RequestId", requestId); + ObjectNode members = response.putObject(subtype.action() + "Result"); + for (String member : subtype.resultMembers()) { + JsonNode value = result == null ? null : result.get(member); + if (value == null || value.isNull()) { + members.putNull(member); + } else { + members.set(member, value); + } + } + return root; + } + + /** An action error in the shape API Gateway relays it. */ + public ObjectNode actionError(String code, String message, int status, String requestId) { + ObjectNode root = objectMapper.createObjectNode(); + ObjectNode error = root.putObject("Error"); + error.put("Code", code); + error.put("Message", message); + error.put("Type", status >= 500 ? "Receiver" : "Sender"); + root.put("RequestId", requestId); + return root; + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java index 3796f1f5ab..1ff1108cea 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java @@ -1,11 +1,13 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.apigatewayv2.ApiGatewayV2OpenApiImporter; import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service; import io.floci.aws.services.apigatewayv2.model.Api; import io.floci.aws.services.apigatewayv2.model.Authorizer; @@ -318,6 +320,15 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { "httpMethod"); putOpenApiIntegrationValue(integrationRequest, "payloadFormatVersion", integration, "payloadFormatVersion"); + putOpenApiIntegrationValue(integrationRequest, "integrationSubtype", integration, + "integrationSubtype"); + JsonNode requestParameters = integration.path("requestParameters"); + if (requestParameters.isObject() && !requestParameters.isEmpty()) { + integrationRequest.put("requestParameters", + ApiGatewayV2OpenApiImporter.stringValues( + objectMapper.convertValue(requestParameters, + new TypeReference>() {}))); + } Integration createdIntegration = apiGatewayV2Service.createIntegration(region, apiId, integrationRequest); integrationIds.add(createdIntegration.getIntegrationId()); @@ -881,9 +892,12 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { String region = ctx.region(); String apiId = ctx.resolveOptional(props, "ApiId"); Map req = new HashMap<>(); + String integrationSubtype = ctx.resolveOptional(props, "IntegrationSubtype"); req.put("integrationType", ctx.resolveOptional(props, "IntegrationType")); + req.put("integrationSubtype", integrationSubtype); req.put("integrationUri", ctx.resolveOptional(props, "IntegrationUri")); - req.put("payloadFormatVersion", ctx.resolveOrDefault(props, "PayloadFormatVersion", "2.0")); + req.put("payloadFormatVersion", ctx.resolveOrDefault(props, "PayloadFormatVersion", + ApiGatewayV2Service.defaultPayloadFormatVersion(integrationSubtype))); String connectionType = ctx.resolveOptional(props, "ConnectionType"); String connectionId = ctx.resolveOptional(props, "ConnectionId"); req.put("connectionType", connectionType); @@ -931,6 +945,9 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { (String) req.get("integrationMethod"), (String) req.get("templateSelectionExpression"), timeoutInMillis, requestParameters, requestTemplates); + if (integrationSubtype == null && prior.getIntegrationSubtype() != null) { + apiGatewayV2Service.replaceIntegrationSubtype(region, apiId, r.getPhysicalId(), null); + } integration = apiGatewayV2Service.updateIntegration(region, apiId, r.getPhysicalId(), req); } catch (RuntimeException failure) { // The stack skips rollbackUpdate for a resource whose own update failed, so undo it here. @@ -952,9 +969,9 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { } /** - * The connection and the five settings the integration had before this update, and whether the - * update also changes another field. UpdateIntegration keeps a field the request leaves out, so - * only a value that is set and differs counts as a change. + * The connection, the five settings and the subtype the integration had before this update, and + * whether the update also changes another field. UpdateIntegration keeps a field the request + * leaves out, so only a value that is set and differs counts as a change. */ private String integrationConnectionSnapshot(String region, String apiId, Integration prior, Map req) { @@ -971,6 +988,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { snapshot.put("timeoutInMillis", prior.getTimeoutInMillis()); snapshot.set("requestParameters", objectMapper.valueToTree(prior.getRequestParameters())); snapshot.set("requestTemplates", objectMapper.valueToTree(prior.getRequestTemplates())); + snapshot.put("integrationSubtype", prior.getIntegrationSubtype()); snapshot.put("otherFieldChanged", otherFieldChanged); return snapshot.toString(); } @@ -1005,6 +1023,11 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { textOrNull(snapshot, "integrationMethod"), textOrNull(snapshot, "templateSelectionExpression"), snapshot.path("timeoutInMillis").asInt(), stringMapOrNull(snapshot.path("requestParameters")), stringMapOrNull(snapshot.path("requestTemplates"))); + if (snapshot.has("integrationSubtype")) { + apiGatewayV2Service.replaceIntegrationSubtype(snapshot.path("region").asText(), + snapshot.path("apiId").asText(), resource.getPhysicalId(), + textOrNull(snapshot, "integrationSubtype")); + } // Spent only once the restore succeeded, so a restore that throws can be tried again. resource.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR); return !snapshot.path("otherFieldChanged").asBoolean(); diff --git a/src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2SqsSendMessageIntegrationTest.java b/src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2SqsSendMessageIntegrationTest.java new file mode 100644 index 0000000000..71a2c81d6f --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2SqsSendMessageIntegrationTest.java @@ -0,0 +1,521 @@ +package io.floci.aws.services.apigatewayv2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.http.apache5.Apache5HttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client; +import software.amazon.awssdk.services.apigatewayv2.model.BadRequestException; +import software.amazon.awssdk.services.apigatewayv2.model.CreateIntegrationResponse; +import software.amazon.awssdk.services.apigatewayv2.model.GetIntegrationResponse; +import software.amazon.awssdk.services.apigatewayv2.model.Route; +import software.amazon.awssdk.services.apigatewayv2.model.UpdateIntegrationResponse; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.Message; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +class ApiGatewayV2SqsSendMessageIntegrationTest { + private static final String SUBTYPE = "SQS-SendMessage"; + private static final String ROLE = "arn:aws:iam::000000000000:role/apigw-sqs"; + private static final String ATTRIBUTES = + "{\"Authorization\":{\"DataType\":\"String\",\"StringValue\":\"${request.header.Authorization}\"}}"; + + @Inject + ObjectMapper mapper; + + private ApiGatewayV2Client apigw() { + return AwsTestClients.create(ApiGatewayV2Client.builder(), "test", Region.US_EAST_1, + Apache5HttpClient.builder()); + } + + private SqsClient sqs() { + return AwsTestClients.create(SqsClient.builder(), "test", Region.US_EAST_1); + } + + private static Map parameters(String queueUrl) { + return Map.of("QueueUrl", queueUrl, "MessageBody", "$request.body", "DelaySeconds", "0", + "Region", "us-east-1", "MessageAttributes", ATTRIBUTES); + } + + @Test + void sdkIntegrationSubtypeSurvivesCreateGetAndUpdate() { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype").protocolType("HTTP")).apiId(); + try { + CreateIntegrationResponse created = client.createIntegration(b -> b.apiId(api) + .integrationType("AWS_PROXY").integrationSubtype(SUBTYPE).credentialsArn(ROLE) + .requestParameters(parameters("http://localhost/000000000000/round-trip"))); + assertEquals(SUBTYPE, created.integrationSubtype()); + assertEquals("1.0", created.payloadFormatVersion()); + assertEquals("$request.body", created.requestParameters().get("MessageBody")); + String id = created.integrationId(); + GetIntegrationResponse fetched = client.getIntegration(b -> b.apiId(api).integrationId(id)); + assertEquals(SUBTYPE, fetched.integrationSubtype()); + assertEquals(ATTRIBUTES, fetched.requestParameters().get("MessageAttributes")); + assertEquals(SUBTYPE, client.getIntegrations(b -> b.apiId(api)).items().getFirst() + .integrationSubtype()); + UpdateIntegrationResponse updated = client.updateIntegration(b -> b.apiId(api).integrationId(id) + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/other", + "MessageBody", "$request.body"))); + assertEquals(SUBTYPE, updated.integrationSubtype()); + assertEquals("http://localhost/000000000000/other", updated.requestParameters().get("QueueUrl")); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void updateMergesRequestParametersAndEmptyValueRemovesKey() { + String queueUrl = "http://localhost/000000000000/merge"; + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-merge").protocolType("HTTP")).apiId(); + try { + String id = client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE).requestParameters(parameters(queueUrl))).integrationId(); + + Map delayed = client.updateIntegration(b -> b.apiId(api).integrationId(id) + .requestParameters(Map.of("DelaySeconds", "5"))).requestParameters(); + assertEquals("5", delayed.get("DelaySeconds")); + assertEquals(queueUrl, delayed.get("QueueUrl")); + assertEquals("$request.body", delayed.get("MessageBody")); + assertEquals(ATTRIBUTES, delayed.get("MessageAttributes")); + + Map removed = client.updateIntegration(b -> b.apiId(api).integrationId(id) + .requestParameters(Map.of("MessageAttributes", ""))).requestParameters(); + assertFalse(removed.containsKey("MessageAttributes")); + assertEquals(queueUrl, removed.get("QueueUrl")); + assertEquals("5", removed.get("DelaySeconds")); + + BadRequestException missing = assertThrows(BadRequestException.class, () -> + client.updateIntegration(b -> b.apiId(api).integrationId(id) + .requestParameters(Map.of("QueueUrl", "")))); + assertThat(missing.getMessage(), containsString("QueueUrl")); + assertEquals(queueUrl, client.getIntegration(b -> b.apiId(api).integrationId(id)) + .requestParameters().get("QueueUrl")); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void jsonCompatibilityPathKeepsSubtypeAndParameterNames() throws Exception { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-json").protocolType("HTTP")).apiId(); + try { + JsonNode integration = json("CreateIntegration", Map.of("ApiId", api, + "IntegrationType", "AWS_PROXY", "IntegrationSubtype", SUBTYPE, + "RequestParameters", parameters("http://localhost/000000000000/json")), 201); + assertEquals(SUBTYPE, integration.path("IntegrationSubtype").asText()); + assertEquals("$request.body", integration.path("RequestParameters").path("MessageBody").asText()); + assertEquals("0", integration.path("RequestParameters").path("DelaySeconds").asText()); + + JsonNode numeric = json("CreateIntegration", Map.of("ApiId", api, + "IntegrationType", "AWS_PROXY", "IntegrationSubtype", SUBTYPE, + "RequestParameters", Map.of("QueueUrl", "http://localhost/000000000000/json", + "MessageBody", "$request.body", "DelaySeconds", 5)), 201); + assertEquals("5", numeric.path("RequestParameters").path("DelaySeconds").asText()); + + JsonNode nested = json("CreateIntegration", Map.of("ApiId", api, + "IntegrationType", "AWS_PROXY", "IntegrationSubtype", SUBTYPE, + "RequestParameters", Map.of("QueueUrl", "http://localhost/000000000000/json", + "MessageBody", Map.of("nested", "value"))), 400); + assertEquals("BadRequestException", nested.path("__type").asText()); + + Map nullQueue = new HashMap<>(); + nullQueue.put("QueueUrl", null); + nullQueue.put("MessageBody", "$request.body"); + JsonNode absent = json("CreateIntegration", Map.of("ApiId", api, + "IntegrationType", "AWS_PROXY", "IntegrationSubtype", SUBTYPE, + "RequestParameters", nullQueue), 400); + assertEquals("BadRequestException", absent.path("__type").asText()); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void createRejectsMissingRequiredParameter() { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-missing").protocolType("HTTP")).apiId(); + try { + BadRequestException missing = assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/q")))); + assertThat(missing.getMessage(), containsString("MessageBody")); + BadRequestException empty = assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/q", + "MessageBody", "")))); + assertThat(empty.getMessage(), containsString("MessageBody")); + assertEquals(" ", client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/q", + "MessageBody", " "))).requestParameters().get("MessageBody")); + BadRequestException malformed = assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/q", + "MessageBody", "$request.body", "MessageAttributes", "{not json")))); + assertThat(malformed.getMessage(), containsString("MessageAttributes")); + BadRequestException unknown = assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype("SQS-PurgeEverything") + .requestParameters(parameters("http://localhost/000000000000/q")))); + assertThat(unknown.getMessage(), containsString("SQS-PurgeEverything")); + assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("HTTP_PROXY") + .integrationUri("https://backend.example/items").integrationMethod("POST") + .integrationSubtype(SUBTYPE) + .requestParameters(parameters("http://localhost/000000000000/q")))); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void restPathReadsScalarParametersAsTextAndRejectsContainers() { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-rest").protocolType("HTTP")).apiId(); + try { + given().contentType(ContentType.JSON) + .body(""" + {"integrationType":"AWS_PROXY","integrationSubtype":"SQS-SendMessage", + "requestParameters":{"QueueUrl":"http://localhost/000000000000/rest", + "MessageBody":"$request.body","DelaySeconds":5}} + """) + .when().post("/v2/apis/" + api + "/integrations") + .then().statusCode(201) + .body("requestParameters.DelaySeconds", equalTo("5")); + given().contentType(ContentType.JSON) + .body(""" + {"integrationType":"AWS_PROXY","integrationSubtype":"SQS-SendMessage", + "requestParameters":{"QueueUrl":"http://localhost/000000000000/rest", + "MessageBody":{"nested":"value"}}} + """) + .when().post("/v2/apis/" + api + "/integrations") + .then().statusCode(400); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void createRejectsUnsupportedSourceExpressions() { + String queueUrl = "http://localhost/000000000000/expressions"; + List>> rejected = List.of( + Map.entry("$5 off", Map.of("QueueUrl", queueUrl, "MessageBody", "$5 off")), + Map.entry("$request.heder.x", Map.of("QueueUrl", queueUrl, "MessageBody", "$request.heder.x")), + Map.entry("$request.heder.x", Map.of("QueueUrl", queueUrl, "MessageBody", "id ${request.heder.x}")), + Map.entry("$request.heder.Authorization", Map.of("QueueUrl", queueUrl, + "MessageBody", "$request.body", "MessageAttributes", ATTRIBUTES.replace("header", "heder")))); + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-expressions").protocolType("HTTP")).apiId(); + try { + for (Map.Entry> entry : rejected) { + BadRequestException error = assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE).requestParameters(entry.getValue()))); + assertThat(error.getMessage(), containsString(entry.getKey())); + } + assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", queueUrl, "MessageBody", "$request.body", + "MessageAttributes", ATTRIBUTES + " {}")))); + CreateIntegrationResponse mixed = client.createIntegration(b -> b.apiId(api) + .integrationType("AWS_PROXY").integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", queueUrl, + "MessageBody", "price $5 for ${request.header.X-Item} on ${context.stage}"))); + assertEquals(SUBTYPE, mixed.integrationSubtype()); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void restPathTreatsNullPayloadFormatVersionAsAbsent() { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-null-version").protocolType("HTTP")).apiId(); + try { + String id = given().contentType(ContentType.JSON) + .body(""" + {"integrationType":"AWS_PROXY","integrationSubtype":"SQS-SendMessage", + "payloadFormatVersion":null, + "requestParameters":{"QueueUrl":"http://localhost/000000000000/rest", + "MessageBody":"$request.body"}} + """) + .when().post("/v2/apis/" + api + "/integrations") + .then().statusCode(201) + .body("payloadFormatVersion", equalTo("1.0")) + .extract().path("integrationId"); + given().contentType(ContentType.JSON) + .body("{\"payloadFormatVersion\":null}") + .when().patch("/v2/apis/" + api + "/integrations/" + id) + .then().statusCode(200) + .body("payloadFormatVersion", equalTo("1.0")); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void importReadsObjectValuedParameterAsJson() throws Exception { + String document = """ + {"openapi": "3.0.1", "info": {"title": "subtype-object-parameter", "version": "1.0"}, + "paths": {"/send": {"post": {"x-amazon-apigateway-integration": { + "type": "aws_proxy", "integrationSubtype": "SQS-SendMessage", + "payloadFormatVersion": "1.0", "credentials": "%s", + "requestParameters": {"QueueUrl": "http://localhost/000000000000/q", + "MessageBody": "$request.body", + "MessageAttributes": {"Authorization": {"DataType": "String", + "StringValue": "${request.header.Authorization}"}}}}}}}} + """.formatted(ROLE); + try (ApiGatewayV2Client client = apigw()) { + String api = client.importApi(b -> b.body(document)).apiId(); + try { + String attributes = client.getIntegrations(b -> b.apiId(api)).items().getFirst() + .requestParameters().get("MessageAttributes"); + assertEquals(mapper.readTree(ATTRIBUTES), mapper.readTree(attributes)); + assertThrows(BadRequestException.class, () -> client.reimportApi(b -> b.apiId(api) + .body(document.replace("\"MessageAttributes\": {", "\"MessageAttributes\": [{") + .replace("}}}}}}}}", "}}]}}}}}}")))); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void updateThatAddsSubtypeDefaultsPayloadFormatVersion() { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-subtype-add").protocolType("HTTP")).apiId(); + try { + String id = client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationUri("arn:aws:lambda:us-east-1:000000000000:function:target")).integrationId(); + UpdateIntegrationResponse updated = client.updateIntegration(b -> b.apiId(api).integrationId(id) + .integrationSubtype(SUBTYPE) + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/added", + "MessageBody", "$request.body"))); + assertEquals(SUBTYPE, updated.integrationSubtype()); + assertEquals("1.0", updated.payloadFormatVersion()); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void subtypeWithoutInvokerIsStoredAndAnswersServerError() { + try (ApiGatewayV2Client client = apigw()) { + String api = client.createApi(b -> b.name("sqs-purge").protocolType("HTTP")).apiId(); + try { + CreateIntegrationResponse created = client.createIntegration(b -> b.apiId(api) + .integrationType("AWS_PROXY").integrationSubtype("SQS-PurgeQueue") + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/purge"))); + assertEquals("SQS-PurgeQueue", created.integrationSubtype()); + assertThrows(BadRequestException.class, () -> + client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype("SQS-PurgeQueue") + .requestParameters(Map.of("QueueUrl", "http://localhost/000000000000/purge", + "MessageBody", "$request.body")))); + client.createRoute(b -> b.apiId(api).routeKey("POST /purge") + .target("integrations/" + created.integrationId())); + client.createStage(b -> b.apiId(api).stageName("test").autoDeploy(true)); + + given().post("/execute-api/" + api + "/test/purge") + .then().statusCode(500); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void reimportWithInvalidSubtypeLeavesApiUnchanged() { + String valid = """ + {"openapi": "3.0.1", "info": {"title": "subtype-reimport", "version": "1.0"}, + "paths": {"/items": {"get": {"x-amazon-apigateway-integration": { + "type": "http_proxy", "httpMethod": "GET", "uri": "https://backend.example/items", + "payloadFormatVersion": "1.0"}}}}} + """; + String invalid = """ + {"openapi": "3.0.1", "info": {"title": "subtype-reimport", "version": "1.0"}, + "paths": {"/send": {"post": {"x-amazon-apigateway-integration": { + "type": "aws_proxy", "integrationSubtype": "SQS-PurgeEverything", + "payloadFormatVersion": "1.0", + "requestParameters": {"QueueUrl": "http://localhost/000000000000/q"}}}}}} + """; + try (ApiGatewayV2Client client = apigw()) { + String api = client.importApi(b -> b.body(valid)).apiId(); + try { + assertThrows(BadRequestException.class, () -> client.reimportApi(b -> b.apiId(api).body(invalid))); + List routeKeys = client.getRoutes(b -> b.apiId(api)).items().stream() + .map(Route::routeKey).toList(); + assertEquals(List.of("GET /items"), routeKeys); + } finally { + client.deleteApi(b -> b.apiId(api)); + } + } + } + + @Test + void invokeSendsRequestBodyAndMappedHeaderAttributeToQueue() { + withSendMessageRoute("sqs-invoke", ApiGatewayV2SqsSendMessageIntegrationTest::parameters, + (sqs, queueUrl, api) -> { + given().contentType("application/json").header("Authorization", "Bearer token-123") + .body("{\"event\":\"created\"}") + .post("/execute-api/" + api + "/test/send") + .then().statusCode(200) + .body("SendMessageResponse.SendMessageResult.MessageId", notNullValue()) + .body("SendMessageResponse.ResponseMetadata.RequestId", notNullValue()); + + Message message = onlyMessage(sqs, queueUrl); + assertThat(message.body(), equalTo("{\"event\":\"created\"}")); + assertThat(message.messageAttributes().get("Authorization").stringValue(), + equalTo("Bearer token-123")); + }); + } + + @Test + void invokeWithEmptyBodyReturnsMissingParameter() { + withSendMessageRoute("sqs-invoke-empty", ApiGatewayV2SqsSendMessageIntegrationTest::parameters, + (sqs, queueUrl, api) -> { + given().post("/execute-api/" + api + "/test/send") + .then().statusCode(400) + .body("Error.Code", equalTo("MissingParameter")); + assertThat(sqs.receiveMessage(b -> b.queueUrl(queueUrl)).messages(), hasSize(0)); + }); + } + + @Test + void invokeSendsWhitespaceOnlyBody() { + withSendMessageRoute("sqs-invoke-blank", ApiGatewayV2SqsSendMessageIntegrationTest::parameters, + (sqs, queueUrl, api) -> { + given().contentType("text/plain").header("Authorization", "Bearer token-123").body(" ") + .post("/execute-api/" + api + "/test/send") + .then().statusCode(200); + assertThat(onlyMessage(sqs, queueUrl).body(), equalTo(" ")); + }); + } + + @Test + void invokeSendsBodyFieldSelectedByPath() { + withSendMessageRoute("sqs-invoke-path", + queueUrl -> Map.of("QueueUrl", queueUrl, "MessageBody", "$request.body.message"), + (sqs, queueUrl, api) -> { + given().contentType("application/json").body("{\"message\":\"hi\"}") + .post("/execute-api/" + api + "/test/send") + .then().statusCode(200); + assertThat(onlyMessage(sqs, queueUrl).body(), equalTo("hi")); + }); + } + + @Test + void invokeKeepsHeaderValueInsideItsAttribute() { + String header = "x\"},\"TenantId\":{\"DataType\":\"String\",\"StringValue\":\"evil"; + withSendMessageRoute("sqs-invoke-quoted", ApiGatewayV2SqsSendMessageIntegrationTest::parameters, + (sqs, queueUrl, api) -> { + given().contentType("application/json").header("Authorization", header).body("{}") + .post("/execute-api/" + api + "/test/send") + .then().statusCode(200); + Message message = onlyMessage(sqs, queueUrl); + assertThat(message.messageAttributes().get("Authorization").stringValue(), equalTo(header)); + assertFalse(message.messageAttributes().containsKey("TenantId")); + }); + } + + @Test + void invokeResolvesContextVariables() { + String attributes = "{\"Stage\":{\"DataType\":\"String\",\"StringValue\":\"${context.stage}\"}," + + "\"Route\":{\"DataType\":\"String\",\"StringValue\":\"${context.routeKey}\"}," + + "\"Path\":{\"DataType\":\"String\",\"StringValue\":\"${context.path}\"}}"; + withSendMessageRoute("sqs-invoke-context", + queueUrl -> Map.of("QueueUrl", queueUrl, "MessageBody", "$context.httpMethod", + "MessageAttributes", attributes), + (sqs, queueUrl, api) -> { + given().post("/execute-api/" + api + "/test/send").then().statusCode(200); + Message message = onlyMessage(sqs, queueUrl); + assertThat(message.body(), equalTo("POST")); + assertThat(message.messageAttributes().get("Stage").stringValue(), equalTo("test")); + assertThat(message.messageAttributes().get("Route").stringValue(), equalTo("POST /send")); + assertThat(message.messageAttributes().get("Path").stringValue(), equalTo("/test/send")); + }); + } + + private interface RouteCheck { + void run(SqsClient sqs, String queueUrl, String apiId); + } + + /** + * Creates a queue and an HTTP API whose {@code POST /send} route on stage {@code test} sends to it + * through an SQS-SendMessage integration, runs the check, then deletes both. + */ + private void withSendMessageRoute(String name, Function> parameters, + RouteCheck check) { + try (ApiGatewayV2Client client = apigw(); SqsClient sqs = sqs()) { + String api = client.createApi(b -> b.name(name).protocolType("HTTP")).apiId(); + String queueUrl = null; + try { + String createdQueue = sqs.createQueue(b -> b.queueName(name + "-" + UUID.randomUUID())).queueUrl(); + queueUrl = createdQueue; + String integration = client.createIntegration(b -> b.apiId(api).integrationType("AWS_PROXY") + .integrationSubtype(SUBTYPE).credentialsArn(ROLE) + .requestParameters(parameters.apply(createdQueue))).integrationId(); + client.createRoute(b -> b.apiId(api).routeKey("POST /send").target("integrations/" + integration)); + client.createStage(b -> b.apiId(api).stageName("test").autoDeploy(true)); + check.run(sqs, createdQueue, api); + } finally { + client.deleteApi(b -> b.apiId(api)); + if (queueUrl != null) { + String createdQueue = queueUrl; + sqs.deleteQueue(b -> b.queueUrl(createdQueue)); + } + } + } + } + + private static Message onlyMessage(SqsClient sqs, String queueUrl) { + List messages = sqs.receiveMessage(b -> b.queueUrl(queueUrl) + .messageAttributeNames("All").maxNumberOfMessages(10)).messages(); + assertThat(messages, hasSize(1)); + return messages.getFirst(); + } + + private JsonNode json(String action, Map body, int status) throws Exception { + String response = given().contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AmazonApiGatewayV2." + action) + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20261110/us-east-1/apigatewayv2/aws4_request") + .body(mapper.writeValueAsBytes(body)).post("/").then().statusCode(status).extract().asString(); + return mapper.readTree(response); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java index deeb90f683..4bfb755b92 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -364,6 +364,36 @@ class ApiGatewayV2CfnProvisionerTest { } } + @Test + void bodyMapsIntegrationSubtypeAndRequestParameters() throws Exception { + Integration integration = new Integration(); + integration.setIntegrationId("body-integration"); + when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(route("body-route", "POST /send")); + + StackResource resource = provision(body(""" + {"paths":{"/send":{"post":{ + "x-amazon-apigateway-integration":{"type":"aws_proxy", + "integrationSubtype":"SQS-SendMessage", + "credentials":"arn:aws:iam::000000000000:role/integration", + "payloadFormatVersion":"1.0", + "requestParameters":{"QueueUrl":"http://localhost/000000000000/q", + "MessageBody":"$request.body","DelaySeconds":5, + "MessageAttributes":{"Authorization":{"DataType":"String", + "StringValue":"${request.header.Authorization}"}}}}}}}} + """), null, Map.of()); + + assertEquals("CREATE_COMPLETE", resource.getStatus()); + verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID), argThat(request -> + "SQS-SendMessage".equals(request.get("integrationSubtype")) + && Map.of("QueueUrl", "http://localhost/000000000000/q", "MessageBody", "$request.body", + "DelaySeconds", "5", + "MessageAttributes", "{\"Authorization\":{\"DataType\":\"String\"," + + "\"StringValue\":\"${request.header.Authorization}\"}}") + .equals(request.get("requestParameters")))); + } + @Test void materializesInheritedJwtSecurityAndHonorsOperationOptOut() throws Exception { Authorizer authorizer = new Authorizer(); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java index 16a391faeb..a75598b457 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java @@ -41,6 +41,8 @@ class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest { private static final String PARAMETERS = ",\"RequestParameters\":{\"overwrite:header.x-example\":\"%s\"}"; private static final String TIMEOUT = ",\"TimeoutInMillis\":15000"; + private static final String SUBTYPE = ",\"IntegrationSubtype\":\"SQS-SendMessage\",\"RequestParameters\":{" + + "\"QueueUrl\":\"http://localhost/000000000000/q\",\"MessageBody\":\"$request.body\"}"; @Inject ApiGatewayV2Service apiGatewayV2Service; @@ -114,6 +116,20 @@ class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest { .body("requestParameters.'overwrite:header.x-example'", equalTo("original")); } + @Test + void failedUpdateRemovesTheSubtypeItAdded() { + String stackName = "integration-subtype-rollback-stack"; + stackAction("CreateStack", stackName, awsProxy(template("", ""))); + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE"); + + stackAction("UpdateStack", stackName, awsProxy(template(SUBTYPE, FAILING_RESOURCE))); + CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE"); + + Integration integration = integration(apiGatewayV2Service, stack(cloudFormationService, stackName)); + assertNull(integration.getIntegrationSubtype()); + assertNull(integration.getRequestParameters()); + } + @Test void stageVariablesTheTemplateDropsAreClearedFromTheStage() { String stackName = "stage-variables-drop-stack"; @@ -211,6 +227,10 @@ class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest { .then().statusCode(200); } + private static String awsProxy(String template) { + return template.replace("\"IntegrationType\":\"HTTP_PROXY\"", "\"IntegrationType\":\"AWS_PROXY\""); + } + /** * An HTTP API and an HTTP_PROXY integration to a plain URL, so no container starts. * {@code settings} adds integration properties and {@code extraResources} adds resources, both diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index dc0b4a8c08..976b54f3af 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -49,7 +49,6 @@ AWS::ApiGatewayV2::Deployment StageName accepted and ignored AWS::ApiGatewayV2::Integration ContentHandlingStrategy accepted and ignored AWS::ApiGatewayV2::Integration CredentialsArn accepted and ignored AWS::ApiGatewayV2::Integration Description accepted and ignored -AWS::ApiGatewayV2::Integration IntegrationSubtype accepted and ignored AWS::ApiGatewayV2::Integration PassthroughBehavior accepted and ignored AWS::ApiGatewayV2::Integration ResponseParameters accepted and ignored AWS::ApiGatewayV2::Integration TlsConfig accepted and ignored