mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(core): route JSON services over Smithy RPC v2 CBOR (#8592)
* fix(core): share JSON dispatch with RPC v2 CBOR * fix(core): adapt modeled blobs and timestamps for RPC v2 CBOR * fix(core): preserve CBOR event streams and compact wire models * test(paymentcryptography): avoid random CVV verification collisions
This commit is contained in:
1 parent
017e635edf
commit
306bcf8c5b
15 files changed
+7653
-134
No files matched your search
@@ -64,13 +64,19 @@ import io.floci.aws.services.transfer.TransferHandler;
|
||||
import io.floci.aws.services.translate.TranslateJsonHandler;
|
||||
import io.floci.aws.services.wafv2.WafV2Handler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* Generic dispatcher for all AWS services that use the application/x-amz-json-1.1 protocol.
|
||||
* Routes requests to the appropriate service handler based on the X-Amz-Target header prefix.
|
||||
@@ -314,84 +320,7 @@ public class AwsJson11Controller {
|
||||
authorization = IamEnforcementFilter.requestAuthorization(null, uriInfo.getQueryParameters());
|
||||
}
|
||||
|
||||
Response delegated = switch (serviceKey) {
|
||||
case "ssm" -> ssmJsonHandler.handle(
|
||||
action, request, region, authorization);
|
||||
case "events" -> eventBridgeHandler.handle(action, request, region);
|
||||
case "servicediscovery" -> cloudMapHandler.handle(action, request, region);
|
||||
case "elasticmapreduce" -> emrHandler.handle(action, request, region);
|
||||
case "wafv2" -> wafV2Handler.handle(action, request, region);
|
||||
case "memorydb" -> memoryDbHandler.handle(action, request, region);
|
||||
case "logs" -> cloudWatchLogsHandler.handle(action, request, region);
|
||||
case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region, authorization);
|
||||
case "kinesis" -> kinesisJsonHandler.handle(action, request, region);
|
||||
case "kinesisanalytics" -> kinesisAnalyticsV2JsonHandler.handle(action, request, region);
|
||||
case "apigatewayv2" -> apigwV2JsonHandler.handle(action, request, region);
|
||||
case "kms" -> kmsJsonHandler.handle(action, request, region);
|
||||
case "cognito-idp" -> cognitoJsonHandler.handle(action, request, region);
|
||||
case "acm" -> acmJsonHandler.handle(action, request, region);
|
||||
case "ecs" -> ecsJsonHandler.handle(action, request, region, uriInfo.getBaseUri());
|
||||
case "ecr" -> ecrJsonHandler.handle(action, request, region);
|
||||
case "glue" -> glueJsonHandler.handle(action, request, region);
|
||||
case "athena" -> athenaJsonHandler.handle(action, request, region);
|
||||
case "redshift-data" -> redshiftDataJsonHandler.handle(action, request, region);
|
||||
case "redshift-serverless" -> redshiftServerlessJsonHandler.handle(
|
||||
action, request, region, authorization);
|
||||
case "firehose" -> firehoseJsonHandler.handle(action, request, region);
|
||||
case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
|
||||
case "codebuild" -> codeBuildJsonHandler.handle(action, request, region, regionResolver.getAccountId());
|
||||
case "codedeploy" -> codeDeployJsonHandler.handle(action, request, region);
|
||||
case "codepipeline" -> codePipelineJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);
|
||||
case "ec2-instance-connect" -> instanceConnectJsonHandler.handle(action, request, region);
|
||||
case "transfer" -> transferHandler.handle(action, request, region);
|
||||
case "textract" -> textractJsonHandler.handle(action, request, region);
|
||||
case "comprehend" -> comprehendJsonHandler.handle(action, request, region);
|
||||
case "rekognition" -> rekognitionJsonHandler.handle(action, request, region);
|
||||
case "pricing" -> pricingJsonHandler.handle(action, request, region);
|
||||
case "transcribe" -> transcribeJsonHandler.handle(action, request);
|
||||
case "translate" -> translateJsonHandler.handle(action, request, region);
|
||||
case "ce" -> costExplorerJsonHandler.handle(action, request, region);
|
||||
case "cur" -> curJsonHandler.handle(action, request, region);
|
||||
case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region);
|
||||
case "config" -> configServiceJsonHandler.handle(action, request, region);
|
||||
case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region);
|
||||
case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region);
|
||||
case "lightsail" -> lightsailJsonHandler.handle(action, request, region);
|
||||
case "route53resolver" -> route53ResolverJsonHandler.handle(action, request, region, regionResolver.getAccountId());
|
||||
case "cognito-identity" -> cognitoIdentityJsonHandler.handle(action, request, region);
|
||||
// Global Accelerator is a global service: its resources carry an empty ARN region
|
||||
// segment and are never partitioned by the region the caller signed with, so the
|
||||
// handler takes no region.
|
||||
case "globalaccelerator" -> globalAcceleratorJsonHandler.handle(action, request);
|
||||
case "datasync" -> dataSyncJsonHandler.handle(action, request, region);
|
||||
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "servicecatalog" -> serviceCatalogJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "cloudcontrol" -> cloudControlJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "cloudhsmv2" -> cloudHsmV2JsonHandler.handle(action, request, region);
|
||||
// Organizations is global and account-scoped rather than region-scoped: every
|
||||
// action is authorized against the calling account, so pass that instead of region.
|
||||
case "organizations" ->
|
||||
organizationsJsonHandler.handle(action, request, regionResolver.getAccountId());
|
||||
case "sso" -> ssoAdminJsonHandler.handle(action, request, regionResolver.getAccountId(), region);
|
||||
case "identitystore" -> identityStoreJsonHandler.handle(action, request);
|
||||
case "budgets" -> budgetsJsonHandler.handle(action, request, regionResolver.getAccountId());
|
||||
case "servicequotas" -> serviceQuotasJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "marketplace" -> {
|
||||
if (targetMatch.prefix().startsWith("AWSMPEntitlementService.")) {
|
||||
yield marketplaceEntitlementController.handle(action, request, region);
|
||||
}
|
||||
yield marketplaceMeteringController.handle(action, request, region);
|
||||
}
|
||||
case "sagemaker" -> sageMakerJsonHandler.handle(action, request, region);
|
||||
case "dms" -> dmsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
Response delegated = dispatch(targetMatch, request, region, authorization, uriInfo.getBaseUri());
|
||||
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
|
||||
// (e.g. DynamoDB_20120810.*) can match here under @Consumes json-1.1.
|
||||
// Return the AWS-style unknown-operation error rather than null.
|
||||
@@ -407,4 +336,90 @@ public class AwsJson11Controller {
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatches an already-decoded request before HTTP-specific response encoding. */
|
||||
Response dispatch(ServiceCatalog.TargetMatch targetMatch, JsonNode request, String region,
|
||||
String authorization, URI baseUri) throws Exception {
|
||||
String serviceKey = targetMatch.descriptor().externalKey();
|
||||
String action = targetMatch.action();
|
||||
return switch (serviceKey) {
|
||||
case "ssm" -> ssmJsonHandler.handle(
|
||||
action, request, region, authorization);
|
||||
case "events" -> eventBridgeHandler.handle(action, request, region);
|
||||
case "servicediscovery" -> cloudMapHandler.handle(action, request, region);
|
||||
case "elasticmapreduce" -> emrHandler.handle(action, request, region);
|
||||
case "wafv2" -> wafV2Handler.handle(action, request, region);
|
||||
case "memorydb" -> memoryDbHandler.handle(action, request, region);
|
||||
case "logs" -> cloudWatchLogsHandler.handle(action, request, region);
|
||||
case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region, authorization);
|
||||
case "kinesis" -> kinesisJsonHandler.handle(action, request, region);
|
||||
case "kinesisanalytics" -> kinesisAnalyticsV2JsonHandler.handle(action, request, region);
|
||||
case "apigatewayv2" -> apigwV2JsonHandler.handle(action, request, region);
|
||||
case "kms" -> kmsJsonHandler.handle(action, request, region);
|
||||
case "cognito-idp" -> cognitoJsonHandler.handle(action, request, region);
|
||||
case "acm" -> acmJsonHandler.handle(action, request, region);
|
||||
case "ecs" -> ecsJsonHandler.handle(action, request, region, baseUri);
|
||||
case "ecr" -> ecrJsonHandler.handle(action, request, region);
|
||||
case "glue" -> glueJsonHandler.handle(action, request, region);
|
||||
case "athena" -> athenaJsonHandler.handle(action, request, region);
|
||||
case "redshift-data" -> redshiftDataJsonHandler.handle(action, request, region);
|
||||
case "redshift-serverless" -> redshiftServerlessJsonHandler.handle(
|
||||
action, request, region, authorization);
|
||||
case "firehose" -> firehoseJsonHandler.handle(action, request, region);
|
||||
case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
|
||||
case "codebuild" -> codeBuildJsonHandler.handle(action, request, region, regionResolver.getAccountId());
|
||||
case "codedeploy" -> codeDeployJsonHandler.handle(action, request, region);
|
||||
case "codepipeline" -> codePipelineJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);
|
||||
case "ec2-instance-connect" -> instanceConnectJsonHandler.handle(action, request, region);
|
||||
case "transfer" -> transferHandler.handle(action, request, region);
|
||||
case "textract" -> textractJsonHandler.handle(action, request, region);
|
||||
case "comprehend" -> comprehendJsonHandler.handle(action, request, region);
|
||||
case "rekognition" -> rekognitionJsonHandler.handle(action, request, region);
|
||||
case "pricing" -> pricingJsonHandler.handle(action, request, region);
|
||||
case "transcribe" -> transcribeJsonHandler.handle(action, request);
|
||||
case "translate" -> translateJsonHandler.handle(action, request, region);
|
||||
case "ce" -> costExplorerJsonHandler.handle(action, request, region);
|
||||
case "cur" -> curJsonHandler.handle(action, request, region);
|
||||
case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region);
|
||||
case "config" -> configServiceJsonHandler.handle(action, request, region);
|
||||
case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region);
|
||||
case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region);
|
||||
case "lightsail" -> lightsailJsonHandler.handle(action, request, region);
|
||||
case "route53resolver" -> route53ResolverJsonHandler.handle(action, request, region, regionResolver.getAccountId());
|
||||
case "cognito-identity" -> cognitoIdentityJsonHandler.handle(action, request, region);
|
||||
// Global Accelerator is a global service: its resources carry an empty ARN region
|
||||
// segment and are never partitioned by the region the caller signed with, so the
|
||||
// handler takes no region.
|
||||
case "globalaccelerator" -> globalAcceleratorJsonHandler.handle(action, request);
|
||||
case "datasync" -> dataSyncJsonHandler.handle(action, request, region);
|
||||
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "servicecatalog" -> serviceCatalogJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "cloudcontrol" -> cloudControlJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "cloudhsmv2" -> cloudHsmV2JsonHandler.handle(action, request, region);
|
||||
// Organizations is global and account-scoped rather than region-scoped: every
|
||||
// action is authorized against the calling account, so pass that instead of region.
|
||||
case "organizations" ->
|
||||
organizationsJsonHandler.handle(action, request, regionResolver.getAccountId());
|
||||
case "sso" -> ssoAdminJsonHandler.handle(action, request, regionResolver.getAccountId(), region);
|
||||
case "identitystore" -> identityStoreJsonHandler.handle(action, request);
|
||||
case "budgets" -> budgetsJsonHandler.handle(action, request, regionResolver.getAccountId());
|
||||
case "servicequotas" -> serviceQuotasJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "marketplace" -> {
|
||||
if (targetMatch.prefix().startsWith("AWSMPEntitlementService.")) {
|
||||
yield marketplaceEntitlementController.handle(action, request, region);
|
||||
}
|
||||
yield targetMatch.prefix().startsWith("AWSMPMeteringService.")
|
||||
? marketplaceMeteringController.handle(action, request, region) : null;
|
||||
}
|
||||
case "sagemaker" -> sageMakerJsonHandler.handle(action, request, region);
|
||||
case "dms" -> dmsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,10 +22,17 @@ import io.floci.aws.services.stepfunctions.StepFunctionsJsonHandler;
|
||||
import io.floci.aws.services.translate.TranslateJsonHandler;
|
||||
import io.smallrye.common.annotation.RunOnVirtualThread;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
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 jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
@@ -44,8 +51,8 @@ import java.util.zip.GZIPInputStream;
|
||||
* Generic dispatcher for all AWS services that use the application/cbor protocol,
|
||||
* via either smithy-rpc-v2-cbor path routing or the legacy X-Amz-Target header.
|
||||
* <p>
|
||||
* Currently supported services: DynamoDB (incl. Streams), SQS, SNS, Kinesis,
|
||||
* Step Functions, CloudWatch Metrics, and EventBridge V2.
|
||||
* RPC v2 requests reuse the target-routed JSON service dispatchers. Existing CBOR-only services
|
||||
* and legacy X-Amz-Target routes retain their format-specific handlers.
|
||||
* <p>
|
||||
* Requests run on virtual threads, as in {@link AwsJsonController}, so a ReceiveMessage or
|
||||
* GetActivityTask long poll does not hold one of the shared request workers while it waits.
|
||||
@@ -55,7 +62,9 @@ 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 RpcV2CborCodec RPC_CODEC = RpcV2CborCodec.load();
|
||||
private static final String GENERIC_CBOR_MEDIA_TYPE = "application/cbor";
|
||||
private static final String EVENT_STREAM_MEDIA_TYPE = "application/vnd.amazon.eventstream";
|
||||
private static final String AWS_CBOR_1_1_MEDIA_TYPE = "application/x-amz-cbor-1.1";
|
||||
|
||||
/** The RPC v2 path parameters {@link IamEnforcementFilter} authorizes, as this endpoint dispatches them. */
|
||||
@@ -65,6 +74,8 @@ public class AwsJsonCborController {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ResolvedServiceCatalog catalog;
|
||||
private final RegionResolver regionResolver;
|
||||
private final AwsJsonController jsonController;
|
||||
private final AwsJson11Controller json11Controller;
|
||||
private final DynamoDbJsonHandler dynamoDbJsonHandler;
|
||||
private final DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler;
|
||||
private final SqsJsonHandler sqsJsonHandler;
|
||||
@@ -87,10 +98,13 @@ public class AwsJsonCborController {
|
||||
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler,
|
||||
MarketplaceEntitlementController marketplaceEntitlementController,
|
||||
EventBridgeV2Handler eventBridgeV2Handler,
|
||||
TranslateJsonHandler translateJsonHandler) {
|
||||
TranslateJsonHandler translateJsonHandler,
|
||||
AwsJsonController jsonController, AwsJson11Controller json11Controller) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.catalog = catalog;
|
||||
this.regionResolver = regionResolver;
|
||||
this.jsonController = jsonController;
|
||||
this.json11Controller = json11Controller;
|
||||
this.dynamoDbJsonHandler = dynamoDbJsonHandler;
|
||||
this.dynamoDbStreamsJsonHandler = dynamoDbStreamsJsonHandler;
|
||||
this.sqsJsonHandler = sqsJsonHandler;
|
||||
@@ -322,35 +336,50 @@ public class AwsJsonCborController {
|
||||
@POST
|
||||
@Path("service/{serviceId}/operation/{operation}")
|
||||
@Consumes({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
|
||||
@Produces({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
|
||||
@Produces({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE, EVENT_STREAM_MEDIA_TYPE})
|
||||
@RunOnVirtualThread
|
||||
public Response handleSmithyRpcV2Cbor(
|
||||
@PathParam(RPC_V2_SERVICE_PARAMETER) String serviceId,
|
||||
@PathParam(RPC_V2_OPERATION_PARAMETER) String operation,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
@Context UriInfo uriInfo,
|
||||
byte[] body) {
|
||||
|
||||
LOG.debugv("Smithy RPC v2 CBOR: service={0}, operation={1}", serviceId, operation);
|
||||
|
||||
try {
|
||||
JsonNode request = bodyToJson(httpHeaders, body);
|
||||
boolean modeled = RPC_CODEC.supports(serviceId);
|
||||
if (modeled) {
|
||||
request = RPC_CODEC.decodeRequest(serviceId, operation, request);
|
||||
}
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = dispatchCbor(serviceId, operation, request, region);
|
||||
Response delegated = dispatchCbor(serviceId, operation, request, region, httpHeaders, uriInfo);
|
||||
if (delegated == null) {
|
||||
return Response.status(404).build();
|
||||
return cborUnknownOperationError("Unknown service or operation: " + serviceId + "." + operation,
|
||||
httpHeaders);
|
||||
}
|
||||
|
||||
JsonNode responseNode = delegated.getEntity() instanceof JsonNode
|
||||
? (JsonNode) delegated.getEntity()
|
||||
: objectMapper.valueToTree(delegated.getEntity());
|
||||
byte[] cborBytes = nodeToSmithyCbor(responseNode, timestampMembers(serviceId));
|
||||
String responseContentType = responseContentType(httpHeaders);
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.type(responseContentType)
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
boolean successful = delegated.getStatus() >= 200 && delegated.getStatus() < 300;
|
||||
Response.ResponseBuilder response = Response.fromResponse(delegated)
|
||||
.status(successful ? 200 : delegated.getStatus())
|
||||
.header(HttpHeaders.CONTENT_LENGTH, null)
|
||||
.header("X-Amz-Crc32", null)
|
||||
.header("smithy-protocol", "rpc-v2-cbor");
|
||||
if (delegated.getMediaType() != null
|
||||
&& MediaType.valueOf(EVENT_STREAM_MEDIA_TYPE).isCompatible(delegated.getMediaType())
|
||||
&& delegated.getEntity() instanceof byte[] frames) {
|
||||
return response.type(EVENT_STREAM_MEDIA_TYPE)
|
||||
.entity(RPC_CODEC.encodeEventStream(serviceId, operation, frames)).build();
|
||||
}
|
||||
if (modeled && successful && !RPC_CODEC.hasOutput(serviceId, operation)) {
|
||||
return response.entity(null).type((String) null).build();
|
||||
}
|
||||
JsonNode responseNode = responseNode(delegated.getEntity());
|
||||
byte[] cborBytes = modeled ? RPC_CODEC.encodeResponse(serviceId, operation, responseNode)
|
||||
: nodeToSmithyCbor(responseNode, timestampMembers(serviceId));
|
||||
return response.type(responseContentType(httpHeaders)).entity(cborBytes).build();
|
||||
} catch (AwsException e) {
|
||||
return cborErrorResponse(e, "smithy-protocol", responseContentType(httpHeaders));
|
||||
} catch (JacksonException e) {
|
||||
@@ -510,7 +539,8 @@ public class AwsJsonCborController {
|
||||
/**
|
||||
* 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 {
|
||||
private Response dispatchCbor(String serviceId, String operation, JsonNode request, String region,
|
||||
HttpHeaders headers, UriInfo uriInfo) throws Exception {
|
||||
ServiceDescriptor descriptor = catalog.byCborSdkServiceId(serviceId).orElse(null);
|
||||
if (descriptor == null) {
|
||||
return null;
|
||||
@@ -528,13 +558,45 @@ public class AwsJsonCborController {
|
||||
case "kinesis" -> kinesisJsonHandler.handle(operation, request, region);
|
||||
case "states" -> sfnJsonHandler.handle(operation, request, region);
|
||||
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(operation, request, region);
|
||||
case "marketplace" -> marketplaceEntitlementController.handle(operation, request, region);
|
||||
case "marketplace" -> descriptor.cborSdkServiceIds().contains(serviceId)
|
||||
? marketplaceEntitlementController.handle(operation, request, region)
|
||||
: dispatchJson(serviceId, operation, request, region, headers, uriInfo);
|
||||
case "eventsv2" -> eventBridgeV2Handler.handle(operation, request, region);
|
||||
case "translate" -> translateJsonHandler.handleCbor(operation, request, region);
|
||||
default -> null;
|
||||
default -> dispatchJson(serviceId, operation, request, region, headers, uriInfo);
|
||||
};
|
||||
}
|
||||
|
||||
private Response dispatchJson(String serviceId, String operation, JsonNode request, String region,
|
||||
HttpHeaders headers, UriInfo uriInfo) throws Exception {
|
||||
ServiceCatalog.TargetMatch target = catalog.matchTarget(serviceId + "." + operation).orElse(null);
|
||||
if (target == null || target.jsonOnly() || !target.descriptor().supportsProtocol(ServiceProtocol.JSON)) {
|
||||
return null;
|
||||
}
|
||||
if (request == null || !request.isObject()) {
|
||||
throw new AwsException("SerializationException", "Request body must be a structure", 400);
|
||||
}
|
||||
String authorization = headers.getHeaderString("Authorization");
|
||||
if (authorization == null || authorization.isBlank()) {
|
||||
authorization = IamEnforcementFilter.requestAuthorization(null, uriInfo.getQueryParameters());
|
||||
}
|
||||
Response response = json11Controller.dispatch(target, request, region, authorization, uriInfo.getBaseUri());
|
||||
return response != null ? response : jsonController.dispatch(target, request, region, null);
|
||||
}
|
||||
|
||||
private JsonNode responseNode(Object entity) throws IOException {
|
||||
if (entity instanceof JsonNode node) {
|
||||
return node;
|
||||
}
|
||||
if (entity instanceof String json) {
|
||||
return objectMapper.readTree(json);
|
||||
}
|
||||
if (entity instanceof byte[] json) {
|
||||
return objectMapper.readTree(json);
|
||||
}
|
||||
return objectMapper.valueToTree(entity);
|
||||
}
|
||||
|
||||
/** The timestamp members a service's responses carry under names {@link #isTimestampField} does not match. */
|
||||
private Set<String> timestampMembers(String serviceId) {
|
||||
return catalog.byCborSdkServiceId(serviceId)
|
||||
|
||||
@@ -24,7 +24,11 @@ import io.floci.aws.services.timestreaminfluxdb.TimestreamInfluxDbJsonHandler;
|
||||
import io.floci.aws.services.verifiedpermissions.VerifiedPermissionsJsonHandler;
|
||||
import io.smallrye.common.annotation.RunOnVirtualThread;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -173,39 +177,7 @@ public class AwsJsonController {
|
||||
try {
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
response = switch (serviceKey) {
|
||||
case "dynamodb" -> {
|
||||
if (targetMatch.prefix().startsWith("DynamoDBStreams_")) {
|
||||
yield dynamoDbStreamsJsonHandler.handle(action, request, region);
|
||||
}
|
||||
if (targetMatch.jsonOnly()) {
|
||||
yield dynamoDbJsonHandler.handleLegacy(action, request, region);
|
||||
}
|
||||
DynamoDbRequestShapes.check(action, request, body);
|
||||
yield dynamoDbJsonHandler.handle(action, request, region);
|
||||
}
|
||||
case "sqs" -> sqsJsonHandler.handle(action, request, region);
|
||||
case "sns" -> snsJsonHandler.handle(action, request, region);
|
||||
case "states" -> sfnJsonHandler.handle(action, request, region);
|
||||
case "swf" -> swfJsonHandler.handle(action, request, region);
|
||||
case "monitoring" -> targetMatch.jsonOnly()
|
||||
? cloudWatchMetricsJsonHandler.handleLegacy(action, request, region)
|
||||
: cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||
case "cloudcontrol" -> cloudControlJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
// The control plane of Payment Cryptography is an awsJson 1.0 service: the
|
||||
// AWS SDK sends application/x-amz-json-1.0 and targets
|
||||
// PaymentCryptographyControlPlane.<Operation>.
|
||||
case "paymentcryptography" -> paymentCryptographyJsonHandler.handle(action, request, region);
|
||||
case "marketplace" -> marketplaceJsonHandler.handle(action, request, region);
|
||||
case "verifiedpermissions" -> verifiedPermissionsJsonHandler.handle(action, request, region);
|
||||
case "bcm-pricing-calculator" -> bcmPricingCalculatorJsonHandler.handle(action, request, region);
|
||||
case "timestream-influxdb" -> timestreamInfluxDbJsonHandler.handle(action, request, region);
|
||||
case "kms" -> kmsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
response = dispatch(targetMatch, request, region, body);
|
||||
// catalog.matchTarget is protocol-agnostic: a JSON 1.1 target
|
||||
// (e.g. AmazonSSM.*) can match here under @Consumes json-1.0.
|
||||
// Return the AWS-style unknown-operation error rather than null.
|
||||
@@ -244,4 +216,43 @@ public class AwsJsonController {
|
||||
}
|
||||
return response;
|
||||
}
|
||||
/** Dispatches an already-decoded request before HTTP-specific response encoding. */
|
||||
Response dispatch(ServiceCatalog.TargetMatch targetMatch, JsonNode request, String region, String body) throws Exception {
|
||||
String serviceKey = targetMatch.descriptor().externalKey();
|
||||
String action = targetMatch.action();
|
||||
return switch (serviceKey) {
|
||||
case "dynamodb" -> {
|
||||
if (targetMatch.prefix().startsWith("DynamoDBStreams_")) {
|
||||
yield dynamoDbStreamsJsonHandler.handle(action, request, region);
|
||||
}
|
||||
if (targetMatch.jsonOnly()) {
|
||||
yield dynamoDbJsonHandler.handleLegacy(action, request, region);
|
||||
}
|
||||
DynamoDbRequestShapes.check(action, request, body);
|
||||
yield dynamoDbJsonHandler.handle(action, request, region);
|
||||
}
|
||||
case "sqs" -> sqsJsonHandler.handle(action, request, region);
|
||||
case "sns" -> snsJsonHandler.handle(action, request, region);
|
||||
case "states" -> sfnJsonHandler.handle(action, request, region);
|
||||
case "swf" -> swfJsonHandler.handle(action, request, region);
|
||||
case "monitoring" -> targetMatch.jsonOnly()
|
||||
? cloudWatchMetricsJsonHandler.handleLegacy(action, request, region)
|
||||
: cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||
case "cloudcontrol" -> cloudControlJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
// The control plane of Payment Cryptography is an awsJson 1.0 service: the
|
||||
// AWS SDK sends application/x-amz-json-1.0 and targets
|
||||
// PaymentCryptographyControlPlane.<Operation>.
|
||||
case "paymentcryptography" -> paymentCryptographyJsonHandler.handle(action, request, region);
|
||||
case "marketplace" -> marketplaceJsonHandler.handle(action, request, region);
|
||||
case "verifiedpermissions" -> verifiedPermissionsJsonHandler.handle(action, request, region);
|
||||
case "bcm-pricing-calculator" -> bcmPricingCalculatorJsonHandler.handle(action, request, region);
|
||||
case "timestream-influxdb" -> timestreamInfluxDbJsonHandler.handle(action, request, region);
|
||||
case "kms" -> kmsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
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.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.DateTimeException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Converts only members whose wire types are identified by the vendored operation model. */
|
||||
final class RpcV2CborCodec {
|
||||
|
||||
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private final JsonNode metadata;
|
||||
|
||||
private RpcV2CborCodec(JsonNode metadata) {
|
||||
this.metadata = metadata.deepCopy();
|
||||
}
|
||||
|
||||
static RpcV2CborCodec load() {
|
||||
return VendoredResources.read("aws/rpcv2-cbor-shapes.json", "RPC v2 CBOR wire model",
|
||||
in -> parse(new ObjectMapper().readTree(in)));
|
||||
}
|
||||
|
||||
static RpcV2CborCodec parse(JsonNode metadata) {
|
||||
return new RpcV2CborCodec(metadata);
|
||||
}
|
||||
|
||||
boolean supports(String serviceId) {
|
||||
return metadata.path("aliases").has(serviceId);
|
||||
}
|
||||
|
||||
boolean hasOutput(String serviceId, String operation) {
|
||||
return service(serviceId).path("operations").path(operation).path("hasOutput").asBoolean(true);
|
||||
}
|
||||
|
||||
JsonNode decodeRequest(String serviceId, String operation, JsonNode body) {
|
||||
JsonNode service = service(serviceId);
|
||||
String root = service.path("operations").path(operation).path("input").asText(null);
|
||||
return decode(service, root, body, null);
|
||||
}
|
||||
|
||||
byte[] encodeResponse(String serviceId, String operation, JsonNode body) throws IOException {
|
||||
JsonNode service = service(serviceId);
|
||||
String root = service.path("operations").path(operation).path("output").asText(null);
|
||||
return encode(service, root, body);
|
||||
}
|
||||
|
||||
/** Reframes JSON handler events with CBOR payloads, preserving their event names and order. */
|
||||
byte[] encodeEventStream(String serviceId, String operation, byte[] frames) throws IOException {
|
||||
JsonNode service = service(serviceId);
|
||||
JsonNode model = service.path("operations").path(operation);
|
||||
JsonNode events = shape(service, model.path("eventStream").asText(null));
|
||||
ByteBuffer input = ByteBuffer.wrap(frames);
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
while (input.hasRemaining()) {
|
||||
int start = input.position();
|
||||
if (input.remaining() < 16) {
|
||||
throw new IOException("Incomplete handler event-stream frame");
|
||||
}
|
||||
int length = input.getInt();
|
||||
int headerLength = input.getInt();
|
||||
input.getInt(); // The encoder replaces the prelude checksum along with the payload.
|
||||
if (length < 16 || length > frames.length - start || headerLength < 0 || headerLength > length - 16) {
|
||||
throw new IOException("Invalid handler event-stream frame length");
|
||||
}
|
||||
int headerEnd = input.position() + headerLength;
|
||||
LinkedHashMap<String, String> headers = new LinkedHashMap<>();
|
||||
while (input.position() < headerEnd) {
|
||||
String name = frameText(input, Byte.toUnsignedInt(input.get()), headerEnd);
|
||||
if (headerEnd - input.position() < 3 || input.get() != 7) {
|
||||
throw new IOException("Handler event-stream headers must be strings");
|
||||
}
|
||||
int valueLength = Short.toUnsignedInt(input.getShort());
|
||||
headers.put(name, frameText(input, valueLength, headerEnd));
|
||||
}
|
||||
byte[] payload = new byte[length - headerLength - 16];
|
||||
input.get(payload);
|
||||
input.getInt(); // The encoder also replaces the message checksum.
|
||||
String type = headers.getOrDefault(":event-type", headers.get(":exception-type"));
|
||||
String root = "initial-response".equals(type) ? model.path("output").asText(null)
|
||||
: events.path("members").path(type == null ? "" : type).path("shape").asText(null);
|
||||
if (!"application/json".equals(headers.get(":content-type"))) {
|
||||
throw new IOException("Handler event-stream payload must be JSON");
|
||||
}
|
||||
headers.put(":content-type", "application/cbor");
|
||||
output.write(AwsEventStreamEncoder.encodeMessage(headers, encode(service, root, JSON.readTree(payload))));
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
|
||||
private static String frameText(ByteBuffer input, int length, int end) throws IOException {
|
||||
if (length > end - input.position()) {
|
||||
throw new IOException("Invalid handler event-stream header length");
|
||||
}
|
||||
byte[] bytes = new byte[length];
|
||||
input.get(bytes);
|
||||
return new String(bytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private byte[] encode(JsonNode service, String root, JsonNode body) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (CBORGenerator generator = (CBORGenerator) CBOR.getFactory().createGenerator(bytes)) {
|
||||
encode(generator, service, root, body, null);
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private JsonNode service(String serviceId) {
|
||||
String name = metadata.path("aliases").path(serviceId).asText("");
|
||||
return metadata.path("services").path(name);
|
||||
}
|
||||
|
||||
private JsonNode decode(JsonNode service, String name, JsonNode value, String formatOverride) {
|
||||
if (value == null || value.isNull()) {
|
||||
return value;
|
||||
}
|
||||
JsonNode shape = shape(service, name);
|
||||
return switch (shape.path("type").asText()) {
|
||||
case "blob" -> {
|
||||
if (!value.isBinary()) {
|
||||
throw serialization("A CBOR blob must be a byte string");
|
||||
}
|
||||
try {
|
||||
yield TextNode.valueOf(Base64.getEncoder().encodeToString(value.binaryValue()));
|
||||
} catch (IOException e) {
|
||||
throw serialization("Could not decode a CBOR byte string");
|
||||
}
|
||||
}
|
||||
case "timestamp" -> {
|
||||
if (!value.isNumber()) {
|
||||
throw serialization("A CBOR timestamp must contain epoch seconds");
|
||||
}
|
||||
String format = timestampFormat(service, shape, formatOverride);
|
||||
yield switch (format) {
|
||||
case "iso8601" -> TextNode.valueOf(instant(value.decimalValue()).toString());
|
||||
case "rfc822" -> TextNode.valueOf(DateTimeFormatter.RFC_1123_DATE_TIME
|
||||
.format(instant(value.decimalValue()).atZone(ZoneOffset.UTC)));
|
||||
default -> value;
|
||||
};
|
||||
}
|
||||
case "structure" -> {
|
||||
if (!value.isObject()) {
|
||||
yield value.deepCopy();
|
||||
}
|
||||
ObjectNode result = value.deepCopy();
|
||||
for (Map.Entry<String, JsonNode> member : shape.path("members").properties()) {
|
||||
JsonNode child = value.get(member.getKey());
|
||||
if (child == null) {
|
||||
continue;
|
||||
}
|
||||
JsonNode spec = member.getValue();
|
||||
String jsonName = spec.path("jsonName").asText(member.getKey());
|
||||
result.remove(member.getKey());
|
||||
result.set(jsonName, decode(service, spec.path("shape").asText(null), child,
|
||||
spec.path("timestampFormat").asText(null)));
|
||||
}
|
||||
yield result;
|
||||
}
|
||||
case "list" -> {
|
||||
if (!value.isArray()) {
|
||||
yield value.deepCopy();
|
||||
}
|
||||
ArrayNode result = CBOR.createArrayNode();
|
||||
for (JsonNode child : value) {
|
||||
result.add(decode(service, shape.path("member").asText(null), child, formatOverride));
|
||||
}
|
||||
yield result;
|
||||
}
|
||||
case "map" -> {
|
||||
if (!value.isObject()) {
|
||||
yield value.deepCopy();
|
||||
}
|
||||
ObjectNode result = CBOR.createObjectNode();
|
||||
for (Map.Entry<String, JsonNode> entry : value.properties()) {
|
||||
result.set(entry.getKey(), decode(service, shape.path("value").asText(null), entry.getValue(),
|
||||
formatOverride));
|
||||
}
|
||||
yield result;
|
||||
}
|
||||
default -> value.deepCopy();
|
||||
};
|
||||
}
|
||||
|
||||
private void encode(CBORGenerator generator, JsonNode service, String name, JsonNode value,
|
||||
String formatOverride) throws IOException {
|
||||
JsonNode shape = shape(service, name);
|
||||
if (value == null || value.isNull()) {
|
||||
generator.writeNull();
|
||||
} else if ("blob".equals(shape.path("type").asText())) {
|
||||
generator.writeBinary(value.isBinary() ? value.binaryValue() : Base64.getDecoder().decode(value.asText()));
|
||||
} else if ("timestamp".equals(shape.path("type").asText())) {
|
||||
BigDecimal seconds;
|
||||
if (value.isNumber()) {
|
||||
seconds = value.decimalValue();
|
||||
} else {
|
||||
Instant timestamp = "rfc822".equals(timestampFormat(service, shape, formatOverride))
|
||||
? ZonedDateTime.parse(value.asText(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()
|
||||
: Instant.parse(value.asText());
|
||||
seconds = BigDecimal.valueOf(timestamp.getEpochSecond())
|
||||
.add(BigDecimal.valueOf(timestamp.getNano(), 9));
|
||||
}
|
||||
generator.writeTag(1);
|
||||
if (seconds.stripTrailingZeros().scale() <= 0) {
|
||||
generator.writeNumber(seconds.longValueExact());
|
||||
} else {
|
||||
generator.writeNumber(seconds.doubleValue());
|
||||
}
|
||||
} else if ("structure".equals(shape.path("type").asText()) && value.isObject()) {
|
||||
generator.writeStartObject();
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
Map.Entry<String, JsonNode> member = jsonMember(shape, field.getKey());
|
||||
generator.writeFieldName(member == null ? field.getKey() : member.getKey());
|
||||
JsonNode spec = member == null ? CBOR.nullNode() : member.getValue();
|
||||
encode(generator, service, spec.path("shape").asText(null), field.getValue(),
|
||||
spec.path("timestampFormat").asText(null));
|
||||
}
|
||||
generator.writeEndObject();
|
||||
} else if ("list".equals(shape.path("type").asText()) && value.isArray()) {
|
||||
generator.writeStartArray();
|
||||
for (JsonNode child : value) {
|
||||
encode(generator, service, shape.path("member").asText(null), child, formatOverride);
|
||||
}
|
||||
generator.writeEndArray();
|
||||
} else if ("map".equals(shape.path("type").asText()) && value.isObject()) {
|
||||
generator.writeStartObject();
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
generator.writeFieldName(field.getKey());
|
||||
encode(generator, service, shape.path("value").asText(null), field.getValue(), formatOverride);
|
||||
}
|
||||
generator.writeEndObject();
|
||||
} else {
|
||||
generator.writeTree(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode shape(JsonNode service, String name) {
|
||||
return service.path("shapes").path(name == null ? "" : name);
|
||||
}
|
||||
|
||||
private static Map.Entry<String, JsonNode> jsonMember(JsonNode shape, String jsonName) {
|
||||
for (Map.Entry<String, JsonNode> member : shape.path("members").properties()) {
|
||||
if (jsonName.equals(member.getValue().path("jsonName").asText(member.getKey()))) {
|
||||
return member;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String timestampFormat(JsonNode service, JsonNode shape, String override) {
|
||||
return override != null ? override
|
||||
: shape.path("timestampFormat").asText(service.path("timestampFormat").asText("unixTimestamp"));
|
||||
}
|
||||
|
||||
private static Instant instant(BigDecimal seconds) {
|
||||
try {
|
||||
BigDecimal integral = seconds.setScale(0, RoundingMode.DOWN);
|
||||
long nanos = seconds.subtract(integral).movePointRight(9).longValue();
|
||||
return Instant.ofEpochSecond(integral.longValueExact(), nanos);
|
||||
} catch (ArithmeticException | DateTimeException e) {
|
||||
throw serialization("CBOR timestamp is outside the supported range");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException serialization(String message) {
|
||||
return new AwsException("SerializationException", message, 400);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user