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
@@ -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);
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -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"));
|
||||
|
||||
|
||||
Reference in new issue
Block a user