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:
Aniket Shukla authored and GitHub committed 2026-11-20 14:09:47 -04:00
1 parent 017e635edf
commit 306bcf8c5b
15 files changed
+7653 -134

No files matched your search

+5
View File
@@ -318,6 +318,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
$(PYTHON) tools/aws/regen_eks_shapes.py
$(PYTHON) tools/aws/regen_organizations_shapes.py
$(PYTHON) tools/aws/regen_emr_serverless_shapes.py
$(PYTHON) tools/aws/regen_rpcv2_cbor_shapes.py
$(PYTHON) tools/aws/regen_query_services.py
$(PYTHON) tools/aws/regen_rest_routes.py
$(PYTHON) tools/aws/regen_iam_paginators.py
@@ -499,6 +500,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_rpcv2_cbor_shapes.py --check || { \
echo "error: RPC v2 CBOR wire shapes are stale; run make aws-data-sync-botocore."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_query_services.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/query-services.json is out of date."; \
+15
View File
@@ -4,6 +4,21 @@ Floci emulates the AWS services listed below on a single port (`4566`). All serv
This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.
## Smithy RPC v2 CBOR
Services with a JSON `X-Amz-Target` endpoint also accept Smithy RPC v2 CBOR at
`POST /service/{serviceName}/operation/{operation}`, with `Content-Type: application/cbor`
and `smithy-protocol: rpc-v2-cbor`. The service name is its target prefix without the final dot;
for example, CodeBuild uses `/service/CodeBuild_20161006/operation/ListProjects`. SDKs that
select this protocol use the same operations, accounts, regions, and IAM checks as JSON clients.
Modeled blobs use CBOR byte strings. Modeled timestamps use tag 1 with epoch seconds, including
members whose JSON form is an ISO date. An operation without an output shape returns no body or
content type. Event-stream operations retain AWS event-stream framing and encode each event payload
as CBOR, including modeled binary records and timestamps. The existing root-path, `X-Amz-Target`
legacy CBOR routes retain their own dialect;
its timestamp conventions do not change.
## Service Matrix
Operation counts are exact. For dispatch-table services (Query and JSON 1.1) each count reflects one case per AWS action in the handler. For REST-based services the count reflects distinct AWS SDK operations, collapsing routes where one JAX-RS handler fans out via query-string or header markers (e.g. `PUT /{bucket}/{key}` → `PutObject`, `PutObjectTagging`, `PutObjectAcl`, etc.). `make docs-check` checks every count against the handlers that serve it, except S3's, which is kept by hand because its handlers pick most operations by query string.
+6
View File
@@ -392,6 +392,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>translate</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
@@ -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);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
package io.floci.aws.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.CBORParser;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.CRC32;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class AwsJsonCborEventStreamIntegrationTest {
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
@ParameterizedTest
@ValueSource(strings = {"application/vnd.amazon.eventstream", "application/cbor"})
void subscribeReturnsFramedCborEventsWithBinaryRecordsAndTaggedDates(String accept) throws Exception {
String stream = "cbor-events-" + UUID.randomUUID();
byte[] content = {0, (byte) 255, 1};
try (KinesisClient kinesis = AwsTestClients.create(KinesisClient.builder(), "test", Region.US_EAST_1)) {
kinesis.createStream(request -> request.streamName(stream).shardCount(1));
String consumer = null;
try {
String arn = kinesis.describeStreamSummary(request -> request.streamName(stream))
.streamDescriptionSummary().streamARN();
consumer = kinesis.registerStreamConsumer(request -> request.streamARN(arn).consumerName("reader"))
.consumer().consumerARN();
kinesis.putRecord(request -> request.streamName(stream).partitionKey("pk")
.data(SdkBytes.fromByteArray(content)));
byte[] request = CBOR.writeValueAsBytes(Map.of("ConsumerARN", consumer,
"ShardId", "shardId-000000000000", "StartingPosition", Map.of("Type", "TRIM_HORIZON")));
byte[] response = given().contentType("application/cbor").accept(accept)
.header("smithy-protocol", "rpc-v2-cbor").body(request)
.post("/service/Kinesis_20131202/operation/SubscribeToShard")
.then().statusCode(200).contentType("application/vnd.amazon.eventstream")
.header("smithy-protocol", "rpc-v2-cbor").extract().asByteArray();
ByteBuffer frames = ByteBuffer.wrap(response);
Frame initial = readFrame(frames);
assertEquals("initial-response", initial.headers().get(":event-type"));
assertEquals("application/cbor", initial.headers().get(":content-type"));
assertTrue(CBOR.readTree(initial.payload()).isEmpty());
Frame event = readFrame(frames);
assertEquals("SubscribeToShardEvent", event.headers().get(":event-type"));
assertEquals("application/cbor", event.headers().get(":content-type"));
JsonNode record = CBOR.readTree(event.payload()).path("Records").get(0);
assertEquals("pk", record.path("PartitionKey").asText());
assertTrue(record.path("Data").isBinary());
assertArrayEquals(content, record.path("Data").binaryValue());
try (CBORParser parser = (CBORParser) CBOR.getFactory().createParser(event.payload())) {
boolean taggedDate = false;
while (parser.nextToken() != null) {
if (parser.currentToken().isNumeric()
&& "ApproximateArrivalTimestamp".equals(parser.currentName())) {
assertEquals(1, parser.getCurrentTag());
taggedDate = true;
}
}
assertTrue(taggedDate);
}
assertFalse(frames.hasRemaining());
} finally {
if (consumer != null) {
String consumerArn = consumer;
kinesis.deregisterStreamConsumer(request -> request.consumerARN(consumerArn));
}
kinesis.deleteStream(request -> request.streamName(stream));
}
}
}
private static Frame readFrame(ByteBuffer frames) {
int start = frames.position();
int length = frames.getInt();
int headersLength = frames.getInt();
CRC32 crc = new CRC32();
crc.update(frames.array(), start, 8);
assertEquals((int) crc.getValue(), frames.getInt(), "prelude checksum");
int headersEnd = frames.position() + headersLength;
Map<String, String> headers = new LinkedHashMap<>();
while (frames.position() < headersEnd) {
String name = readText(frames, Byte.toUnsignedInt(frames.get()));
assertEquals(7, frames.get(), "event header string type");
headers.put(name, readText(frames, Short.toUnsignedInt(frames.getShort())));
}
byte[] payload = new byte[length - headersLength - 16];
frames.get(payload);
crc.reset();
crc.update(frames.array(), start, length - 4);
assertEquals((int) crc.getValue(), frames.getInt(), "message checksum");
return new Frame(headers, payload);
}
private static String readText(ByteBuffer input, int length) {
byte[] bytes = new byte[length];
input.get(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
private record Frame(Map<String, String> headers, byte[] payload) {
}
}
@@ -0,0 +1,231 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class AwsJsonCborServiceRoutingIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final Set<String> JSON_1_0_SERVICES = Set.of(
"dynamodb", "sqs", "sns", "states", "swf", "monitoring", "paymentcryptography",
"cloudcontrol", "network-firewall", "verifiedpermissions", "bcm-pricing-calculator",
"timestream-influxdb");
private static final Map<String, Operation> OPERATIONS = Map.ofEntries(
operation("ssm", "DescribeParameters"),
operation("sqs", "ListQueues"),
operation("dynamodb", "ListTables"),
operation("sns", "ListTopics"),
operation("memorydb", "DescribeClusters"),
operation("redshift-data", "ListStatements"),
operation("redshift-serverless", "ListNamespaces"),
operation("events", "ListRules", "{\"EventBusName\":\"default\"}"),
operation("servicediscovery", "ListNamespaces"),
operation("elasticmapreduce", "ListClusters"),
operation("wafv2", "ListWebACLs", "{\"Scope\":\"REGIONAL\",\"Limit\":10}"),
operation("logs", "DescribeLogGroups"),
operation("monitoring", "ListMetrics"),
operation("paymentcryptography", "ListKeys"),
operation("secretsmanager", "ListSecrets"),
operation("apigatewayv2", "GetApis"),
operation("kinesis", "ListStreams"),
operation("kinesisanalytics", "ListApplications"),
operation("kms", "ListKeys"),
operation("cognito-idp", "ListUserPools", "{\"MaxResults\":10}"),
operation("states", "ListStateMachines"),
operation("swf", "ListDomains", "{\"registrationStatus\":\"REGISTERED\"}"),
operation("acm", "ListCertificates"),
operation("athena", "ListWorkGroups"),
operation("glue", "GetDatabases"),
operation("firehose", "ListDeliveryStreams"),
operation("ecs", "ListClusters"),
operation("ecr", "DescribeRepositories"),
operation("tagging", "GetResources"),
operation("codebuild", "ListProjects"),
operation("sagemaker", "ListModels"),
operation("codedeploy", "ListApplications"),
operation("codepipeline", "ListPipelines"),
operation("servicequotas", "ListServices"),
operation("config", "DescribeConfigRules"),
operation("cloudtrail", "DescribeTrails"),
operation("lightsail", "GetInstances"),
operation("cloudcontrol", "ListResources", "{\"TypeName\":\"AWS::S3::Bucket\"}"),
Map.entry("sso", new Operation("DescribeInstance", "{}", 400)),
operation("identitystore", "ListUsers", "{\"IdentityStoreId\":\"d-9067f2a3c1\"}"),
operation("budgets", "DescribeBudgets", "{\"AccountId\":\"000000000000\"}"),
operation("application-autoscaling", "DescribeScalableTargets", "{\"ServiceNamespace\":\"ecs\"}"),
operation("ec2messages", "GetEndpoint"),
Map.entry("ec2-instance-connect", new Operation("SendSSHPublicKey", "{}", 400)),
operation("transfer", "ListServers"),
Map.entry("textract", new Operation("GetDocumentTextDetection", "{}", 400)),
Map.entry("comprehend", new Operation("DetectSentiment", "{}", 400)),
operation("rekognition", "ListCollections"),
operation("pricing", "DescribeServices"),
operation("transcribe", "ListTranscriptionJobs"),
operation("translate", "ListLanguages"),
operation("ce", "GetAnomalyMonitors"),
operation("cur", "DescribeReportDefinitions"),
Map.entry("bcm-pricing-calculator", new Operation("CreateWorkloadEstimate", "{}", 400)),
operation("timestream-influxdb", "ListDbInstances"),
operation("bcm-data-exports", "ListExports"),
operation("cloudhsmv2", "DescribeClusters"),
Map.entry("organizations", new Operation("DescribeOrganization", "{}", 400)),
operation("route53resolver", "ListResolverEndpoints"),
operation("cognito-identity", "ListIdentityPools", "{\"MaxResults\":10}"),
operation("globalaccelerator", "ListAccelerators"),
operation("datasync", "ListAgents"),
operation("network-firewall", "ListFirewalls"),
operation("servicecatalog", "ListPortfolios"),
operation("verifiedpermissions", "ListPolicyStores", "{\"maxResults\":10}"),
operation("marketplace", "GetEntitlements", "{\"ProductCode\":\"cbor-routing-test\"}"),
operation("dms", "DescribeReplicationInstances"));
@Inject
ResolvedServiceCatalog catalog;
@Test
void everyTargetRoutedJsonServiceHasARegressionCase() {
Set<String> services = catalog.all().stream()
.filter(descriptor -> descriptor.supportsProtocol(ServiceProtocol.JSON))
.filter(descriptor -> !descriptor.targetPrefixes().isEmpty())
.map(ServiceDescriptor::externalKey)
.collect(Collectors.toSet());
assertEquals(services, OPERATIONS.keySet());
}
Stream<String> jsonServices() {
return OPERATIONS.keySet().stream().sorted();
}
@ParameterizedTest(name = "{0} via rpc-v2-cbor")
@MethodSource("jsonServices")
void cborReturnsTheSameServiceResponseAsJson(String service) throws Exception {
ServiceDescriptor descriptor = catalog.byExternalKey(service).orElseThrow();
Operation operation = OPERATIONS.get(service);
String prefix = targetPrefix(descriptor);
String target = prefix + operation.action();
String jsonContentType = JSON_1_0_SERVICES.contains(service)
? "application/x-amz-json-1.0" : "application/x-amz-json-1.1";
Response json = given()
.contentType(jsonContentType)
.header("X-Amz-Target", target)
.body(operation.request().getBytes(StandardCharsets.UTF_8))
.when().post("/");
assertEquals(operation.status(), json.statusCode(), service + " JSON baseline: " + json.asString());
JsonNode jsonBody = JSON.readTree(json.asByteArray());
assertFalse(jsonBody.isEmpty(), service + " must return a service-specific response");
String path = "/service/" + prefix.substring(0, prefix.length() - 1)
+ "/operation/" + operation.action();
Response cbor = given()
.contentType("application/cbor")
.accept("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor")
.body(CBOR.writeValueAsBytes(JSON.readTree(operation.request())))
.when().post(path);
assertEquals(json.statusCode(), cbor.statusCode(), service + " RPC v2 must reach its JSON handler");
assertEquals("application/cbor", cbor.contentType());
assertEquals(jsonBody, CBOR.readTree(cbor.asByteArray()), service + " RPC v2 response");
}
@ParameterizedTest(name = "{0} reaches its Marketplace handler")
@CsvSource({
"AWSMPCommerceService_v20200301, SearchAgreements, application/x-amz-json-1.0",
"AWSMPMeteringService, ResolveCustomer, application/x-amz-json-1.1"
})
void marketplacePrefixesReturnTheirOwnServiceErrors(String serviceId, String action, String contentType)
throws Exception {
Response json = given()
.contentType(contentType)
.header("X-Amz-Target", serviceId + "." + action)
.body("{}".getBytes(StandardCharsets.UTF_8))
.when().post("/");
assertEquals(400, json.statusCode(), "Marketplace JSON baseline: " + json.asString());
JsonNode jsonBody = JSON.readTree(json.asByteArray());
assertFalse(jsonBody.path("__type").asText().contains("UnknownOperation"));
Response cbor = given()
.contentType("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor")
.body(CBOR.writeValueAsBytes(Map.of()))
.when().post("/service/" + serviceId + "/operation/" + action);
assertEquals(json.statusCode(), cbor.statusCode());
assertEquals(jsonBody, CBOR.readTree(cbor.asByteArray()), serviceId + " must select its own handler");
}
@ParameterizedTest
@ValueSource(strings = {"[]", "null", "42", "\"scalar\""})
void genericCborServiceRejectsNonStructureInputs(String payload) throws Exception {
Response response = given()
.contentType("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor")
.body(CBOR.writeValueAsBytes(JSON.readTree(payload)))
.when().post("/service/CodeBuild_20161006/operation/ListProjects");
assertEquals(400, response.statusCode(), "CodeBuild input must be a structure: " + payload);
assertEquals("SerializationException", CBOR.readTree(response.asByteArray()).path("__type").asText());
}
@Test
void unknownRpcV2ServiceStillReturnsAnAwsError() throws Exception {
Response response = given()
.contentType("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor")
.body(CBOR.writeValueAsBytes(Map.of()))
.when().post("/service/UnknownCborService/operation/ListThings");
assertEquals(404, response.statusCode());
assertEquals("UnknownOperationException", CBOR.readTree(response.asByteArray()).path("__type").asText());
}
private static String targetPrefix(ServiceDescriptor descriptor) {
if ("dynamodb".equals(descriptor.externalKey())) {
return "DynamoDB_20120810.";
}
if ("marketplace".equals(descriptor.externalKey())) {
return "AWSMPEntitlementService.";
}
return descriptor.targetPrefixes().stream()
.filter(prefix -> !descriptor.jsonOnlyTargetPrefixes().contains(prefix))
.min(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
.orElseThrow();
}
private static Map.Entry<String, Operation> operation(String service, String action) {
return operation(service, action, "{}");
}
private static Map.Entry<String, Operation> operation(String service, String action, String request) {
return Map.entry(service, new Operation(action, request, 200));
}
private record Operation(String action, String request, int status) {
}
}
@@ -0,0 +1,242 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.core.JsonToken;
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.CBORParser;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
import software.amazon.awssdk.services.apigatewayv2.model.NotFoundException;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.KeyState;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import software.amazon.awssdk.services.translate.TranslateClient;
import software.amazon.awssdk.services.translate.model.TranslateDocumentResponse;
import java.net.URI;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class AwsJsonCborTypedShapesIntegrationTest {
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final byte[] PAYLOAD = {0, (byte) 255, 1, 127, 0};
@TestHTTPResource("/")
URI endpoint;
@Test
void secretsManagerReturnsBinaryBytesAndTaggedCreatedDate() throws Exception {
try (SecretsManagerClient secrets = AwsTestClients.create(SecretsManagerClient.builder(),
"AKID", "secret", Region.US_EAST_1, endpoint)) {
String secretId = secrets.createSecret(request -> request.name("cbor-shapes-" + UUID.randomUUID())
.secretBinary(SdkBytes.fromByteArray(PAYLOAD))).arn();
try {
GetSecretValueResponse expected = secrets.getSecretValue(request -> request.secretId(secretId));
byte[] body = cborCall("secretsmanager", "GetSecretValue", Map.of("SecretId", secretId))
.asByteArray();
assertArrayEquals(PAYLOAD, byteString(body, "SecretBinary"));
assertEquals(1, tagOf(body, "CreatedDate"), "CreatedDate must carry CBOR tag 1");
JsonNode decoded = CBOR.readTree(body);
assertEquals(expected.createdDate().toEpochMilli() / 1000.0,
decoded.path("CreatedDate").asDouble(), 0.001, "timestamps use epoch seconds");
} finally {
secrets.deleteSecret(request -> request.secretId(secretId).forceDeleteWithoutRecovery(true));
}
}
}
@Test
void kmsEncryptAcceptsByteStringsAndReturnsDecryptableByteStrings() throws Exception {
try (KmsClient kms = kmsClient()) {
String keyId = kms.createKey().keyMetadata().keyId();
try {
byte[] request = CBOR.writeValueAsBytes(Map.of("KeyId", keyId, "Plaintext", PAYLOAD));
assertArrayEquals(PAYLOAD, byteString(request, "Plaintext"));
byte[] encrypted = cborCall("TrentService", "Encrypt", request).asByteArray();
byte[] ciphertext = byteString(encrypted, "CiphertextBlob");
assertTrue(ciphertext.length > 0);
assertArrayEquals(PAYLOAD, kms.decrypt(builder -> builder.keyId(keyId)
.ciphertextBlob(SdkBytes.fromByteArray(ciphertext))).plaintext().asByteArray());
} finally {
kms.scheduleKeyDeletion(request -> request.keyId(keyId).pendingWindowInDays(7));
}
}
}
@Test
void kmsDisableKeyHasNoResponseBodyOrContentTypeAndChangesKeyState() throws Exception {
try (KmsClient kms = kmsClient()) {
String keyId = kms.createKey().keyMetadata().keyId();
try {
// Botocore models DisableKey without an output shape, unlike an empty output structure.
Response response = cborCall("TrentService", "DisableKey", Map.of("KeyId", keyId));
assertEquals(KeyState.DISABLED, kms.describeKey(request -> request.keyId(keyId)).keyMetadata().keyState());
assertEquals(0, response.asByteArray().length, "Unit output must have an empty HTTP body");
assertNull(response.header("Content-Type"), "Unit output must omit Content-Type");
} finally {
kms.scheduleKeyDeletion(request -> request.keyId(keyId).pendingWindowInDays(7));
}
}
}
@Test
void apiGatewayV2FacadePreservesUppercaseMembersAndTagsNumericCreatedDate() throws Exception {
try (ApiGatewayV2Client gateway = AwsTestClients.create(ApiGatewayV2Client.builder(),
"AKID", "secret", Region.US_EAST_1, endpoint)) {
String apiId = gateway.createApi(request -> request.name("cbor-api-" + UUID.randomUUID())
.protocolType("HTTP")).apiId();
try {
Instant createdDate = gateway.getApi(request -> request.apiId(apiId)).createdDate();
byte[] body = cborCall("AmazonApiGatewayV2", "GetApi", Map.of("ApiId", apiId)).asByteArray();
JsonNode decoded = CBOR.readTree(body);
assertEquals(apiId, decoded.path("ApiId").asText());
assertFalse(decoded.has("apiId"), "JSON facade members retain their uppercase spelling");
assertTrue(decoded.path("CreatedDate").isNumber(), "facade timestamps use numeric epoch seconds");
assertEquals(1, tagOf(body, "CreatedDate"));
assertEquals(createdDate.toEpochMilli() / 1000.0, decoded.path("CreatedDate").asDouble(), 0.001);
} finally {
gateway.deleteApi(request -> request.apiId(apiId));
}
}
}
@Test
void rpcV2CreateApiReturns200AndCreatesAnApi() throws Exception {
try (ApiGatewayV2Client gateway = AwsTestClients.create(ApiGatewayV2Client.builder(),
"AKID", "secret", Region.US_EAST_1, endpoint)) {
byte[] request = CBOR.writeValueAsBytes(Map.of("Name", "cbor-create-" + UUID.randomUUID(),
"ProtocolType", "HTTP"));
Response response = rawCborCall("AmazonApiGatewayV2", "CreateApi", request);
String apiId = CBOR.readTree(response.asByteArray()).path("ApiId").asText();
try {
assertFalse(apiId.isBlank(), "CreateApi must return the created API identifier");
assertEquals(apiId, gateway.getApi(builder -> builder.apiId(apiId)).apiId());
assertEquals(200, response.statusCode(), "RPC v2 creation succeeds with HTTP 200");
} finally {
if (!apiId.isBlank()) {
gateway.deleteApi(builder -> builder.apiId(apiId));
}
}
}
}
@Test
void rpcV2DeleteApiReturns200AndDeletesTheApi() throws Exception {
try (ApiGatewayV2Client gateway = AwsTestClients.create(ApiGatewayV2Client.builder(),
"AKID", "secret", Region.US_EAST_1, endpoint)) {
String apiId = gateway.createApi(request -> request.name("cbor-delete-" + UUID.randomUUID())
.protocolType("HTTP")).apiId();
try {
Response response = rawCborCall("AmazonApiGatewayV2", "DeleteApi",
CBOR.writeValueAsBytes(Map.of("ApiId", apiId)));
assertThrows(NotFoundException.class, () -> gateway.getApi(request -> request.apiId(apiId)));
assertEquals(200, response.statusCode(), "RPC v2 deletion succeeds with HTTP 200");
} finally {
try {
gateway.deleteApi(request -> request.apiId(apiId));
} catch (NotFoundException expected) {
// DeleteApi under test already removed this fixture.
}
}
}
}
@Test
void translateSdkUsesRpcV2CborAndRoundTripsDocumentBytes() {
AtomicReference<SdkHttpRequest> transmitted = new AtomicReference<>();
ExecutionInterceptor capture = new ExecutionInterceptor() {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes attributes) {
transmitted.set(context.httpRequest());
}
};
try (TranslateClient translate = AwsTestClients.create(TranslateClient.builder()
.overrideConfiguration(config -> config.addExecutionInterceptor(capture)),
"AKID", "secret", Region.US_EAST_1, endpoint)) {
TranslateDocumentResponse response = translate.translateDocument(request -> request
.document(document -> document.content(SdkBytes.fromByteArray(PAYLOAD)).contentType("text/plain"))
.sourceLanguageCode("en").targetLanguageCode("es"));
assertArrayEquals(PAYLOAD, response.translatedDocument().content().asByteArray());
assertEquals("en", response.sourceLanguageCode());
assertEquals("es", response.targetLanguageCode());
SdkHttpRequest request = transmitted.get();
assertNotNull(request, "The real SDK must transmit its marshalled request");
assertEquals("/service/AWSShineFrontendService_20170701/operation/TranslateDocument",
request.getUri().getPath());
assertEquals("rpc-v2-cbor", request.firstMatchingHeader("smithy-protocol").orElse(null));
assertEquals("application/cbor", request.firstMatchingHeader("Content-Type").orElse(null));
}
}
private KmsClient kmsClient() {
return AwsTestClients.create(KmsClient.builder(), "AKID", "secret", Region.US_EAST_1, endpoint);
}
private Response cborCall(String service, String operation, Map<String, ?> request) throws Exception {
return cborCall(service, operation, CBOR.writeValueAsBytes(request));
}
private Response cborCall(String service, String operation, byte[] request) {
Response response = rawCborCall(service, operation, request);
assertEquals(200, response.statusCode(), service + "." + operation + " must reach its service handler");
return response;
}
private Response rawCborCall(String service, String operation, byte[] request) {
return given().baseUri(endpoint.toString()).port(endpoint.getPort())
.contentType("application/cbor").accept("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor").body(request)
.post("/service/" + service + "/operation/" + operation);
}
private static byte[] byteString(byte[] body, String member) throws Exception {
try (CBORParser parser = (CBORParser) CBOR.getFactory().createParser(body)) {
while (parser.nextToken() != null) {
if (parser.currentToken() == JsonToken.FIELD_NAME && member.equals(parser.currentName())) {
assertEquals(JsonToken.VALUE_EMBEDDED_OBJECT, parser.nextToken(), member + " must be binary");
int offset = (int) parser.currentTokenLocation().getByteOffset();
assertEquals(2, (body[offset] & 0xff) >>> 5, member + " must use CBOR major type 2");
return parser.getBinaryValue();
}
}
}
throw new AssertionError("Missing CBOR member: " + member);
}
private static int tagOf(byte[] body, String member) throws Exception {
try (CBORParser parser = (CBORParser) CBOR.getFactory().createParser(body)) {
while (parser.nextToken() != null) {
if (member.equals(parser.currentName()) && parser.currentToken().isScalarValue()) {
return parser.getCurrentTag();
}
}
}
throw new AssertionError("Missing CBOR member: " + member);
}
}
@@ -0,0 +1,120 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import com.fasterxml.jackson.dataformat.cbor.CBORParser;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RpcV2CborCodecTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final String MODEL = """
{
"aliases":{"TestService":"test","TestAlias":"test"},
"services":{"test":{
"operations":{"RoundTrip":{"input":"Payload","output":"Payload","hasOutput":true}},
"shapes":{
"Payload":{"type":"structure","members":{
"Body":{"shape":"Blob"},"Nested":{"shape":"Nested"},
"CreatedDate":{"shape":"Time"},
"IsoCreated":{"shape":"Time","timestampFormat":"iso8601"},
"DefaultIso":{"shape":"IsoTime"},
"EpochOverride":{"shape":"IsoTime","timestampFormat":"unixTimestamp"},
"UserStrings":{"shape":"Strings"},"UserNumbers":{"shape":"Numbers"}}},
"Nested":{"type":"structure","members":{
"Items":{"shape":"Blobs"},"Lookup":{"shape":"BlobMap"}}},
"Blob":{"type":"blob"},"Time":{"type":"timestamp"},
"IsoTime":{"type":"timestamp","timestampFormat":"iso8601"},
"Blobs":{"type":"list","member":"Blob"},
"BlobMap":{"type":"map","value":"Blob"},
"Strings":{"type":"map","value":"Text"},
"Numbers":{"type":"map","value":"Number"},
"Text":{"type":"string"},"Number":{"type":"double"}
}
}}
}
""";
@Test
void blobsRoundTripThroughStructuresListsAndMapsWithoutMutatingPayloads() throws Exception {
RpcV2CborCodec codec = RpcV2CborCodec.parse(JSON.readTree(MODEL));
JsonNode original = JSON.readTree("""
{"Body":"AP8B","Nested":{"Items":["AQID","BAU="],"Lookup":{"Data":"Bgc="}},
"UserStrings":{"Data":"AQID","Timestamp":"1700000000"}}
""");
JsonNode snapshot = original.deepCopy();
JsonNode wire = CBOR.readTree(codec.encodeResponse("TestService", "RoundTrip", original));
assertTrue(wire.path("Body").isBinary());
assertArrayEquals(new byte[]{0, (byte) 255, 1}, wire.path("Body").binaryValue());
assertArrayEquals(new byte[]{1, 2, 3}, wire.at("/Nested/Items/0").binaryValue());
assertArrayEquals(new byte[]{4, 5}, wire.at("/Nested/Items/1").binaryValue());
assertArrayEquals(new byte[]{6, 7}, wire.at("/Nested/Lookup/Data").binaryValue());
assertTrue(wire.at("/UserStrings/Data").isTextual());
assertEquals(snapshot, original, "Encoding must not rewrite the JSON handler's payload");
JsonNode wireSnapshot = wire.deepCopy();
assertEquals(original, codec.decodeRequest("TestAlias", "RoundTrip", wire));
assertEquals(wireSnapshot, wire, "Decoding must not rewrite the caller's CBOR tree");
}
@Test
void modelTimestampsUseEpochSecondsTagOneIncludingIsoFormatOverrides() throws Exception {
RpcV2CborCodec codec = RpcV2CborCodec.parse(JSON.readTree(MODEL));
JsonNode response = JSON.readTree("""
{"CreatedDate":1700000000.125,"IsoCreated":"2023-11-14T22:13:20.125Z",
"DefaultIso":"2023-11-14T22:13:20.125Z","EpochOverride":1700000000.125,
"UserNumbers":{"Timestamp":1700000000},"UserStrings":{"Data":"AQID"}}
""");
JsonNode snapshot = response.deepCopy();
byte[] encoded = codec.encodeResponse("TestAlias", "RoundTrip", response);
JsonNode wire = CBOR.readTree(encoded);
for (String member : new String[]{"CreatedDate", "IsoCreated", "DefaultIso", "EpochOverride"}) {
assertEquals(1, tagOf(encoded, member), member + " must carry CBOR tag 1");
assertEquals(0, new BigDecimal("1700000000.125").compareTo(wire.path(member).decimalValue()));
}
assertEquals(-1, tagOf(encoded, "Timestamp"), "A user map key must not imply a timestamp shape");
assertTrue(wire.at("/UserStrings/Data").isTextual());
assertEquals(snapshot, response);
}
@Test
void requestTimestampsAdaptToTheJsonModelsFormatWithoutLosingFractionalSeconds() throws Exception {
RpcV2CborCodec codec = RpcV2CborCodec.parse(JSON.readTree(MODEL));
ObjectNode request = JSON.createObjectNode();
for (String member : new String[]{"CreatedDate", "IsoCreated", "DefaultIso", "EpochOverride"}) {
request.put(member, 1700000000.125);
}
JsonNode snapshot = request.deepCopy();
JsonNode decoded = codec.decodeRequest("TestService", "RoundTrip", request);
assertEquals("2023-11-14T22:13:20.125Z", decoded.path("IsoCreated").asText());
assertEquals("2023-11-14T22:13:20.125Z", decoded.path("DefaultIso").asText());
assertEquals(1700000000.125, decoded.path("CreatedDate").asDouble());
assertEquals(1700000000.125, decoded.path("EpochOverride").asDouble());
assertEquals(snapshot, request);
}
private static int tagOf(byte[] bytes, String member) throws Exception {
try (CBORParser parser = (CBORParser) CBOR.getFactory().createParser(bytes)) {
while (parser.nextToken() != null) {
if (member.equals(parser.currentName()) && parser.currentToken().isScalarValue()) {
return parser.getCurrentTag();
}
}
}
throw new AssertionError("Missing CBOR member: " + member);
}
}
@@ -91,11 +91,17 @@ class PaymentCryptographyCardValidationOperationsTest {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
Map<String, Object> generated = cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(), "PrimaryAccountNumber", PAN,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1");
String value = (String) generated.get("ValidationData");
String wrongValue = (value.charAt(0) - '0' + 1) % 10 + value.substring(1);
AwsException refused = assertThrows(AwsException.class, () -> cardValidation.verify(
PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationData", "999",
"ValidationData", wrongValue,
"VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))),
"us-east-1"));
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Vendor RPC v2 blob/timestamp shapes from the repository-pinned botocore models.
Only ancestors of wire-sensitive leaves are retained. Ordinary fields are copied verbatim by
RpcV2CborCodec. The API Gateway V2 JSON facade uses Smithy names and numeric dates, unlike its REST model.
"""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
from regen_partitions import load_model, resolve_botocore_data, service_model, strip_source
from request_shapes import REPO_ROOT
CATALOG = REPO_ROOT / "src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java"
OUTPUT = REPO_ROOT / "src/main/resources/aws/rpcv2-cbor-shapes.json"
JSON_ONLY_PREFIXES = {"DynamoDB_20111205", "CloudWatchVersion20130116"}
# Floci's JSON facades/short alias do not use the model's targetPrefix.
MODEL_ALIASES = {"AmazonApiGatewayV2": "apigatewayv2", "CloudTrail_20131101": "cloudtrail",
"SNS_20100331": "sns"}
AGENT_PREFIX = "AmazonSSMMessageDeliveryService"
# The agent facade has no pinned botocore model. MDS Message fields, including CreatedDate and Payload, are strings.
# aws/amazon-ssm-agent agent/runcommand/mds/mdsservice.go, immutable blob:
# https://api.github.com/repos/aws/amazon-ssm-agent/git/blobs/f3e4d67147e5027ca2568d597077e56310921610
def project_model(model: dict, json_facade: bool = False) -> dict:
shapes = model["shapes"]
kept = {name for name, shape in shapes.items() if shape["type"] in {"blob", "timestamp"}}
while True:
before = len(kept)
for name, shape in shapes.items():
kind = shape["type"]
if kind == "structure":
members = shape.get("members", {})
if any(spec["shape"] in kept or (not json_facade and spec.get("locationName", member) != member)
for member, spec in members.items()):
kept.add(name)
elif kind in {"list", "map"}:
spec = shape["member" if kind == "list" else "value"]
if spec["shape"] in kept:
kept.add(name)
if len(kept) == before:
break
projected = {}
for name in sorted(kept):
shape = shapes[name]
kind = shape["type"]
entry = {"type": kind}
if "timestampFormat" in shape and not json_facade:
entry["timestampFormat"] = shape["timestampFormat"]
if kind == "structure":
members = {}
for member, spec in shape.get("members", {}).items():
json_name = member if json_facade else spec.get("locationName", member)
if spec["shape"] not in kept and json_name == member:
continue
item = {"shape": spec["shape"] if spec["shape"] in kept else None}
if json_name != member:
item["jsonName"] = json_name
if "timestampFormat" in spec and not json_facade:
item["timestampFormat"] = spec["timestampFormat"]
members[member] = item
entry["members"] = members
elif kind in {"list", "map"}:
key = "member" if kind == "list" else "value"
entry[key] = shape[key]["shape"]
projected[name] = entry
operations = {}
for name, operation in sorted(model["operations"].items()):
roots = {direction: operation.get(direction, {}).get("shape") for direction in ("input", "output")}
entry = {key: root if root in kept else None for key, root in roots.items()}
entry["hasOutput"] = "output" in operation
output = shapes.get(roots["output"], {})
for member in output.get("members", {}).values():
if shapes[member["shape"]].get("eventstream"):
entry["eventStream"] = member["shape"]
if entry != {"input": None, "output": None, "hasOutput": True}:
operations[name] = entry
return {"timestampFormat": "iso8601" if not json_facade and model["metadata"].get("protocol") in {"rest-json", "query"}
else "unixTimestamp", "operations": operations, "shapes": projected}
def build(data: Path, catalog: Path, provenance: str) -> dict:
prefixes = set(re.findall(r'"([A-Za-z0-9_.-]+)\."', catalog.read_text())) - JSON_ONLY_PREFIXES
models = {}
for directory in sorted(path for path in data.iterdir() if path.is_dir()):
files = [source for version in sorted(directory.iterdir(), reverse=True) if version.is_dir()
if (source := service_model(version)) is not None]
if files:
models[directory.name] = load_model(files[0])
selected = {name for name, model in models.items() if model["metadata"].get("targetPrefix") in prefixes}
selected.update(name for prefix, name in MODEL_ALIASES.items() if prefix in prefixes)
services = {name: project_model(models[name], json_facade=name == "apigatewayv2") for name in sorted(selected)}
aliases = {}
for name in sorted(selected):
metadata = models[name]["metadata"]
for alias in (metadata.get("targetPrefix"), metadata.get("serviceId")):
if alias:
if alias in aliases and aliases[alias] != name:
raise ValueError(f"Ambiguous RPC v2 service alias: {alias}")
aliases[alias] = name
aliases.update({prefix: name for prefix, name in MODEL_ALIASES.items() if prefix in prefixes})
aliases["AWS Marketplace Entitlement Service"] = "marketplace-entitlement"
services["ec2messages"] = {"timestampFormat": "unixTimestamp", "shapes": {}, "operations": {}}
aliases[AGENT_PREFIX] = "ec2messages"
missing = prefixes - aliases.keys()
if missing:
raise ValueError(f"No RPC v2 wire model for catalog prefixes: {sorted(missing)}")
return {"_source": {"generator": "tools/aws/regen_rpcv2_cbor_shapes.py", "botocore": provenance,
"ec2messages": "aws/amazon-ssm-agent agent/runcommand/mds/mdsservice.go blob f3e4d67147e5027ca2568d597077e56310921610"},
"aliases": dict(sorted(aliases.items())), "services": dict(sorted(services.items()))}
def render(document: dict) -> str:
"""Keep each alias, operation and shape on one line, like the other vendored wire models."""
lines = ["{", f' "_source": {json.dumps(document["_source"])},', ' "aliases": {']
aliases = list(document["aliases"].items())
for index, (name, service) in enumerate(aliases):
comma = "," if index < len(aliases) - 1 else ""
lines.append(f" {json.dumps(name)}: {json.dumps(service)}{comma}")
lines += [" },", ' "services": {']
services = list(document["services"].items())
for index, (name, service) in enumerate(services):
lines.append(f" {json.dumps(name)}: {{")
lines.append(f' "timestampFormat": {json.dumps(service["timestampFormat"])},')
for group in ("operations", "shapes"):
lines.append(f" {json.dumps(group)}: {{")
entries = list(service[group].items())
for position, (key, value) in enumerate(entries):
comma = "," if position < len(entries) - 1 else ""
lines.append(f" {json.dumps(key)}: {json.dumps(value)}{comma}")
lines.append(" }" + ("," if group == "operations" else ""))
lines.append(" }" + ("," if index < len(services) - 1 else ""))
lines += [" }", "}"]
return "\n".join(lines) + "\n"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--botocore-data", type=Path)
parser.add_argument("--catalog", type=Path, default=CATALOG)
parser.add_argument("--output", type=Path, default=OUTPUT)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
data, provenance = resolve_botocore_data(args.botocore_data)
result = build(data, args.catalog, provenance)
if args.check:
if strip_source(args.output.read_text()) != strip_source(json.dumps(result)):
print(f"error: {args.output} is stale; run tools/aws/regen_rpcv2_cbor_shapes.py")
return 1
else:
args.output.write_text(render(result))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+83
View File
@@ -0,0 +1,83 @@
from regen_rpcv2_cbor_shapes import project_model
def model(shapes, operations=None, protocol="json"):
return {"metadata": {"protocol": protocol}, "shapes": shapes,
"operations": operations or {"Read": {"input": {"shape": "Root"}, "output": {"shape": "Root"}}}}
def test_projection_keeps_typed_leaves_and_their_containers_only():
result = project_model(model({
"Root": {"type": "structure", "members": {"Files": {"shape": "Files"}, "Name": {"shape": "Text"}}},
"Files": {"type": "list", "member": {"shape": "Lookup"}},
"Lookup": {"type": "map", "value": {"shape": "Blob"}},
"Blob": {"type": "blob"}, "Text": {"type": "string"}}))
assert set(result["shapes"]) == {"Root", "Files", "Lookup", "Blob"}
assert result["shapes"]["Root"]["members"] == {"Files": {"shape": "Files"}}
assert result["operations"]["Read"] == {"input": "Root", "output": "Root", "hasOutput": True}
def test_recursive_shape_projection_terminates_and_retains_typed_descendants():
result = project_model(model({
"Root": {"type": "structure", "members": {"Child": {"shape": "List"}, "Data": {"shape": "Blob"}}},
"List": {"type": "list", "member": {"shape": "Root"}}, "Blob": {"type": "blob"}}))
assert set(result["shapes"]) == {"Root", "List", "Blob"}
assert result["shapes"]["List"]["member"] == "Root"
def test_projection_preserves_json_member_names_and_timestamp_overrides():
result = project_model(model({
"Root": {"type": "structure", "members": {
"When": {"shape": "Date", "timestampFormat": "unixTimestamp", "locationName": "when"}}},
"Date": {"type": "timestamp", "timestampFormat": "iso8601"}}, protocol="rest-json"))
assert result["timestampFormat"] == "iso8601"
assert result["shapes"]["Date"]["timestampFormat"] == "iso8601"
assert result["shapes"]["Root"]["members"]["When"] == {
"shape": "Date", "timestampFormat": "unixTimestamp", "jsonName": "when"}
def test_an_ordinary_output_without_special_types_is_not_unit():
result = project_model(model({"Root": {"type": "structure", "members": {}}}, {
"Read": {"output": {"shape": "Root"}}, "Delete": {}}))
assert "Read" not in result["operations"]
assert result["operations"]["Delete"] == {"input": None, "output": None, "hasOutput": False}
def test_api_gateway_json_facade_preserves_member_names_and_numeric_dates():
result = project_model(model({
"Root": {"type": "structure", "members": {
"ApiId": {"shape": "Text", "locationName": "apiId"},
"CreatedDate": {"shape": "Date", "locationName": "createdDate"}}},
"Text": {"type": "string"},
"Date": {"type": "timestamp", "timestampFormat": "iso8601"}}, protocol="rest-json"), json_facade=True)
assert result["timestampFormat"] == "unixTimestamp"
assert result["shapes"]["Date"] == {"type": "timestamp"}
assert result["shapes"]["Root"]["members"] == {"CreatedDate": {"shape": "Date"}}
def test_check_command_ignores_provenance_and_detects_data_drift(tmp_path, monkeypatch):
import json
import sys
import regen_rpcv2_cbor_shapes as generator
output = tmp_path / "wire.json"
expected = {"_source": {"botocore": "new"}, "aliases": {"Service": "test"}, "services": {}}
output.write_text(json.dumps({**expected, "_source": {"botocore": "old"}}))
monkeypatch.setattr(sys, "argv", ["regen_rpcv2_cbor_shapes.py", "--check", "--output", str(output)])
monkeypatch.setattr(generator, "resolve_botocore_data", lambda unused: (tmp_path, "new"))
monkeypatch.setattr(generator, "build", lambda *unused: expected)
assert generator.main() == 0
output.write_text(json.dumps({**expected, "aliases": {}}))
assert generator.main() == 1
def test_projection_records_the_output_event_stream_union():
result = project_model(model({
"Root": {"type": "structure", "members": {"Events": {"shape": "Events"}}},
"Events": {"type": "structure", "eventstream": True,
"members": {"DataEvent": {"shape": "Event"}}},
"Event": {"type": "structure", "members": {"Data": {"shape": "Blob"}}},
"Blob": {"type": "blob"}}))
assert result["operations"]["Read"]["eventStream"] == "Events"
assert result["shapes"]["Events"]["members"]["DataEvent"]["shape"] == "Event"