mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(kinesis): honour DryRun on PutRecord, PutRecords, GetShardIterator, GetRecords and SubscribeToShard (#9409)
Kinesis's PutRecord, PutRecords, GetShardIterator, GetRecords and SubscribeToShard take DryRun, and Floci ignored it, so a dry-run PutRecord wrote the record. Each now makes the checks AWS makes for a dry run (the model constraints, the stream or consumer and the iterator, but not the shard) and answers DryRunOperationException, writing nothing. DryRun is read as Kinesis's deserializer reads it, a string such as "yes" included, through JsonBooleanCoercion.fromJson, which KMS now shares. Part of #8220
This commit is contained in:
1 parent
b85b0a8966
commit
01a42399b0
5 files changed
+226
-26
No files matched your search
@@ -1,5 +1,7 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/** The boolean a JSON string names, as AWS's JSON protocol deserializers read one. */
|
||||
@@ -23,4 +25,27 @@ public final class JsonBooleanCoercion {
|
||||
"STRING_VALUE can not be converted to an Boolean", 400);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The boolean member {@code node} holds, false when it is absent or null, as KMS's and Kinesis's deserializers
|
||||
* read one (measured on AWS): a JSON boolean, or a string as {@link #fromString} reads it. A number, list or
|
||||
* object is refused with the deserializer's {@code SerializationException}; the services word a decimal
|
||||
* differently, so the caller gives that message.
|
||||
*/
|
||||
public static boolean fromJson(JsonNode node, String decimalMessage) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (node.isBoolean()) {
|
||||
return node.booleanValue();
|
||||
}
|
||||
if (node.isTextual()) {
|
||||
return fromString(node.textValue());
|
||||
}
|
||||
String message = node.isIntegralNumber() ? "NUMBER_VALUE can not be converted to a Boolean"
|
||||
: node.isNumber() ? decimalMessage
|
||||
: node.isArray() ? "Start of list found where not expected"
|
||||
: "Start of structure or map found where not expected.";
|
||||
throw new AwsException("SerializationException", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.AwsEventStreamEncoder;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.Base64Url;
|
||||
import io.floci.aws.core.common.EpochSeconds;
|
||||
import io.floci.aws.core.common.JsonBooleanCoercion;
|
||||
import io.floci.aws.services.kinesis.model.KinesisConsumer;
|
||||
import io.floci.aws.services.kinesis.model.KinesisRecord;
|
||||
import io.floci.aws.services.kinesis.model.KinesisShard;
|
||||
@@ -53,7 +54,17 @@ public class KinesisJsonHandler {
|
||||
this.nextTokenTtlMillis = nextTokenTtlMillis;
|
||||
}
|
||||
|
||||
/**
|
||||
* The operations whose request takes {@code DryRun}. A dry run is checked as the call is, up to what AWS checks
|
||||
* for one (the stream or consumer, the records, the iterator, but not the shard), and then answered with
|
||||
* DryRunOperationException, changing and returning nothing.
|
||||
*/
|
||||
private static final Set<String> DRY_RUN_OPERATIONS =
|
||||
Set.of("PutRecord", "PutRecords", "GetShardIterator", "GetRecords", "SubscribeToShard");
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
boolean dryRun = DRY_RUN_OPERATIONS.contains(action) && JsonBooleanCoercion.fromJson(request.path("DryRun"),
|
||||
"NUMBER_VALUE can not be converted to a Boolean");
|
||||
Supplier<Response> operation = switch (action) {
|
||||
case "CreateStream" -> () -> handleCreateStream(request, region);
|
||||
case "DeleteStream" -> () -> handleDeleteStream(request, region);
|
||||
@@ -64,7 +75,7 @@ public class KinesisJsonHandler {
|
||||
case "DeregisterStreamConsumer" -> () -> handleDeregisterStreamConsumer(request, region);
|
||||
case "DescribeStreamConsumer" -> () -> handleDescribeStreamConsumer(request, region);
|
||||
case "ListStreamConsumers" -> () -> handleListStreamConsumers(request, region);
|
||||
case "SubscribeToShard" -> () -> handleSubscribeToShard(request, region);
|
||||
case "SubscribeToShard" -> () -> handleSubscribeToShard(request, region, dryRun);
|
||||
case "AddTagsToStream" -> () -> handleAddTagsToStream(request, region);
|
||||
case "RemoveTagsFromStream" -> () -> handleRemoveTagsFromStream(request, region);
|
||||
case "ListTagsForStream" -> () -> handleListTagsForStream(request, region);
|
||||
@@ -75,10 +86,10 @@ public class KinesisJsonHandler {
|
||||
case "StopStreamEncryption" -> () -> handleStopStreamEncryption(request, region);
|
||||
case "SplitShard" -> () -> handleSplitShard(request, region);
|
||||
case "MergeShards" -> () -> handleMergeShards(request, region);
|
||||
case "PutRecord" -> () -> handlePutRecord(request, region);
|
||||
case "PutRecords" -> () -> handlePutRecords(request, region);
|
||||
case "GetShardIterator" -> () -> handleGetShardIterator(request, region);
|
||||
case "GetRecords" -> () -> handleGetRecords(request, region);
|
||||
case "PutRecord" -> () -> handlePutRecord(request, region, dryRun);
|
||||
case "PutRecords" -> () -> handlePutRecords(request, region, dryRun);
|
||||
case "GetShardIterator" -> () -> handleGetShardIterator(request, region, dryRun);
|
||||
case "GetRecords" -> () -> handleGetRecords(request, region, dryRun);
|
||||
case "ListShards" -> () -> handleListShards(request, region);
|
||||
case "IncreaseStreamRetentionPeriod" -> () -> handleIncreaseStreamRetentionPeriod(request, region);
|
||||
case "DecreaseStreamRetentionPeriod" -> () -> handleDecreaseStreamRetentionPeriod(request, region);
|
||||
@@ -94,7 +105,9 @@ public class KinesisJsonHandler {
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
}
|
||||
KinesisRequestShapes.check(action, request);
|
||||
// DryRun was read above as Kinesis's deserializer reads it, a string such as "yes" included, which the
|
||||
// modeled type check would refuse.
|
||||
KinesisRequestShapes.check(action, dryRunRead(action, request));
|
||||
return operation.get();
|
||||
}
|
||||
|
||||
@@ -383,7 +396,7 @@ public class KinesisJsonHandler {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Response handleSubscribeToShard(JsonNode request, String region) {
|
||||
private Response handleSubscribeToShard(JsonNode request, String region, boolean dryRun) {
|
||||
String consumerArn = request.path("ConsumerARN").asText(null);
|
||||
String shardId = request.path("ShardId").asText(null);
|
||||
JsonNode startPos = request.path("StartingPosition");
|
||||
@@ -393,6 +406,9 @@ public class KinesisJsonHandler {
|
||||
? Math.round(startPos.path("Timestamp").asDouble() * 1000) : null;
|
||||
|
||||
KinesisConsumer consumer = service.describeStreamConsumer(null, null, consumerArn, region);
|
||||
if (dryRun) {
|
||||
throw KinesisService.dryRunOperation("SubscribeToShard");
|
||||
}
|
||||
String streamName = parseStreamNameFromArn(consumer.getStreamArn());
|
||||
|
||||
String shardIterator = service.getShardIterator(streamName, shardId, startType, seqNumber, timestampMs, region);
|
||||
@@ -577,7 +593,16 @@ public class KinesisJsonHandler {
|
||||
return explicitHashKeyNode.asText();
|
||||
}
|
||||
|
||||
private Response handlePutRecord(JsonNode request, String region) {
|
||||
private static JsonNode dryRunRead(String action, JsonNode request) {
|
||||
if (!DRY_RUN_OPERATIONS.contains(action) || !(request instanceof ObjectNode object) || !object.has("DryRun")) {
|
||||
return request;
|
||||
}
|
||||
ObjectNode checked = object.deepCopy();
|
||||
checked.remove("DryRun");
|
||||
return checked;
|
||||
}
|
||||
|
||||
private Response handlePutRecord(JsonNode request, String region, boolean dryRun) {
|
||||
String streamName = resolveStreamName(request);
|
||||
JsonNode dataNode = request.path("Data");
|
||||
// The CBOR transports (the AWS SDK for Java's default for Kinesis) decode Data
|
||||
@@ -593,6 +618,10 @@ public class KinesisJsonHandler {
|
||||
}
|
||||
String partitionKey = request.path("PartitionKey").asText();
|
||||
String explicitHashKey = readExplicitHashKey(request);
|
||||
if (dryRun) {
|
||||
service.checkPutRecord(streamName, data, partitionKey, explicitHashKey, region);
|
||||
throw KinesisService.dryRunOperation("PutRecord");
|
||||
}
|
||||
|
||||
KinesisService.PutRecordResult result = service.putRecordWithShardId(
|
||||
streamName, data, partitionKey, explicitHashKey, region);
|
||||
@@ -603,7 +632,7 @@ public class KinesisJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutRecords(JsonNode request, String region) {
|
||||
private Response handlePutRecords(JsonNode request, String region, boolean dryRun) {
|
||||
String streamName = resolveStreamName(request);
|
||||
KinesisStream stream = service.describeStream(streamName, region);
|
||||
JsonNode recordsNode = request.path("Records");
|
||||
@@ -647,6 +676,9 @@ public class KinesisJsonHandler {
|
||||
service.validateRequestSize(totalBytes);
|
||||
entries.add(new Entry(node, data, explicitHashKey));
|
||||
}
|
||||
if (dryRun) {
|
||||
throw KinesisService.dryRunOperation("PutRecords");
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode results = response.putArray("Records");
|
||||
@@ -679,7 +711,7 @@ public class KinesisJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetShardIterator(JsonNode request, String region) {
|
||||
private Response handleGetShardIterator(JsonNode request, String region, boolean dryRun) {
|
||||
String streamName = resolveStreamName(request);
|
||||
String shardId = request.path("ShardId").asText();
|
||||
String type = request.path("ShardIteratorType").asText();
|
||||
@@ -700,6 +732,11 @@ public class KinesisJsonHandler {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"ShardIteratorType AT_TIMESTAMP requires a Timestamp", 400);
|
||||
}
|
||||
if (dryRun) {
|
||||
// AWS checks the stream for a dry run, but not the shard (measured).
|
||||
service.describeStream(streamName, region);
|
||||
throw KinesisService.dryRunOperation("GetShardIterator");
|
||||
}
|
||||
|
||||
String iterator = service.getShardIterator(streamName, shardId, type, seq, timestampMillis, region);
|
||||
|
||||
@@ -709,11 +746,16 @@ public class KinesisJsonHandler {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Response handleGetRecords(JsonNode request, String region) {
|
||||
private Response handleGetRecords(JsonNode request, String region, boolean dryRun) {
|
||||
String iterator = request.path("ShardIterator").asText();
|
||||
Integer limit = request.has("Limit") ? request.path("Limit").asInt() : null;
|
||||
|
||||
// Reading changes nothing, so a dry run reads, refusing an invalid iterator as the call does, and answers
|
||||
// in place of the records.
|
||||
Map<String, Object> result = service.getRecords(iterator, limit, region);
|
||||
if (dryRun) {
|
||||
throw KinesisService.dryRunOperation("GetRecords");
|
||||
}
|
||||
List<KinesisRecord> records = (List<KinesisRecord>) result.get("Records");
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
|
||||
@@ -1222,6 +1222,24 @@ public class KinesisService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The checks PutRecord makes before it appends, for a dry run: the stream exists and takes writes, and the
|
||||
* explicit hash key and the record's size are valid.
|
||||
*/
|
||||
public void checkPutRecord(String streamName, byte[] data, String partitionKey, String explicitHashKey,
|
||||
String region) {
|
||||
KinesisStream stream = resolveStream(streamName, region);
|
||||
requireWritableStream(stream);
|
||||
validateExplicitHashKey(explicitHashKey);
|
||||
validateRecordSize(stream, data, partitionKey);
|
||||
}
|
||||
|
||||
/** What a dry run of {@code operation} answers when the call would have succeeded (measured on AWS). */
|
||||
static AwsException dryRunOperation(String operation) {
|
||||
return new AwsException("DryRunOperationException", "DryRunOperation validation succeeded while calling "
|
||||
+ operation + " operation.: Request would have succeeded, but DryRun flag is set.", 400);
|
||||
}
|
||||
|
||||
public String getShardIterator(String streamName, String shardId, String type, String sequenceNumber, String region) {
|
||||
return getShardIterator(streamName, shardId, type, sequenceNumber, null, region);
|
||||
}
|
||||
|
||||
@@ -386,21 +386,7 @@ public class KmsJsonHandler {
|
||||
* false. Any other value is refused with the deserializer's SerializationException.
|
||||
*/
|
||||
private static boolean dryRun(JsonNode request) {
|
||||
JsonNode node = request.path("DryRun");
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (node.isBoolean()) {
|
||||
return node.booleanValue();
|
||||
}
|
||||
if (node.isTextual()) {
|
||||
return JsonBooleanCoercion.fromString(node.textValue());
|
||||
}
|
||||
String message = node.isIntegralNumber() ? "NUMBER_VALUE can not be converted to a Boolean"
|
||||
: node.isNumber() ? "DECIMAL_VALUE cannot be converted to Boolean"
|
||||
: node.isArray() ? "Start of list found where not expected"
|
||||
: "Start of structure or map found where not expected.";
|
||||
throw new AwsException("SerializationException", message, 400);
|
||||
return JsonBooleanCoercion.fromJson(request.path("DryRun"), "DECIMAL_VALUE cannot be converted to Boolean");
|
||||
}
|
||||
|
||||
/** The result of a call that changes nothing, or DryRunOperationException in its place for a dry run. */
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package io.floci.aws.services.kinesis;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** Kinesis DryRun, as measured on AWS: checked as the call is, answered DryRunOperationException, nothing changed. */
|
||||
class KinesisDryRunTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String STREAM = "dry";
|
||||
private static final String STREAM_ARN = "arn:aws:kinesis:us-east-1:123456789012:stream/dry";
|
||||
private static final String SHARD = "shardId-000000000000";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private KinesisService service;
|
||||
private KinesisJsonHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT));
|
||||
handler = new KinesisJsonHandler(service, MAPPER, 300_000);
|
||||
handler.handle("CreateStream", MAPPER.createObjectNode().put("StreamName", STREAM).put("ShardCount", 1), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dryRunPutsAreAnsweredAsAwsDoesAndWriteNothing() {
|
||||
assertDryRun("PutRecord", putRecord(STREAM, "k"));
|
||||
ObjectNode puts = MAPPER.createObjectNode().put("StreamName", STREAM).put("DryRun", true);
|
||||
puts.putArray("Records").addObject().put("Data", data()).put("PartitionKey", "k");
|
||||
assertDryRun("PutRecords", puts);
|
||||
|
||||
ObjectNode iterator = MAPPER.createObjectNode().put("StreamName", STREAM).put("ShardId", SHARD)
|
||||
.put("ShardIteratorType", "TRIM_HORIZON");
|
||||
String cursor = ((ObjectNode) handler.handle("GetShardIterator", iterator, REGION).getEntity())
|
||||
.path("ShardIterator").asText();
|
||||
ObjectNode page = (ObjectNode) handler.handle("GetRecords", MAPPER.createObjectNode().put("ShardIterator", cursor),
|
||||
REGION).getEntity();
|
||||
assertEquals(0, page.path("Records").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dryRunReadsAreAnsweredInPlaceOfTheirResult() {
|
||||
assertDryRun("GetShardIterator", MAPPER.createObjectNode().put("StreamName", STREAM).put("ShardId", SHARD)
|
||||
.put("ShardIteratorType", "TRIM_HORIZON").put("DryRun", true));
|
||||
String cursor = service.getShardIterator(STREAM, SHARD, "TRIM_HORIZON", null, null, REGION);
|
||||
assertDryRun("GetRecords", MAPPER.createObjectNode().put("ShardIterator", cursor).put("DryRun", true));
|
||||
String consumer = service.registerStreamConsumer(STREAM_ARN, "dry-consumer", REGION).getConsumerArn();
|
||||
ObjectNode subscribe = MAPPER.createObjectNode().put("ConsumerARN", consumer).put("ShardId", SHARD)
|
||||
.put("DryRun", true);
|
||||
subscribe.putObject("StartingPosition").put("Type", "LATEST");
|
||||
assertDryRun("SubscribeToShard", subscribe);
|
||||
}
|
||||
|
||||
/** Measured: the stream is checked, the shard isn't. */
|
||||
@Test
|
||||
void aDryRunChecksTheStreamButNotTheShard() {
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecord", putRecord("absent", "k"), REGION));
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
assertDryRun("GetShardIterator", MAPPER.createObjectNode().put("StreamName", STREAM)
|
||||
.put("ShardId", "shardId-000000000009").put("ShardIteratorType", "TRIM_HORIZON").put("DryRun", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDryRunOfARequestTheCallRefusesIsRefusedAlike() {
|
||||
AwsException dryRun = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecord", putRecord(STREAM, ""), REGION));
|
||||
AwsException call = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutRecord", putRecord(STREAM, "").put("DryRun", false), REGION));
|
||||
assertEquals(call.getErrorCode(), dryRun.getErrorCode());
|
||||
assertEquals(call.getMessage(), dryRun.getMessage());
|
||||
AwsException badIterator = assertThrows(AwsException.class, () -> handler.handle("GetRecords",
|
||||
MAPPER.createObjectNode().put("ShardIterator", "not-an-iterator").put("DryRun", true), REGION));
|
||||
assertEquals("InvalidArgumentException", badIterator.getErrorCode());
|
||||
}
|
||||
|
||||
/** Kinesis's deserializer reads DryRun as KMS's does, but words a decimal as a number (measured). */
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"\"maybe\"|STRING_VALUE can not be converted to an Boolean",
|
||||
"1|NUMBER_VALUE can not be converted to a Boolean",
|
||||
"1.5|NUMBER_VALUE can not be converted to a Boolean",
|
||||
"[]|Start of list found where not expected",
|
||||
"{}|Start of structure or map found where not expected."})
|
||||
void aDryRunThatIsNoBooleanIsRefusedAsAwsRefusesIt(String json, String message) throws Exception {
|
||||
ObjectNode request = putRecord(STREAM, "k");
|
||||
request.set("DryRun", MAPPER.readTree(json));
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.handle("PutRecord", request, REGION));
|
||||
|
||||
assertEquals("SerializationException", refused.getErrorCode());
|
||||
assertEquals(message, refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDryRunNamedByAStringIsADryRun() {
|
||||
ObjectNode request = putRecord(STREAM, "k").put("DryRun", "yes");
|
||||
assertDryRun("PutRecord", request);
|
||||
}
|
||||
|
||||
private void assertDryRun(String operation, ObjectNode request) {
|
||||
AwsException dryRun = assertThrows(AwsException.class, () -> handler.handle(operation, request, REGION));
|
||||
assertEquals("DryRunOperationException", dryRun.getErrorCode());
|
||||
assertEquals("DryRunOperation validation succeeded while calling " + operation
|
||||
+ " operation.: Request would have succeeded, but DryRun flag is set.", dryRun.getMessage());
|
||||
}
|
||||
|
||||
private static ObjectNode putRecord(String stream, String partitionKey) {
|
||||
return MAPPER.createObjectNode().put("StreamName", stream).put("PartitionKey", partitionKey)
|
||||
.put("Data", data()).put("DryRun", true);
|
||||
}
|
||||
|
||||
private static String data() {
|
||||
return Base64.getEncoder().encodeToString("hi".getBytes());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user