mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat: use AWS-specific content type within the response of all JSON-based controllers (#240)
This commit is contained in:
1 parent
eeefb729c4
commit
b4afdbb842
29 files changed
+478
-420
No files matched your search
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;
|
||||
@@ -10,13 +12,10 @@ import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
|
||||
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -83,7 +82,7 @@ public class AwsJson11Controller {
|
||||
|
||||
@POST
|
||||
@Consumes("application/x-amz-json-1.1")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Produces("application/x-amz-json-1.1")
|
||||
public Response handle(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
@@ -127,10 +126,7 @@ public class AwsJson11Controller {
|
||||
prefix = ECS_TARGET_PREFIX;
|
||||
serviceName = "ECS";
|
||||
} else {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Unknown operation: " + target))
|
||||
.build();
|
||||
return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target);
|
||||
}
|
||||
|
||||
String action = target.substring(prefix.length());
|
||||
@@ -154,16 +150,11 @@ public class AwsJson11Controller {
|
||||
default -> null;
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.build();
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
} catch (Exception e) {
|
||||
LOG.errorf("Error processing %s request", serviceName, e);
|
||||
return Response.status(500)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse("InternalServerError", e.getMessage()))
|
||||
.build();
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Generic dispatcher for all AWS services that use the application/cbor protocol.
|
||||
* Routes requests to the appropriate service handler based on the X-Amz-Target header prefix.
|
||||
* <p>
|
||||
* Currently supported services:
|
||||
* - DynamoDB (DynamoDB_20120810.*)
|
||||
* - SQS (AmazonSQS.*)
|
||||
*/
|
||||
@Path("/")
|
||||
public class AwsJsonCborController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsJsonCborController.class);
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
|
||||
private static final String DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810.";
|
||||
private static final String DYNAMODB_STREAMS_TARGET_PREFIX = "DynamoDBStreams_20120810.";
|
||||
private static final String SQS_TARGET_PREFIX = "AmazonSQS.";
|
||||
private static final String SNS_TARGET_PREFIX = "SNS_20100331.";
|
||||
private static final String STEPFUNCTIONS_TARGET_PREFIX = "AWSStepFunctions.";
|
||||
private static final String CLOUDWATCH_TARGET_PREFIX = "GraniteServiceVersion20100801.";
|
||||
private static final String CLOUDWATCH_SERVICE_ID = "GraniteServiceVersion20100801";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
private final DynamoDbJsonHandler dynamoDbJsonHandler;
|
||||
private final DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler;
|
||||
private final SqsJsonHandler sqsJsonHandler;
|
||||
private final SnsJsonHandler snsJsonHandler;
|
||||
private final StepFunctionsJsonHandler sfnJsonHandler;
|
||||
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
|
||||
|
||||
@Inject
|
||||
public AwsJsonCborController(ObjectMapper objectMapper, RegionResolver regionResolver,
|
||||
DynamoDbJsonHandler dynamoDbJsonHandler,
|
||||
DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler,
|
||||
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
|
||||
StepFunctionsJsonHandler sfnJsonHandler,
|
||||
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.dynamoDbJsonHandler = dynamoDbJsonHandler;
|
||||
this.dynamoDbStreamsJsonHandler = dynamoDbStreamsJsonHandler;
|
||||
this.sqsJsonHandler = sqsJsonHandler;
|
||||
this.snsJsonHandler = snsJsonHandler;
|
||||
this.sfnJsonHandler = sfnJsonHandler;
|
||||
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Serializes a JsonNode to CBOR bytes, encoding fields named "Timestamp" with CBOR tag 1
|
||||
* as required by the smithy-rpc-v2-cbor protocol specification.
|
||||
*/
|
||||
private static byte[] nodeToSmithyCbor(JsonNode node) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
CBORFactory factory = (CBORFactory) CBOR_MAPPER.getFactory();
|
||||
try (CBORGenerator gen = factory.createGenerator(out)) {
|
||||
writeNodeToCbor(gen, node, null);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static void writeNodeToCbor(CBORGenerator gen, JsonNode node, String fieldName) throws Exception {
|
||||
if (node.isObject()) {
|
||||
gen.writeStartObject();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
gen.writeFieldName(entry.getKey());
|
||||
writeNodeToCbor(gen, entry.getValue(), entry.getKey());
|
||||
}
|
||||
gen.writeEndObject();
|
||||
} else if (node.isArray()) {
|
||||
gen.writeStartArray();
|
||||
for (JsonNode item : node) {
|
||||
writeNodeToCbor(gen, item, null);
|
||||
}
|
||||
gen.writeEndArray();
|
||||
} else if ("Timestamp".equals(fieldName) && node.isNumber()) {
|
||||
gen.writeTag(1);
|
||||
// Smithy rpc-v2-cbor timestamps are epoch seconds encoded as tagged floating-point numbers.
|
||||
gen.writeNumber(node.doubleValue());
|
||||
} else if (node.isTextual()) {
|
||||
gen.writeString(node.textValue());
|
||||
} else if (node.isDouble() || node.isFloat()) {
|
||||
gen.writeNumber(node.doubleValue());
|
||||
} else if (node.isLong() || node.isInt()) {
|
||||
gen.writeNumber(node.longValue());
|
||||
} else if (node.isBoolean()) {
|
||||
gen.writeBoolean(node.booleanValue());
|
||||
} else if (node.isNull()) {
|
||||
gen.writeNull();
|
||||
} else {
|
||||
gen.writeString(node.asText());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles AWS smithy-rpc-v2-cbor protocol requests.
|
||||
* AWS SDK v2 sends to POST /service/{sdkId}/operation/{op}
|
||||
* with Content-Type: application/cbor and no X-Amz-Target header.
|
||||
* Supported services: DynamoDB, SQS, SNS, StepFunctions, CloudWatch.
|
||||
*/
|
||||
@POST
|
||||
@Path("service/{serviceId}/operation/{operation}")
|
||||
@Consumes("application/cbor")
|
||||
@Produces("application/cbor")
|
||||
public Response handleSmithyRpcV2Cbor(
|
||||
@PathParam("serviceId") String serviceId,
|
||||
@PathParam("operation") String operation,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
byte[] body) {
|
||||
|
||||
LOG.debugv("Smithy RPC v2 CBOR: service={0}, operation={1}", serviceId, operation);
|
||||
|
||||
try {
|
||||
JsonNode request = (body != null && body.length > 0)
|
||||
? CBOR_MAPPER.readTree(body)
|
||||
: objectMapper.createObjectNode();
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = dispatchCbor(serviceId, operation, request, region);
|
||||
if (delegated == null) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
|
||||
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("Smithy-Protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return cborErrorResponse(e, "Smithy-Protocol");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing Smithy CBOR request: " + serviceId + "." + operation, e);
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles AWS services that migrated to the smithy-rpc-v2-cbor protocol at root path.
|
||||
* Fallback handler for X-Amz-Target based routing with CBOR body.
|
||||
*/
|
||||
@POST
|
||||
@Consumes("application/cbor")
|
||||
@Produces("application/cbor")
|
||||
public Response handleCborRequest(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
byte[] body) {
|
||||
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String prefix;
|
||||
String serviceName;
|
||||
|
||||
if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_STREAMS_TARGET_PREFIX;
|
||||
serviceName = "DynamoDBStreams";
|
||||
} else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_TARGET_PREFIX;
|
||||
serviceName = "DynamoDB";
|
||||
} else if (target.startsWith(SQS_TARGET_PREFIX)) {
|
||||
prefix = SQS_TARGET_PREFIX;
|
||||
serviceName = "SQS";
|
||||
} else if (target.startsWith(SNS_TARGET_PREFIX)) {
|
||||
prefix = SNS_TARGET_PREFIX;
|
||||
serviceName = "SNS";
|
||||
} else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) {
|
||||
prefix = STEPFUNCTIONS_TARGET_PREFIX;
|
||||
serviceName = "StepFunctions";
|
||||
} else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
|
||||
prefix = CLOUDWATCH_TARGET_PREFIX;
|
||||
serviceName = "CloudWatch";
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
String action = target.substring(prefix.length());
|
||||
LOG.debugv("{0} CBOR action: {1}", serviceName, action);
|
||||
|
||||
try {
|
||||
JsonNode request = (body != null && body.length > 0)
|
||||
? CBOR_MAPPER.readTree(body)
|
||||
: objectMapper.createObjectNode();
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = switch (serviceName) {
|
||||
case "DynamoDB" -> dynamoDbJsonHandler.handle(action, request, region);
|
||||
case "DynamoDBStreams" -> dynamoDbStreamsJsonHandler.handle(action, request, region);
|
||||
case "SQS" -> sqsJsonHandler.handle(action, request, region);
|
||||
case "SNS" -> snsJsonHandler.handle(action, request, region);
|
||||
case "StepFunctions" -> sfnJsonHandler.handle(action, request, region);
|
||||
case "CloudWatch" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
if (delegated == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return cborErrorResponse(e, "smithy-protocol");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing CBOR request: " + serviceName + "." + action, e);
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches a CBOR request to the appropriate service handler by SDK service ID.
|
||||
*/
|
||||
private Response dispatchCbor(String serviceId, String operation, JsonNode request, String region) throws Exception {
|
||||
return switch (serviceId) {
|
||||
case "DynamoDB" -> dynamoDbJsonHandler.handle(operation, request, region);
|
||||
case "DynamoDB Streams" -> dynamoDbStreamsJsonHandler.handle(operation, request, region);
|
||||
case "SQS" -> sqsJsonHandler.handle(operation, request, region);
|
||||
case "SNS" -> snsJsonHandler.handle(operation, request, region);
|
||||
case "SFN" -> sfnJsonHandler.handle(operation, request, region);
|
||||
case CLOUDWATCH_SERVICE_ID -> cloudWatchMetricsJsonHandler.handle(operation, request, region);
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private Response cborErrorResponse(AwsException e, String protocolHeader) {
|
||||
try {
|
||||
byte[] errBytes = CBOR_MAPPER.writeValueAsBytes(
|
||||
new AwsErrorResponse(e.jsonType(), e.getMessage()));
|
||||
String queryErrorFault = (e.getHttpStatus() < 500) ? "Sender" : "Receiver";
|
||||
return Response.status(e.getHttpStatus())
|
||||
.header(protocolHeader, "rpc-v2-cbor")
|
||||
.header("x-amzn-query-error", e.getErrorCode() + ";" + queryErrorFault)
|
||||
.type("application/cbor")
|
||||
.entity(errBytes)
|
||||
.build();
|
||||
} catch (Exception ex) {
|
||||
return Response.status(e.getHttpStatus()).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,17 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -34,7 +27,6 @@ import org.jboss.logging.Logger;
|
||||
public class AwsJsonController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsJsonController.class);
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
|
||||
private static final String DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810.";
|
||||
private static final String DYNAMODB_STREAMS_TARGET_PREFIX = "DynamoDBStreams_20120810.";
|
||||
@@ -42,7 +34,6 @@ public class AwsJsonController {
|
||||
private static final String SNS_TARGET_PREFIX = "SNS_20100331.";
|
||||
private static final String STEPFUNCTIONS_TARGET_PREFIX = "AWSStepFunctions.";
|
||||
private static final String CLOUDWATCH_TARGET_PREFIX = "GraniteServiceVersion20100801.";
|
||||
private static final String CLOUDWATCH_SERVICE_ID = "GraniteServiceVersion20100801";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -72,7 +63,7 @@ public class AwsJsonController {
|
||||
|
||||
@POST
|
||||
@Consumes("application/x-amz-json-1.0")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Produces("application/x-amz-json-1.0")
|
||||
public Response handleJsonRequest(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
@@ -88,35 +79,27 @@ public class AwsJsonController {
|
||||
|
||||
if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_STREAMS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "DynamoDBStreams";
|
||||
} else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "DynamoDB";
|
||||
} else if (target.startsWith(SQS_TARGET_PREFIX)) {
|
||||
prefix = SQS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "SQS";
|
||||
} else if (target.startsWith(SNS_TARGET_PREFIX)) {
|
||||
prefix = SNS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "SNS";
|
||||
} else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) {
|
||||
prefix = STEPFUNCTIONS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "StepFunctions";
|
||||
} else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
|
||||
prefix = CLOUDWATCH_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "CloudWatch";
|
||||
} else {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Unknown operation: " + target))
|
||||
.build();
|
||||
return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target);
|
||||
}
|
||||
|
||||
action = target.substring(prefix.length());
|
||||
LOG.debugv("{0} JSON action: {1}", serviceName, action);
|
||||
|
||||
try {
|
||||
@@ -133,211 +116,10 @@ public class AwsJsonController {
|
||||
default -> null;
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse(e.jsonType(), e.getMessage()))
|
||||
.build();
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing " + serviceName + " JSON request", e);
|
||||
return Response.status(500)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse("InternalServerError", e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a JsonNode to CBOR bytes, encoding fields named "Timestamp" with CBOR tag 1
|
||||
* as required by the smithy-rpc-v2-cbor protocol specification.
|
||||
*/
|
||||
private static byte[] nodeToSmithyCbor(JsonNode node) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
CBORFactory factory = (CBORFactory) CBOR_MAPPER.getFactory();
|
||||
try (CBORGenerator gen = factory.createGenerator(out)) {
|
||||
writeNodeToCbor(gen, node, null);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static void writeNodeToCbor(CBORGenerator gen, JsonNode node, String fieldName) throws Exception {
|
||||
if (node.isObject()) {
|
||||
gen.writeStartObject();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
gen.writeFieldName(entry.getKey());
|
||||
writeNodeToCbor(gen, entry.getValue(), entry.getKey());
|
||||
}
|
||||
gen.writeEndObject();
|
||||
} else if (node.isArray()) {
|
||||
gen.writeStartArray();
|
||||
for (JsonNode item : node) {
|
||||
writeNodeToCbor(gen, item, null);
|
||||
}
|
||||
gen.writeEndArray();
|
||||
} else if ("Timestamp".equals(fieldName) && node.isNumber()) {
|
||||
gen.writeTag(1);
|
||||
// Smithy rpc-v2-cbor timestamps are epoch seconds encoded as tagged floating-point numbers.
|
||||
gen.writeNumber(node.doubleValue());
|
||||
} else if (node.isTextual()) {
|
||||
gen.writeString(node.textValue());
|
||||
} else if (node.isDouble() || node.isFloat()) {
|
||||
gen.writeNumber(node.doubleValue());
|
||||
} else if (node.isLong() || node.isInt()) {
|
||||
gen.writeNumber(node.longValue());
|
||||
} else if (node.isBoolean()) {
|
||||
gen.writeBoolean(node.booleanValue());
|
||||
} else if (node.isNull()) {
|
||||
gen.writeNull();
|
||||
} else {
|
||||
gen.writeString(node.asText());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles AWS smithy-rpc-v2-cbor protocol requests.
|
||||
* AWS SDK v2 sends to POST /service/{sdkId}/operation/{op}
|
||||
* with Content-Type: application/cbor and no X-Amz-Target header.
|
||||
* Supported services: DynamoDB, SQS, SNS, StepFunctions, CloudWatch.
|
||||
*/
|
||||
@POST
|
||||
@Path("service/{serviceId}/operation/{operation}")
|
||||
@Consumes("application/cbor")
|
||||
@Produces("application/cbor")
|
||||
public Response handleSmithyRpcV2Cbor(
|
||||
@PathParam("serviceId") String serviceId,
|
||||
@PathParam("operation") String operation,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
byte[] body) {
|
||||
|
||||
LOG.debugv("Smithy RPC v2 CBOR: service={0}, operation={1}", serviceId, operation);
|
||||
|
||||
try {
|
||||
JsonNode request = (body != null && body.length > 0)
|
||||
? CBOR_MAPPER.readTree(body)
|
||||
: objectMapper.createObjectNode();
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = dispatchCbor(serviceId, operation, request, region);
|
||||
if (delegated == null) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
|
||||
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("Smithy-Protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return cborErrorResponse(e, "Smithy-Protocol");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing Smithy CBOR request: " + serviceId + "." + operation, e);
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles AWS services that migrated to the smithy-rpc-v2-cbor protocol at root path.
|
||||
* Fallback handler for X-Amz-Target based routing with CBOR body.
|
||||
*/
|
||||
@POST
|
||||
@Consumes("application/cbor")
|
||||
@Produces("application/cbor")
|
||||
public Response handleCborRequest(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
byte[] body) {
|
||||
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String prefix;
|
||||
String serviceName;
|
||||
|
||||
if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_STREAMS_TARGET_PREFIX;
|
||||
serviceName = "DynamoDBStreams";
|
||||
} else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_TARGET_PREFIX;
|
||||
serviceName = "DynamoDB";
|
||||
} else if (target.startsWith(SQS_TARGET_PREFIX)) {
|
||||
prefix = SQS_TARGET_PREFIX;
|
||||
serviceName = "SQS";
|
||||
} else if (target.startsWith(SNS_TARGET_PREFIX)) {
|
||||
prefix = SNS_TARGET_PREFIX;
|
||||
serviceName = "SNS";
|
||||
} else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) {
|
||||
prefix = STEPFUNCTIONS_TARGET_PREFIX;
|
||||
serviceName = "StepFunctions";
|
||||
} else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
|
||||
prefix = CLOUDWATCH_TARGET_PREFIX;
|
||||
serviceName = "CloudWatch";
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
String action = target.substring(prefix.length());
|
||||
LOG.debugv("{0} CBOR action: {1}", serviceName, action);
|
||||
|
||||
try {
|
||||
JsonNode request = (body != null && body.length > 0)
|
||||
? CBOR_MAPPER.readTree(body)
|
||||
: objectMapper.createObjectNode();
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = switch (serviceName) {
|
||||
case "DynamoDB" -> dynamoDbJsonHandler.handle(action, request, region);
|
||||
case "DynamoDBStreams" -> dynamoDbStreamsJsonHandler.handle(action, request, region);
|
||||
case "SQS" -> sqsJsonHandler.handle(action, request, region);
|
||||
case "SNS" -> snsJsonHandler.handle(action, request, region);
|
||||
case "StepFunctions" -> sfnJsonHandler.handle(action, request, region);
|
||||
case "CloudWatch" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
if (delegated == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return cborErrorResponse(e, "smithy-protocol");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing CBOR request: " + serviceName + "." + action, e);
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatches a CBOR request to the appropriate service handler by SDK service ID. */
|
||||
private Response dispatchCbor(String serviceId, String operation, JsonNode request, String region) throws Exception {
|
||||
return switch (serviceId) {
|
||||
case "DynamoDB" -> dynamoDbJsonHandler.handle(operation, request, region);
|
||||
case "DynamoDB Streams" -> dynamoDbStreamsJsonHandler.handle(operation, request, region);
|
||||
case "SQS" -> sqsJsonHandler.handle(operation, request, region);
|
||||
case "SNS" -> snsJsonHandler.handle(operation, request, region);
|
||||
case "SFN" -> sfnJsonHandler.handle(operation, request, region);
|
||||
case CLOUDWATCH_SERVICE_ID -> cloudWatchMetricsJsonHandler.handle(operation, request, region);
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private Response cborErrorResponse(AwsException e, String protocolHeader) {
|
||||
try {
|
||||
byte[] errBytes = CBOR_MAPPER.writeValueAsBytes(
|
||||
new AwsErrorResponse(e.jsonType(), e.getMessage()));
|
||||
return Response.status(e.getHttpStatus())
|
||||
.header(protocolHeader, "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(errBytes)
|
||||
.build();
|
||||
} catch (Exception ex) {
|
||||
return Response.status(e.getHttpStatus()).build();
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.resteasy.reactive.jackson.runtime.serialisers.FullyFeaturedServerJacksonMessageBodyWriter;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import jakarta.ws.rs.ext.Providers;
|
||||
|
||||
@Provider
|
||||
@Produces({"application/x-amz-json-1.0", "application/x-amz-json-1.1"})
|
||||
public class AwsJsonMessageBodyWriter extends FullyFeaturedServerJacksonMessageBodyWriter {
|
||||
|
||||
@Inject
|
||||
public AwsJsonMessageBodyWriter(Instance<ObjectMapper> mapper, Providers providers) {
|
||||
super(mapper, providers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
public class JsonErrorResponseUtils {
|
||||
|
||||
private JsonErrorResponseUtils() {
|
||||
// Do not instantiate
|
||||
}
|
||||
|
||||
public static Response createErrorResponse(Exception e) {
|
||||
return JsonErrorResponseUtils.createErrorResponse(500, "InternalFailure", "InternalFailure", e.getMessage());
|
||||
}
|
||||
|
||||
public static Response createErrorResponse(AwsException e) {
|
||||
return createErrorResponse(e.getHttpStatus(), e.getErrorCode(), e.jsonType(), e.getMessage());
|
||||
}
|
||||
|
||||
public static Response createUnknownOperationErrorResponse(String target) {
|
||||
return createErrorResponse(404,
|
||||
"UnknownOperationException",
|
||||
"UnknownOperationException",
|
||||
"Unknown operation: " + target);
|
||||
}
|
||||
|
||||
public static Response createErrorResponse(int httpStatusCode, String queryError, String errorType, String errorMessage) {
|
||||
String queryErrorFault = (httpStatusCode < 500) ? "Sender" : "Receiver";
|
||||
return Response.status(httpStatusCode)
|
||||
.header("x-amzn-query-error", queryError + ";" + queryErrorFault)
|
||||
.entity(new AwsErrorResponse(errorType, errorMessage))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+20
-36
@@ -1,15 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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 io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.List;
|
||||
@@ -51,15 +50,10 @@ public class ApiGatewayV2JsonHandler {
|
||||
case "DeleteStage" -> handleDeleteStage(request, region);
|
||||
case "CreateDeployment" -> handleCreateDeployment(request, region);
|
||||
case "GetDeployments" -> handleGetDeployments(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported."))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
default -> JsonErrorResponseUtils.createUnknownOperationErrorResponse(action);
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +63,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Api api = service.createApi(region, map);
|
||||
return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toApiNode(api).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetApis(String region) {
|
||||
@@ -77,13 +71,12 @@ public class ApiGatewayV2JsonHandler {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
apis.forEach(a -> items.add(toApiNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetApi(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
return Response.ok(toApiNode(service.getApi(region, apiId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toApiNode(service.getApi(region, apiId)).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteApi(JsonNode request, String region) {
|
||||
@@ -99,15 +92,13 @@ public class ApiGatewayV2JsonHandler {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Authorizer auth = service.createAuthorizer(region, apiId, map);
|
||||
return Response.status(201).entity(toAuthorizerNode(auth).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toAuthorizerNode(auth).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetAuthorizer(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String authorizerId = request.path("AuthorizerId").asText();
|
||||
return Response.ok(toAuthorizerNode(service.getAuthorizer(region, apiId, authorizerId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toAuthorizerNode(service.getAuthorizer(region, apiId, authorizerId)).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetAuthorizers(JsonNode request, String region) {
|
||||
@@ -116,7 +107,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
authorizers.forEach(a -> items.add(toAuthorizerNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteAuthorizer(JsonNode request, String region) {
|
||||
@@ -133,15 +124,13 @@ public class ApiGatewayV2JsonHandler {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Route route = service.createRoute(region, apiId, map);
|
||||
return Response.status(201).entity(toRouteNode(route).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toRouteNode(route).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetRoute(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String routeId = request.path("RouteId").asText();
|
||||
return Response.ok(toRouteNode(service.getRoute(region, apiId, routeId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toRouteNode(service.getRoute(region, apiId, routeId)).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetRoutes(JsonNode request, String region) {
|
||||
@@ -150,7 +139,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
routes.forEach(r -> items.add(toRouteNode(r)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteRoute(JsonNode request, String region) {
|
||||
@@ -167,15 +156,13 @@ public class ApiGatewayV2JsonHandler {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Integration integration = service.createIntegration(region, apiId, map);
|
||||
return Response.status(201).entity(toIntegrationNode(integration).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toIntegrationNode(integration).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetIntegration(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String integrationId = request.path("IntegrationId").asText();
|
||||
return Response.ok(toIntegrationNode(service.getIntegration(region, apiId, integrationId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toIntegrationNode(service.getIntegration(region, apiId, integrationId)).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetIntegrations(JsonNode request, String region) {
|
||||
@@ -184,7 +171,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
integrations.forEach(i -> items.add(toIntegrationNode(i)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Stage ────────────────────────────
|
||||
@@ -194,15 +181,13 @@ public class ApiGatewayV2JsonHandler {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Stage stage = service.createStage(region, apiId, map);
|
||||
return Response.status(201).entity(toStageNode(stage).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toStageNode(stage).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetStage(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String stageName = request.path("StageName").asText();
|
||||
return Response.ok(toStageNode(service.getStage(region, apiId, stageName)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toStageNode(service.getStage(region, apiId, stageName)).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetStages(JsonNode request, String region) {
|
||||
@@ -211,7 +196,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
stages.forEach(s -> items.add(toStageNode(s)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteStage(JsonNode request, String region) {
|
||||
@@ -228,8 +213,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Deployment deployment = service.createDeployment(region, apiId, map);
|
||||
return Response.status(201).entity(toDeploymentNode(deployment).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toDeploymentNode(deployment).toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetDeployments(JsonNode request, String region) {
|
||||
@@ -238,7 +222,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
deployments.forEach(d -> items.add(toDeploymentNode(d)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Serializers ────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user