fix(cloudformation): apply KinesisStreamSpecification on AWS::DynamoDB::Table (#7464)

* fix(cloudformation): apply KinesisStreamSpecification on AWS::DynamoDB::Table

The property was accepted and ignored, so a stack that declared it got a
table whose item changes never reached the stream.

The declared stream becomes the table's active Kinesis streaming
destination on create and update. Removing a block the previous template
declared turns it off, and a stack that never declared it leaves
destinations set outside it alone. The in-place update snapshot of a
stack that manages the destinations records them, so a failed update
puts them back as they were.

A change of ApproximateCreationDateTimePrecision alone updates the active
destination in place, as CloudFormation does with one
UpdateKinesisStreamingDestination call, so forwarding never stops and
records already captured are still delivered.

A block that is not an object fails template validation, as
TimeToLiveSpecification does, rather than reading as a removed block
that turns forwarding off.

A StreamArn the destination cannot use fails the table as the AWS handler
does, and the table this attempt created is deleted. One under 37
characters fails EnableKinesisStreamingDestination's validation. One that
is not a Kinesis stream ARN, such as the stream name Ref returns, or one
naming a stream that does not exist fails as NotStabilized.

DynamoDbTableAccess gains enable, disable and update operations for the
destination. DynamoDB Local has no Kinesis forwarding, so that backend
leaves the table as it is and logs a warning. CloudFormation still checks
StreamArn there as AWS does; only the forwarding is skipped.

* fix(cloudformation): match Kinesis destinations by their whole stream ARN

A destination was looked up by the last segment of its StreamArn in the
table's account and region, so an ARN for another account, region or
resource type that ended in a local stream's name forwarded to that
stream. KinesisService.describeStreamByArn now finds a stream only by its
exact ARN. NativeDynamoDbTableService uses it, so the public
EnableKinesisStreamingDestination action reports such an ARN as not
found, and CloudFormation fails the table as NotStabilized.

The DynamoDB Local backend looks the stream up the same way before it
skips forwarding, so a template naming a missing stream fails there too.

A declared StreamArn the table already forwards to now goes through the
same template checks as a new one; only the rollback restore skips them.
This commit is contained in:
mokamoto12 authored and GitHub committed 2026-11-03 23:10:27 -04:00
1 parent a026c8a94c
commit 8b756a3467
19 files changed
+1096 -31

No files matched your search

@@ -78,7 +78,7 @@ class IamConditionContextResolverTest {
@BeforeEach
void setUp() {
dynamoDbService = mock(DynamoDbService.class);
NativeDynamoDbBackend dynamoDbBackend = new NativeDynamoDbBackend(null, null, dynamoDbService, null, null, mapper);
NativeDynamoDbBackend dynamoDbBackend = new NativeDynamoDbBackend(null, null, null, dynamoDbService, null, null, mapper);
dynamoDbFacadeInstance = mock(Instance.class);
when(dynamoDbFacadeInstance.isResolvable()).thenReturn(true);
when(dynamoDbFacadeInstance.get()).thenReturn(new DynamoDbFacade(dynamoDbBackend, dynamoDbBackend,
@@ -341,7 +341,7 @@ final class CfnProvisionerFixture {
discovered.add(new SesReceiptRuleCfnProvisioner(sesReceiptRuleService, sesIdentityService));
}
if (dynamoDbService != null) {
NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDbService, null, null, objectMapper);
NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, null, dynamoDbService, null, null, objectMapper);
discovered.add(new DynamoDbCfnProvisioner(new DynamoDbFacade(backend, backend,
new RegionResolver("us-east-1", "000000000000"))));
}
@@ -0,0 +1,261 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.dynamodb.KinesisStreamingForwarder;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.function.Function;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* {@code KinesisStreamSpecification} on {@code AWS::DynamoDB::Table}: a stack that declares it gets
* a table whose item changes reach the declared Kinesis stream, an update that removes the block
* turns the destination off, and a stream that does not exist fails the create without leaving the
* table behind.
*/
@QuarkusTest
class CloudFormationDynamoDbKinesisStreamSpecificationIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String DDB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/dynamodb/aws4_request";
private static final String KINESIS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/kinesis/aws4_request";
private static final String TEMPLATE = """
{
"Resources": {
"Events": {
"Type": "AWS::Kinesis::Stream",
"Properties": {"Name": "%s", "ShardCount": 1}
},
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"BillingMode": "PAY_PER_REQUEST"%s
}
}
}
}
""";
private static final String FORWARDED =
",\n\"KinesisStreamSpecification\": {\"StreamArn\": {\"Fn::GetAtt\": [\"Events\", \"Arn\"]}}";
private final ObjectMapper mapper = new ObjectMapper();
@Inject
KinesisStreamingForwarder forwarder;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createForwardsItemChangesToTheDeclaredStream() throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-kds-" + suffix;
String stream = "kds-events-" + suffix;
String table = "kds-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(stream, table, FORWARDED));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
dynamoDb("DescribeKinesisStreamingDestination", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("KinesisDataStreamDestinations.size()", equalTo(1))
.body("KinesisDataStreamDestinations[0].StreamArn", containsString(":stream/" + stream))
.body("KinesisDataStreamDestinations[0].DestinationStatus", equalTo("ACTIVE"));
dynamoDb("PutItem", "{\"TableName\": \"" + table + "\", \"Item\": {\"pk\": {\"S\": \"k1\"}}}")
.statusCode(200);
forwarder.awaitIdle(Duration.ofSeconds(5));
List<String> records = kinesisRecords(stream);
assertFalse(records.isEmpty(), "Expected the PutItem to reach " + stream);
JsonNode payload = mapper.readTree(Base64.getDecoder().decode(records.get(0)));
assertEquals("INSERT", payload.path("eventName").asText());
assertEquals(table, payload.path("tableName").asText());
deleteStack(stack);
}
@Test
void removingTheBlockDisablesTheDestination() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-kds-rm-" + suffix;
String stream = "kds-rm-events-" + suffix;
String table = "kds-rm-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(stream, table, FORWARDED));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(stream, table, ""));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
dynamoDb("DescribeKinesisStreamingDestination", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("KinesisDataStreamDestinations[0].DestinationStatus", equalTo("DISABLED"));
deleteStack(stack);
}
/** A block that is not an object is refused, not read as a removed block that turns forwarding off. */
@Test
void anUpdateWithABlockThatIsNotAnObjectKeepsTheDestinationActive() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-kds-scalar-" + suffix;
String stream = "kds-scalar-events-" + suffix;
String table = "kds-scalar-table-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(stream, table, FORWARDED));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
cloudFormation(stack, "UpdateStack",
TEMPLATE.formatted(stream, table, ",\n\"KinesisStreamSpecification\": [\"off\"]"));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertEquals("Property [KinesisStreamSpecification] expected type: JSONObject, found: JSONArray",
CfnStackWaits.failedResourceReason(stack, CFN_AUTH));
dynamoDb("DescribeKinesisStreamingDestination", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("KinesisDataStreamDestinations.size()", equalTo(1))
.body("KinesisDataStreamDestinations[0].DestinationStatus", equalTo("ACTIVE"));
deleteStack(stack);
}
@Test
void changingThePrecisionKeepsForwardingToTheSameStream() throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-kds-prec-" + suffix;
String stream = "kds-prec-events-" + suffix;
String table = "kds-prec-table-" + suffix;
String microsecond = ",\n\"KinesisStreamSpecification\": {\"StreamArn\": {\"Fn::GetAtt\": [\"Events\", \"Arn\"]},"
+ " \"ApproximateCreationDateTimePrecision\": \"MICROSECOND\"}";
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(stream, table, FORWARDED));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
dynamoDb("PutItem", "{\"TableName\": \"" + table + "\", \"Item\": {\"pk\": {\"S\": \"before\"}}}")
.statusCode(200);
cloudFormation(stack, "UpdateStack", TEMPLATE.formatted(stream, table, microsecond));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
dynamoDb("DescribeKinesisStreamingDestination", "{\"TableName\": \"" + table + "\"}")
.statusCode(200)
.body("KinesisDataStreamDestinations.size()", equalTo(1))
.body("KinesisDataStreamDestinations[0].DestinationStatus", equalTo("ACTIVE"))
.body("KinesisDataStreamDestinations[0].ApproximateCreationDateTimePrecision", equalTo("MICROSECOND"));
dynamoDb("PutItem", "{\"TableName\": \"" + table + "\", \"Item\": {\"pk\": {\"S\": \"after\"}}}")
.statusCode(200);
forwarder.awaitIdle(Duration.ofSeconds(5));
List<String> records = kinesisRecords(stream);
assertEquals(2, records.size(), "Both writes reach " + stream);
JsonNode before = mapper.readTree(Base64.getDecoder().decode(records.get(0))).path("dynamodb");
JsonNode after = mapper.readTree(Base64.getDecoder().decode(records.get(1))).path("dynamodb");
assertEquals("before", before.path("Keys").path("pk").path("S").asText());
assertEquals(13, Long.toString(before.path("ApproximateCreationDateTime").asLong()).length());
assertEquals("after", after.path("Keys").path("pk").path("S").asText());
assertEquals(16, Long.toString(after.path("ApproximateCreationDateTime").asLong()).length());
deleteStack(stack);
}
@Test
void aStreamThatDoesNotExistFailsTheCreateAndLeavesNoTable() {
assertCreateDoesNotStabilizeAndLeavesNoTable("missing", suffix -> "\"arn:aws:kinesis:us-east-1:000000000000"
+ ":stream/no-such-stream-" + suffix + "\"");
}
/** Ref of an AWS::Kinesis::Stream is the stream's name, which AWS never makes a destination. */
@Test
void aStreamNameFromRefFailsTheCreateAndLeavesNoTable() {
assertCreateDoesNotStabilizeAndLeavesNoTable("ref", suffix -> "{\"Ref\": \"Events\"}");
}
private void assertCreateDoesNotStabilizeAndLeavesNoTable(String label, Function<String, String> streamArn) {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-ddb-kds-" + label + "-" + suffix;
String stream = "kds-" + label + "-events-name-long-enough-" + suffix;
String table = "kds-" + label + "-table-" + suffix;
String spec = ",\n\"KinesisStreamSpecification\": {\"StreamArn\": " + streamArn.apply(suffix) + "}";
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(stream, table, spec));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());
assertEquals("Resource of type 'AWS::DynamoDB::Table' with identifier '" + table + "' did not stabilize.",
CfnStackWaits.failedResourceReason(stack, CFN_AUTH));
dynamoDb("DescribeTable", "{\"TableName\": \"" + table + "\"}")
.statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
deleteStack(stack);
}
private List<String> kinesisRecords(String stream) {
String shardIterator = kinesis("GetShardIterator", "{\"StreamName\": \"" + stream + "\","
+ " \"ShardId\": \"shardId-000000000000\", \"ShardIteratorType\": \"TRIM_HORIZON\"}")
.statusCode(200)
.extract().path("ShardIterator");
return kinesis("GetRecords", "{\"ShardIterator\": \"" + shardIterator + "\", \"Limit\": 10}")
.statusCode(200)
.extract().path("Records.Data");
}
private void cloudFormation(String stack, String action, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack)
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
}
private void deleteStack(String stack) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
}
private ValidatableResponse dynamoDb(String action, String body) {
return given()
.contentType("application/x-amz-json-1.0")
.header("Authorization", DDB_AUTH)
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.body(body)
.when().post("/").then();
}
private ValidatableResponse kinesis(String action, String body) {
return given()
.contentType("application/x-amz-json-1.1")
.header("Authorization", KINESIS_AUTH)
.header("X-Amz-Target", "Kinesis_20131202." + action)
.body(body)
.when().post("/").then();
}
}
@@ -41,7 +41,8 @@ import static org.mockito.Mockito.when;
* {@code TimeToLiveSpecification} reconcile, and the snapshot a failed table update rolls back
* from. The stream and replica
* behaviour keeps its own coverage in {@code DynamoDbStreamSpecificationCfnProvisionerTest} and
* {@code DynamoDbReplicaCfnProvisionerTest}, which reach this class through the fixture.
* {@code DynamoDbReplicaCfnProvisionerTest}, which reach this class through the fixture, and
* {@code KinesisStreamSpecification} in {@code DynamoDbKinesisStreamSpecificationCfnProvisionerTest}.
*/
class DynamoDbCfnProvisionerTest {
@@ -54,7 +55,7 @@ class DynamoDbCfnProvisionerTest {
private final DynamoDbService dynamoDb = mock(DynamoDbService.class);
private final ObjectMapper mapper = new ObjectMapper();
private final NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, dynamoDb, null, null, mapper);
private final NativeDynamoDbBackend backend = new NativeDynamoDbBackend(null, null, null, dynamoDb, null, null, mapper);
private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(
new DynamoDbFacade(backend, backend, new RegionResolver("us-east-1", "000000000000")));
@@ -0,0 +1,407 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService;
import io.github.hectorvent.floci.services.dynamodb.backend.NativeDynamoDbBackend;
import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* {@code KinesisStreamSpecification} on {@code AWS::DynamoDB::Table}: the declared stream becomes
* the table's active Kinesis streaming destination on create and update, removing the block turns
* it off, and a failed in-place update puts the previous destinations back.
*/
class DynamoDbKinesisStreamSpecificationCfnProvisionerTest {
private static final String REGION = "us-east-1";
private static final String TABLE_NAME = "orders";
private static final String TABLE_ARN = "arn:aws:dynamodb:us-east-1:000000000000:table/" + TABLE_NAME;
private static final String STREAM_ARN = "arn:aws:kinesis:us-east-1:000000000000:stream/orders-events";
private static final String OTHER_STREAM_ARN = "arn:aws:kinesis:us-east-1:000000000000:stream/orders-audit";
private static final String MILLISECOND = KinesisStreamingDestination.PRECISION_MILLISECOND;
private static final String MICROSECOND = KinesisStreamingDestination.PRECISION_MICROSECOND;
private static final String DECLARED = "{\"TableName\":\"orders\",\"KinesisStreamSpecification\":"
+ "{\"StreamArn\":\"" + STREAM_ARN + "\"}}";
private static final String DECLARED_MICROSECOND = "{\"TableName\":\"orders\",\"KinesisStreamSpecification\":"
+ "{\"StreamArn\":\"" + STREAM_ARN + "\",\"ApproximateCreationDateTimePrecision\":\"MICROSECOND\"}}";
private static final String DECLARED_OTHER = "{\"TableName\":\"orders\",\"KinesisStreamSpecification\":"
+ "{\"StreamArn\":\"" + OTHER_STREAM_ARN + "\"}}";
private static final String UNDECLARED = "{\"TableName\":\"orders\"}";
private final DynamoDbService dynamoDb = mock(DynamoDbService.class);
private final NativeDynamoDbTableService tableService = mock(NativeDynamoDbTableService.class);
private final ObjectMapper mapper = new ObjectMapper();
private final NativeDynamoDbBackend backend =
new NativeDynamoDbBackend(null, null, tableService, dynamoDb, null, null, mapper);
private final DynamoDbCfnProvisioner provisioner = new DynamoDbCfnProvisioner(
new DynamoDbFacade(backend, backend, new RegionResolver(REGION, "000000000000")));
private ProvisionContext ctx() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, REGION, "000000000000", "my-stack");
}
private ProvisionContext updateCtx(String priorProperties) throws Exception {
ProvisionContext create = ctx();
return new ProvisionContext(create.engine(), create.region(), create.accountId(),
create.stackName(), TABLE_NAME, event -> { }, props(priorProperties));
}
private JsonNode props(String json) throws Exception {
return mapper.readTree(json);
}
private StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("Orders");
r.setResourceType("AWS::DynamoDB::Table");
r.setAttributes(new HashMap<>());
return r;
}
private StackResource existingResource() {
StackResource r = resource();
r.setPhysicalId(TABLE_NAME);
r.getAttributes().put("Arn", TABLE_ARN);
return r;
}
private static TableDefinition table(KinesisStreamingDestination... destinations) {
TableDefinition table = new TableDefinition();
table.setTableName(TABLE_NAME);
table.setTableArn(TABLE_ARN);
table.setKinesisStreamingDestinations(List.of(destinations));
return table;
}
private static KinesisStreamingDestination active(String streamArn, String precision) {
return new KinesisStreamingDestination(streamArn, precision);
}
private void newTable() {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenReturn(table());
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table());
}
private void existingTable(TableDefinition current) {
when(dynamoDb.createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(), anyString()))
.thenThrow(new AwsException("ResourceInUseException", "Table already exists", 400));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(current);
}
@Test
void createEnablesTheDeclaredDestinationWithMillisecondPrecisionByDefault() throws Exception {
newTable();
provisioner.provision(resource(), props(DECLARED), ctx());
verify(tableService).enableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MILLISECOND, REGION);
}
@Test
void createHonoursTheDeclaredPrecision() throws Exception {
newTable();
provisioner.provision(resource(), props(DECLARED_MICROSECOND), ctx());
verify(tableService).enableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MICROSECOND, REGION);
}
@Test
void createWithoutTheBlockTouchesNoDestination() throws Exception {
newTable();
provisioner.provision(resource(), props(UNDECLARED), ctx());
verifyNoInteractions(tableService);
}
@Test
void blockWithoutAStreamArnFailsModelValidationBeforeTheTableIsCreated() throws Exception {
StackResource r = resource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":{}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
verify(dynamoDb, never()).createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(),
anyString());
}
@Test
void unknownPrecisionFailsModelValidationBeforeTheTableIsCreated() throws Exception {
StackResource r = resource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":"
+ "{\"StreamArn\":\"" + STREAM_ARN + "\",\"ApproximateCreationDateTimePrecision\":\"SECOND\"}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
verify(dynamoDb, never()).createTable(anyString(), anyList(), anyList(), any(), any(), anyList(), anyList(),
anyString());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {"false|String", "[]|JSONArray"})
void blockThatIsNotAnObjectFailsTemplateValidationBeforeTheTableIsCreated(String value, String found)
throws Exception {
StackResource r = resource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":" + value + "}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("ValidationError", e.getErrorCode());
assertEquals("Property [KinesisStreamSpecification] expected type: JSONObject, found: " + found,
e.getMessage());
verifyNoInteractions(dynamoDb, tableService);
}
@Test
void updateWithABlockThatIsNotAnObjectLeavesTheDeclaredDestinationActive() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
StackResource r = existingResource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":\"off\"}");
ProvisionContext ctx = updateCtx(DECLARED);
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
verifyNoInteractions(tableService);
}
/**
* A stream that does not exist never becomes the active destination, so AWS fails the table as
* NotStabilized inside its own provision, and the new table is not left behind.
*/
@Test
void createWhoseStreamDoesNotExistFailsAsNotStabilizedAndDeletesTheTable() throws Exception {
newTable();
doThrow(new AwsException("ResourceNotFoundException", "Kinesis stream not found: " + STREAM_ARN, 400))
.when(tableService).enableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MILLISECOND, REGION);
StackResource r = resource();
JsonNode props = props(DECLARED);
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("NotStabilized", e.getErrorCode());
assertEquals("Resource of type 'AWS::DynamoDB::Table' with identifier 'orders' did not stabilize.",
e.getMessage());
verify(dynamoDb).deleteTable(TABLE_NAME, REGION);
}
/** A stream's name, which {@code Ref} of an AWS::Kinesis::Stream returns, is not its ARN. */
@Test
void createWithAStreamNameInsteadOfItsArnFailsAsNotStabilizedAndDeletesTheTable() throws Exception {
newTable();
StackResource r = resource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":"
+ "{\"StreamArn\":\"orders-events-stream-name-long-enough-1\"}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("NotStabilized", e.getErrorCode());
verifyNoInteractions(tableService);
verify(dynamoDb).deleteTable(TABLE_NAME, REGION);
}
/**
* EnableKinesisStreamingDestination rejects a StreamArn under 37 characters with its own
* validation. An empty one is present, so it passes model validation and fails the same check.
*/
@ParameterizedTest
@ValueSource(strings = {"kds-short", ""})
void createWithAStreamArnUnder37CharactersFailsTheApiValidationAndDeletesTheTable(String streamArn)
throws Exception {
newTable();
StackResource r = resource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":"
+ "{\"StreamArn\":\"" + streamArn + "\"}}");
ProvisionContext ctx = ctx();
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("1 validation error detected: Value '" + streamArn + "' at 'streamArn' failed to satisfy"
+ " constraint: Member must have length greater than or equal to 37", e.getMessage());
verifyNoInteractions(tableService);
verify(dynamoDb).deleteTable(TABLE_NAME, REGION);
}
@Test
void updateWithTheSameDestinationMakesNoDestinationCall() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
provisioner.provision(existingResource(), props(DECLARED), updateCtx(DECLARED));
verifyNoInteractions(tableService);
}
/** A destination set through the API with a stream name does not let a template declare that name. */
@Test
void updateDeclaringAStreamArnTheTableAlreadyForwardsToStillChecksIt() throws Exception {
existingTable(table(active("events", MILLISECOND)));
StackResource r = existingResource();
JsonNode props = props("{\"TableName\":\"orders\",\"KinesisStreamSpecification\":{\"StreamArn\":\"events\"}}");
ProvisionContext ctx = updateCtx(UNDECLARED);
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
assertEquals("InvalidRequest", e.getErrorCode());
verifyNoInteractions(tableService);
}
@Test
void updateThatRemovesTheBlockDisablesTheDestination() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
provisioner.provision(existingResource(), props(UNDECLARED), updateCtx(DECLARED));
verify(tableService).disableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, REGION);
}
/** A destination enabled outside a stack that never declared the property survives its updates. */
@Test
void updateOfAStackThatNeverDeclaredTheBlockLeavesDestinationsAlone() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
provisioner.provision(existingResource(), props(UNDECLARED), updateCtx(UNDECLARED));
verifyNoInteractions(tableService);
}
@Test
void updateToAnotherStreamMovesTheDestination() throws Exception {
existingTable(table(active(OTHER_STREAM_ARN, MILLISECOND)));
provisioner.provision(existingResource(), props(DECLARED), updateCtx(DECLARED_OTHER));
verify(tableService).disableKinesisStreamingDestination(TABLE_NAME, OTHER_STREAM_ARN, REGION);
verify(tableService).enableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MILLISECOND, REGION);
}
/**
* CloudFormation changes the precision with one UpdateKinesisStreamingDestination call, so the
* destination stays active and nothing it already captured is discarded.
*/
@Test
void updateThatChangesThePrecisionUpdatesTheDestinationInPlace() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
provisioner.provision(existingResource(), props(DECLARED_MICROSECOND), updateCtx(DECLARED));
verify(tableService).updateKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MICROSECOND, REGION);
verifyNoMoreInteractions(tableService);
}
@Test
void rollbackUpdatePutsThePreviousDestinationBack() throws Exception {
existingTable(table(active(OTHER_STREAM_ARN, MILLISECOND)));
StackResource r = existingResource();
provisioner.provision(r, props(DECLARED), updateCtx(DECLARED_OTHER));
// The table as the update left it: forwarding to the newly declared stream only.
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(active(STREAM_ARN, MILLISECOND)));
assertTrue(provisioner.rollbackUpdate(r));
verify(tableService).disableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, REGION);
verify(tableService).enableKinesisStreamingDestination(TABLE_NAME, OTHER_STREAM_ARN, MILLISECOND, REGION);
assertFalse(r.getAttributes().containsKey(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR));
}
@Test
void rollbackOfAPrecisionChangePutsThePreviousPrecisionBackInPlace() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
StackResource r = existingResource();
provisioner.provision(r, props(DECLARED_MICROSECOND), updateCtx(DECLARED));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(active(STREAM_ARN, MICROSECOND)));
assertTrue(provisioner.rollbackUpdate(r));
verify(tableService).updateKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MICROSECOND, REGION);
verify(tableService).updateKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, MILLISECOND, REGION);
verifyNoMoreInteractions(tableService);
}
/**
* The template checks are for a newly declared StreamArn. A destination the table already had,
* here one set through the API with a stream name, is put back as it was.
*/
@Test
void rollbackRestoresAPriorDestinationWithoutTheTemplateChecks() throws Exception {
existingTable(table(active("events", MILLISECOND)));
StackResource r = existingResource();
provisioner.provision(r, props(DECLARED), updateCtx(UNDECLARED));
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(active(STREAM_ARN, MILLISECOND)));
assertTrue(provisioner.rollbackUpdate(r));
verify(tableService).disableKinesisStreamingDestination(TABLE_NAME, STREAM_ARN, REGION);
verify(tableService).enableKinesisStreamingDestination(TABLE_NAME, "events", MILLISECOND, REGION);
}
@Test
void rollbackOfAStackThatNeverDeclaredTheBlockLeavesDestinationsAlone() throws Exception {
existingTable(table(active(STREAM_ARN, MILLISECOND)));
StackResource r = existingResource();
provisioner.provision(r, props(UNDECLARED), updateCtx(UNDECLARED));
// A destination set outside the stack while the update ran.
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(active(OTHER_STREAM_ARN, MILLISECOND)));
assertTrue(provisioner.rollbackUpdate(r));
verifyNoInteractions(tableService);
}
/** A snapshot an earlier version took, without the destinations, leaves them as they are. */
@Test
void rollbackOfASnapshotWithoutDestinationsLeavesThemAlone() {
when(dynamoDb.describeTable(TABLE_NAME, REGION)).thenReturn(table(active(STREAM_ARN, MILLISECOND)));
StackResource r = existingResource();
r.getAttributes().put(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR, "{\"accountId\":\"000000000000\","
+ "\"region\":\"us-east-1\",\"tableName\":\"orders\",\"tags\":{},\"streamEnabled\":false,"
+ "\"streamViewType\":null,\"ttlEnabled\":false,\"ttlAttributeName\":null}");
assertTrue(provisioner.rollbackUpdate(r));
verifyNoInteractions(tableService);
}
}
@@ -37,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -346,7 +347,7 @@ class NativeDynamoDbTableServiceTest {
assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND,
resolved.approximateCreationDateTimePrecision(),
"the snapshot carries the precision the response echoes");
verify(kinesisService).describeStream(STREAM_NAME, REGION);
verify(kinesisService).describeStreamByArn(STREAM_ARN, REGION);
KinesisStreamingDestination enabled = reloadFromDisk().findKinesisStreamingDestination(STREAM_ARN)
.orElseThrow();
assertEquals("ACTIVE", enabled.getDestinationStatus());
@@ -384,11 +385,50 @@ class NativeDynamoDbTableServiceTest {
"re-enabling reuses the existing destination");
}
@Test
void updatingAKinesisDestinationChangesItsPrecisionWithoutDisablingIt() {
tableService.createTable(createRequest(null, NO_SETTINGS), "ACTIVE", REGION);
tableService.enableKinesisStreamingDestination(
TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MILLISECOND, REGION);
NativeDynamoDbTableService.KinesisDestination updated = tableService.updateKinesisStreamingDestination(
TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MICROSECOND, REGION);
assertEquals("ACTIVE", updated.destinationStatus());
assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND, updated.approximateCreationDateTimePrecision());
KinesisStreamingDestination persisted = reloadFromDisk().findKinesisStreamingDestination(STREAM_ARN)
.orElseThrow();
assertEquals("ACTIVE", persisted.getDestinationStatus());
assertEquals(KinesisStreamingDestination.PRECISION_MICROSECOND,
persisted.getApproximateCreationDateTimePrecision());
verify(forwarder, never()).onDestinationDisabled(ACCOUNT, REGION, TABLE, STREAM_ARN);
}
@Test
void updatingADisabledOrUnknownKinesisDestinationIsRejected() {
tableService.createTable(createRequest(null, NO_SETTINGS), "ACTIVE", REGION);
AwsException unknown = assertThrows(AwsException.class, () -> tableService.updateKinesisStreamingDestination(
TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MICROSECOND, REGION));
assertEquals("ResourceNotFoundException", unknown.getErrorCode());
tableService.enableKinesisStreamingDestination(
TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MILLISECOND, REGION);
tableService.disableKinesisStreamingDestination(TABLE, STREAM_ARN, REGION);
assertValidationFailure(() -> tableService.updateKinesisStreamingDestination(
TABLE, STREAM_ARN, KinesisStreamingDestination.PRECISION_MICROSECOND, REGION),
"Kinesis streaming destination is not active for stream: " + STREAM_ARN);
assertEquals(KinesisStreamingDestination.PRECISION_MILLISECOND,
reloadFromDisk().findKinesisStreamingDestination(STREAM_ARN).orElseThrow()
.getApproximateCreationDateTimePrecision());
}
@Test
void unknownKinesisStreamIsReportedAsNotFound() {
tableService.createTable(createRequest(null, NO_SETTINGS), "ACTIVE", REGION);
String missingArn = "arn:aws:kinesis:us-east-1:000000000000:stream/missing";
when(kinesisService.describeStream("missing", REGION))
when(kinesisService.describeStreamByArn(missingArn, REGION))
.thenThrow(new AwsException("ResourceNotFoundException", "Stream missing not found", 400));
AwsException ex = assertThrows(AwsException.class, () -> tableService.enableKinesisStreamingDestination(
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -62,6 +63,7 @@ class DynamoDbLocalBackendTest {
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
private final DynamoDbLocalClient client = mock(DynamoDbLocalClient.class);
private final KinesisService kinesisService = mock(KinesisService.class);
private final AccountAwareStorageBackend<Map<String, String>> tags =
AccountAwareStorageBackend.inMemory("000000000000");
private DynamoDbLocalBackend backend;
@@ -69,7 +71,7 @@ class DynamoDbLocalBackendTest {
@BeforeEach
void setUp() {
when(client.endpoint()).thenReturn(URI.create("http://local:8000"));
backend = new DynamoDbLocalBackend(client, tags, mapper, Duration.ofSeconds(5));
backend = new DynamoDbLocalBackend(client, tags, kinesisService, mapper, Duration.ofSeconds(5));
}
private JsonNode json(String text) throws IOException {
@@ -495,6 +497,39 @@ class DynamoDbLocalBackendTest {
neverSent("UpdateTable");
}
@Test
void kinesisDestinationCallsLeaveTheTableAsItIs() throws Exception {
answerOrdersTable();
String streamArn = "arn:aws:kinesis:" + REGION + ":" + ACCOUNT + ":stream/orders-events";
TableDefinition enabled = backend.enableKinesisStreamingDestination(SCOPE, "orders", streamArn, "MILLISECOND");
TableDefinition updated = backend.updateKinesisStreamingDestination(SCOPE, "orders", streamArn, "MICROSECOND");
TableDefinition disabled = backend.disableKinesisStreamingDestination(SCOPE, "orders", streamArn);
for (TableDefinition table : List.of(enabled, updated, disabled)) {
assertEquals("orders", table.getTableName());
assertTrue(table.getKinesisStreamingDestinations().isEmpty());
}
verify(kinesisService).describeStreamByArn(streamArn, REGION);
neverSent("EnableKinesisStreamingDestination");
neverSent("UpdateKinesisStreamingDestination");
neverSent("DisableKinesisStreamingDestination");
}
@Test
void enablingADestinationWhoseStreamDoesNotExistIsReportedAsNotFound() throws Exception {
String streamArn = "arn:aws:kinesis:" + REGION + ":" + ACCOUNT + ":stream/missing";
when(kinesisService.describeStreamByArn(streamArn, REGION))
.thenThrow(new AwsException("ResourceNotFoundException", "Stream missing not found", 400));
AwsException e = assertThrows(AwsException.class,
() -> backend.enableKinesisStreamingDestination(SCOPE, "orders", streamArn, "MILLISECOND"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
assertEquals("Kinesis stream not found: " + streamArn, e.getMessage());
neverSent("DescribeTable");
}
@Test
void ensureGlobalTableDescribes() throws Exception {
answerOrdersTable();
@@ -770,7 +805,7 @@ class DynamoDbLocalBackendTest {
@Test
void startFailsWhenBudgetExpires() throws Exception {
backend = new DynamoDbLocalBackend(client, tags, mapper, Duration.ZERO);
backend = new DynamoDbLocalBackend(client, tags, kinesisService, mapper, Duration.ZERO);
when(client.send(any(), any(), any(), any(), any())).thenThrow(new ConnectException("refused"));
IllegalStateException error = assertThrows(IllegalStateException.class, backend::start);
@@ -76,7 +76,7 @@ class DynamoDbNativeBackendTest {
NativeDynamoDbTableService tables = new NativeDynamoDbTableService(service, streams, mock(KinesisService.class));
backend = new NativeDynamoDbBackend(new NativeDynamoDbJsonHandler(service, tables, mapper),
new NativeDynamoDbStreamsJsonHandler(streams, service, new RegionResolver(REGION, ACCOUNT), mapper),
service, streams, ttl, mapper);
tables, service, streams, ttl, mapper);
}
private Reply call(Api api, String action, JsonNode body) throws Exception {
@@ -116,6 +116,23 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
return record("disableStream", scope);
}
@Override
public TableDefinition enableKinesisStreamingDestination(Scope scope, String tableName, String streamArn,
String precision) {
return record("enableKinesisStreamingDestination", scope);
}
@Override
public TableDefinition disableKinesisStreamingDestination(Scope scope, String tableName, String streamArn) {
return record("disableKinesisStreamingDestination", scope);
}
@Override
public TableDefinition updateKinesisStreamingDestination(Scope scope, String tableName, String streamArn,
String precision) {
return record("updateKinesisStreamingDestination", scope);
}
@Override
public TimeToLive timeToLive(Scope scope, String tableName) {
record("timeToLive", scope);
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
@@ -98,6 +99,29 @@ class KinesisServiceTest {
kinesisService.describeStream("missing", REGION));
}
@Test
void describeStreamByArnFindsTheStreamWithThatExactArn() {
KinesisStream created = kinesisService.createStream("orders-events", 1, REGION);
assertEquals(created.getStreamArn(),
kinesisService.describeStreamByArn(created.getStreamArn(), REGION).getStreamArn());
}
@ParameterizedTest
@ValueSource(strings = {
"orders-events",
"arn:aws:kinesis:eu-west-1:000000000000:stream/orders-events",
"arn:aws:kinesis:us-east-1:111111111111:stream/orders-events",
"arn:aws:kinesis:us-east-1:000000000000:not-a-stream/orders-events"
})
void describeStreamByArnNamesNoStreamForAnotherIdentityWithTheSameName(String streamArn) {
kinesisService.createStream("orders-events", 1, REGION);
AwsException e = assertThrows(AwsException.class, () -> kinesisService.describeStreamByArn(streamArn, REGION));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void deleteStream() {
kinesisService.createStream("to-delete", 1, REGION);