fix(apigateway): support SQS query-protocol integrations (path-style URI) (#1385)

* fix(apigateway): support SQS query-protocol integrations (path-style URI)

API Gateway → SQS AWS integrations use a path-style integration URI
(arn:aws:apigateway:{region}:sqs:path/{account}/{queue}) and a VTL request
template that renders the SQS query protocol (form-urlencoded,
"Action=SendMessage&QueueUrl=...&MessageBody=..."). This is the canonical AWS
recipe, also supported by LocalStack.

Two gaps blocked it:

- AwsServiceRouter.parseIntegrationUri only accepted the action/{Action} form
  and returned null for path/{resourcePath}, failing with "Cannot parse AWS
  integration URI" (500). It now also parses the path form, leaving the action
  null (the action comes from the rendered body).

- invokeAwsIntegration always parsed the rendered body as JSON and dispatched
  to the JSON handlers. For a path-style target it now parses the body as
  form-urlencoded and dispatches via the new AwsServiceRouter.invokeQuery,
  which routes to the existing SqsQueryHandler.

Also fixes request-template selection: AWS selects the template by the
incoming request Content-Type, but the integration.request.header.Content-Type
override (set to application/x-www-form-urlencoded for these integrations) was
clobbering it before selection, causing spurious 415s. The incoming
Content-Type is now captured before parameter mapping runs.

Closes #1384

* fix(apigateway): align MissingAction message with AwsQueryController and AWS

The MissingAction error message in invokeQuery drifted from the rest of
Floci and from AWS. AwsQueryController and real AWS use
"The request must contain the parameter Action" — match it exactly.
This commit is contained in:
Stas Burnashev authored and GitHub committed 2026-06-18 17:57:45 -05:00
1 parent a922d07e77
commit 31991ac5c3
3 files changed
+277 -14

No files matched your search

@@ -813,6 +813,13 @@ public class ApiGatewayExecuteController {
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, regionResolver.getAccountId(), null);
// AWS selects the request template by the *incoming* request Content-Type. Capture it
// before parameter mapping runs, since an integration.request.header.Content-Type
// override (common for SQS query-protocol integrations) would otherwise clobber it and
// misdirect template selection.
String incomingContentType = headerMap.getOrDefault("Content-Type",
headerMap.getOrDefault("content-type", "application/json"));
// Apply request parameter mapping (method.request.* → integration.request.*)
Map<String, String> integrationReqParams = integration.getRequestParameters();
if (integrationReqParams != null && !integrationReqParams.isEmpty()) {
@@ -835,8 +842,6 @@ public class ApiGatewayExecuteController {
// Content-Type negotiation and passthrough behavior
String transformedBody;
Map<String, String> requestTemplates = integration.getRequestTemplates();
String incomingContentType = headerMap.getOrDefault("Content-Type",
headerMap.getOrDefault("content-type", "application/json"));
if (requestTemplates != null && !requestTemplates.isEmpty()) {
// Try exact match first, then wildcard fallback
@@ -879,13 +884,23 @@ public class ApiGatewayExecuteController {
transformedBody = bodyStr != null ? bodyStr : "";
}
// Dispatch to service
// Dispatch to service.
//
// A path-style integration URI (arn:...:{service}:path/...) carries no action: the
// rendered template body is the AWS query protocol (form-urlencoded,
// "Action=SendMessage&..."). Action-style URIs (arn:...:{service}:action/{Action})
// carry the action in the URI and render a JSON body.
Response serviceResponse;
String errorType = null;
String errorMessage = null;
try {
JsonNode requestJson = objectMapper.readTree(transformedBody);
serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region);
if (target.action() == null) {
MultivaluedMap<String, String> formParams = parseFormUrlEncoded(transformedBody);
serviceResponse = serviceRouter.invokeQuery(target.service(), formParams, region);
} else {
JsonNode requestJson = objectMapper.readTree(transformedBody);
serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region);
}
} catch (AwsException e) {
errorType = e.getErrorCode();
errorMessage = e.getMessage();
@@ -1810,6 +1825,27 @@ public class ApiGatewayExecuteController {
return objectMapper.createObjectNode().put("message", message).toString();
}
/**
* Parses an {@code application/x-www-form-urlencoded} body into a {@link MultivaluedMap},
* matching the form parameters an AWS query-protocol handler expects. Both keys and values
* are URL-decoded. Parameters without a value (e.g. a bare {@code "Key"}) map to an empty string.
*/
private MultivaluedMap<String, String> parseFormUrlEncoded(String body) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
if (body == null || body.isEmpty()) {
return params;
}
for (String pair : body.split("&")) {
if (pair.isEmpty()) continue;
int eq = pair.indexOf('=');
String key = eq >= 0 ? pair.substring(0, eq) : pair;
String value = eq >= 0 ? pair.substring(eq + 1) : "";
params.add(URLDecoder.decode(key, StandardCharsets.UTF_8),
URLDecoder.decode(value, StandardCharsets.UTF_8));
}
return params;
}
// ──────────────────────────── Path matching ────────────────────────────
/**
@@ -13,10 +13,12 @@ import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
@@ -35,6 +37,7 @@ public class AwsServiceRouter {
private final StepFunctionsJsonHandler stepFunctionsHandler;
private final DynamoDbJsonHandler dynamoDbHandler;
private final SqsJsonHandler sqsHandler;
private final SqsQueryHandler sqsQueryHandler;
private final SnsJsonHandler snsHandler;
private final EventBridgeHandler eventBridgeHandler;
private final SsmJsonHandler ssmHandler;
@@ -50,6 +53,7 @@ public class AwsServiceRouter {
public AwsServiceRouter(StepFunctionsJsonHandler stepFunctionsHandler,
DynamoDbJsonHandler dynamoDbHandler,
SqsJsonHandler sqsHandler,
SqsQueryHandler sqsQueryHandler,
SnsJsonHandler snsHandler,
EventBridgeHandler eventBridgeHandler,
SsmJsonHandler ssmHandler,
@@ -63,6 +67,7 @@ public class AwsServiceRouter {
this.stepFunctionsHandler = stepFunctionsHandler;
this.dynamoDbHandler = dynamoDbHandler;
this.sqsHandler = sqsHandler;
this.sqsQueryHandler = sqsQueryHandler;
this.snsHandler = snsHandler;
this.eventBridgeHandler = eventBridgeHandler;
this.ssmHandler = ssmHandler;
@@ -81,8 +86,16 @@ public class AwsServiceRouter {
public record IntegrationTarget(String region, String service, String action) {}
/**
* Parses an integration URI like
* {@code arn:aws:apigateway:us-east-1:states:action/StartExecution}.
* Parses an integration URI in either of the two forms AWS accepts:
*
* <ul>
* <li><b>action</b> — {@code arn:aws:apigateway:{region}:{service}:action/{Action}}.
* The action is encoded in the URI and the request template renders a JSON body.</li>
* <li><b>path</b> — {@code arn:aws:apigateway:{region}:{service}:path/{resourcePath}}.
* The action is not in the URI; it is carried in the rendered request body
* (the AWS query protocol, e.g. {@code Action=SendMessage&...}). For this form
* {@link IntegrationTarget#action()} is {@code null}.</li>
* </ul>
*
* @return parsed target, or null if the URI format is not recognized
*/
@@ -90,20 +103,27 @@ public class AwsServiceRouter {
if (uri == null || !uri.startsWith("arn:aws:apigateway:")) {
return null;
}
// arn:aws:apigateway:{region}:{service}:action/{Action}
// arn:aws:apigateway:{region}:{service}:{action/{Action}|path/{resourcePath}}
String[] parts = uri.split(":");
if (parts.length < 6) {
return null;
}
String region = parts[3];
String service = parts[4];
// parts[5] should be "action/{ActionName}"
String actionPart = parts[5];
if (!actionPart.startsWith("action/")) {
return null;
// parts[5] is either "action/{ActionName}" or "path/{resourcePath}".
// A path may itself contain ':' (rare), so re-join the remainder.
String resourceSpec = parts.length > 6
? String.join(":", java.util.Arrays.copyOfRange(parts, 5, parts.length))
: parts[5];
if (resourceSpec.startsWith("action/")) {
String action = resourceSpec.substring("action/".length());
return new IntegrationTarget(region, service, action);
}
String action = actionPart.substring("action/".length());
return new IntegrationTarget(region, service, action);
if (resourceSpec.startsWith("path/")) {
// Action is supplied by the rendered request body (query protocol).
return new IntegrationTarget(region, service, null);
}
return null;
}
/**
@@ -143,4 +163,40 @@ public class AwsServiceRouter {
e.getMessage() != null ? e.getMessage() : "Service invocation failed", 500);
}
}
/**
* Dispatches an AWS query-protocol (form-encoded) integration request.
*
* <p>Used for {@code path/}-style integration URIs whose VTL request template renders an
* {@code application/x-www-form-urlencoded} body in the AWS query protocol, e.g.
* {@code Action=SendMessage&QueueUrl=...&MessageBody=...}. The {@code Action} parameter
* selects the operation, mirroring {@link io.github.hectorvent.floci.core.common.AwsQueryController}.
*
* @param service the AWS service name from the URI (e.g., "sqs")
* @param params the parsed form parameters, including {@code Action}
* @param region the AWS region
* @return the service response (query-protocol XML)
*/
public Response invokeQuery(String service, MultivaluedMap<String, String> params, String region) {
String action = params.getFirst("Action");
LOG.debugv("AWS query integration dispatch: {0}:{1} in {2}", service, action, region);
if (action == null || action.isBlank()) {
throw new AwsException("MissingAction",
"The request must contain the parameter Action", 400);
}
try {
return switch (service) {
case "sqs" -> sqsQueryHandler.handle(action, params, region);
default -> throw new AwsException("UnknownService",
"Unsupported AWS query-protocol service integration: " + service, 400);
};
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("InternalError",
e.getMessage() != null ? e.getMessage() : "Service invocation failed", 500);
}
}
}