From 8b756a3467ae8eccafc8fb8fcae6d199c65e11b8 Mon Sep 17 00:00:00 2001 From: mokamoto12 Date: Wed, 4 Nov 2026 12:10:27 +0900 Subject: [PATCH] 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. --- docs/services/cloudformation.md | 2 +- .../provisioners/DynamoDbCfnProvisioner.java | 183 +++++++- .../dynamodb/NativeDynamoDbTableService.java | 39 +- .../backend/DynamoDbLocalBackend.java | 46 +- .../dynamodb/backend/DynamoDbTableAccess.java | 8 + .../backend/NativeDynamoDbBackend.java | 30 ++ .../services/kinesis/KinesisService.java | 13 + .../IamConditionContextResolverTest.java | 2 +- .../cloudformation/CfnProvisionerFixture.java | 2 +- ...sisStreamSpecificationIntegrationTest.java | 261 +++++++++++ .../DynamoDbCfnProvisionerTest.java | 5 +- ...StreamSpecificationCfnProvisionerTest.java | 407 ++++++++++++++++++ .../NativeDynamoDbTableServiceTest.java | 44 +- .../backend/DynamoDbLocalBackendTest.java | 39 +- .../backend/DynamoDbNativeBackendTest.java | 2 +- .../backend/RecordingDynamoDbBackend.java | 17 + .../services/kinesis/KinesisServiceTest.java | 24 ++ .../cloudformation/writable-property-gaps.tsv | 1 - tools/docs/cfn_resource_types.yaml | 2 +- 19 files changed, 1096 insertions(+), 31 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbKinesisStreamSpecificationIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbKinesisStreamSpecificationCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 5458ca4368..ad7aa2c22d 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -182,7 +182,7 @@ cross-resource references. | SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) | | SNS | `Topic`, `Subscription`, `TopicPolicy` | | SES | `EmailIdentity` (BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS's region- and identity-specific zone assignment), `ReceiptRule` (stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery) | -| DynamoDB | `Table` (`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one), `GlobalTable` | +| DynamoDB | `Table` (`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one. `KinesisStreamSpecification` applied on create and update; with the DynamoDB Local backend, `StreamArn` is checked as on AWS but nothing is forwarded), `GlobalTable` | | Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`, `WebFunction` (control plane only; the endpoint domain does not serve requests yet), `WebFunctionEndpoint`, `WebFunctionRevision` (every property is createOnly, so a change mints a new revision). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. | | IAM | `Role`, `User` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` | | Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java index 181400e3da..a29a7de17d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisioner.java @@ -3,9 +3,12 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.SmithyValidationErrors; 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; @@ -14,6 +17,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess. import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; 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.KinesisStreamingDestination; import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; import jakarta.enterprise.context.ApplicationScoped; @@ -43,9 +47,11 @@ import java.util.Set; * {@code Ref} of a replica follows CDK's {@code -} format. * *

A table's {@code TimeToLiveSpecification} is reconciled against what DescribeTimeToLive - * reports, so UpdateTimeToLive is called only when the setting differs. An in-place update of an - * {@code AWS::DynamoDB::Table} keeps the tags, stream and TTL setting it replaces, so a failed - * stack update can put all three back. + * reports, so UpdateTimeToLive is called only when the setting differs. Its + * {@code KinesisStreamSpecification} is reconciled against the table's active Kinesis streaming + * destinations the same way. An in-place update of an {@code AWS::DynamoDB::Table} keeps the tags, + * stream, TTL setting and Kinesis streaming destinations it replaces, so a failed stack update can + * put all four back. */ @ApplicationScoped public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { @@ -62,6 +68,14 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { private static final String REPLICA_REGION_ATTR = "__FlociDynamoDbReplicaRegion"; private static final String REPLICA_SKIP_DELETION_ATTR = "__FlociDynamoDbReplicaSkipDeletion"; private static final int TABLE_NAME_MAX_LENGTH = 255; + private static final String KINESIS_STREAM_SPECIFICATION = "KinesisStreamSpecification"; + private static final String DESTINATION_ACTIVE = "ACTIVE"; + private static final int STREAM_ARN_MIN_LENGTH = 37; + private static final int STREAM_ARN_MAX_LENGTH = 1024; + + /** One Kinesis streaming destination a table should forward to, with its timestamp precision. */ + private record KinesisDestinationSpec(String streamArn, String precision) { + } private final DynamoDbFacade dynamoDb; @@ -133,6 +147,15 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { // survives an update; removing a block the previous template declared turns TTL off. boolean ttlManaged = ttlDeclared || ctx.previouslyDeclared("TimeToLiveSpecification"); TimeToLive desiredTtl = ttlDeclared ? declaredTimeToLive(ttlSpec, engine) : TIME_TO_LIVE_OFF; + JsonNode kinesisSpec = props != null ? engine.resolveNode(props.get(KINESIS_STREAM_SPECIFICATION)) : null; + boolean kinesisDeclared = kinesisSpec != null && !kinesisSpec.isNull(); + if (kinesisDeclared) { + CfnPropertyTypes.requireType(KINESIS_STREAM_SPECIFICATION, kinesisSpec, JsonNodeType.OBJECT); + } + boolean kinesisManaged = kinesisDeclared || ctx.previouslyDeclared(KINESIS_STREAM_SPECIFICATION); + List desiredKinesis = kinesisDeclared + ? List.of(declaredKinesisDestination(kinesisSpec, engine)) + : List.of(); List keySchema = new ArrayList<>(); List attrDefs = new ArrayList<>(); @@ -232,7 +255,7 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { } Map currentTags = dynamoDb.tables().listTagsOfResource(scope, table.getTableArn()); if (inPlaceUpdate && TABLE.equals(r.getResourceType())) { - snapshotBeforeUpdate(r, scope, tableName, table, currentTags, currentTtl); + snapshotBeforeUpdate(r, scope, tableName, table, currentTags, currentTtl, kinesisManaged); } reconcileTags(scope, table.getTableArn(), currentTags, @@ -262,6 +285,10 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { reconcileTimeToLive(scope, tableName, currentTtl, desiredTtl); } + if (kinesisManaged) { + table = reconcileKinesisDestinations(scope, tableName, table, desiredKinesis, true); + } + r.setPhysicalId(tableName); r.getAttributes().put("Arn", table.getTableArn()); // Only the global table's registry schema declares TableId read-only; a plain table exposes @@ -382,12 +409,128 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { } /** - * Keeps the tags, stream setting and TTL setting the table has before an in-place update - * changes them, with the account and region that address it, so {@link #rollbackUpdate} can - * put all three back. + * Runs before the table is created, as AWS validates the template before any resource exists. An + * empty {@code StreamArn} is present, so it passes here and fails the API's length check later. + */ + private static KinesisDestinationSpec declaredKinesisDestination(JsonNode spec, + CloudFormationTemplateEngine engine) { + JsonNode streamArnNode = spec.get("StreamArn"); + String streamArn = streamArnNode == null || streamArnNode.isNull() ? null : engine.resolve(streamArnNode); + if (streamArn == null) { + throw new AwsException("InvalidRequest", + "Model validation failed (#/KinesisStreamSpecification: required key [StreamArn] not found)", 400); + } + JsonNode precisionNode = spec.get("ApproximateCreationDateTimePrecision"); + String precision = precisionNode == null || precisionNode.isNull() + ? KinesisStreamingDestination.PRECISION_MILLISECOND + : engine.resolve(precisionNode); + if (!KinesisStreamingDestination.PRECISION_MILLISECOND.equals(precision) + && !KinesisStreamingDestination.PRECISION_MICROSECOND.equals(precision)) { + throw new AwsException("InvalidRequest", "Model validation failed" + + " (#/KinesisStreamSpecification/ApproximateCreationDateTimePrecision:" + + " failed validation constraint for keyword [enum])", 400); + } + return new KinesisDestinationSpec(streamArn, precision); + } + + private static List activeKinesisDestinations(TableDefinition table) { + List active = new ArrayList<>(); + for (KinesisStreamingDestination destination : table.getKinesisStreamingDestinations()) { + if (DESTINATION_ACTIVE.equals(destination.getDestinationStatus())) { + active.add(new KinesisDestinationSpec(destination.getStreamArn(), + destination.getApproximateCreationDateTimePrecision())); + } + } + return active; + } + + /** + * Leaves exactly the desired destinations active. A destination whose precision alone differs is + * updated in place, as CloudFormation does with one UpdateKinesisStreamingDestination call. The + * active list is copied first: the service may hand back the stored table, whose destination list + * the calls below change. + * {@code fromTemplate} checks every declared {@code StreamArn} as the AWS handler does, whether + * or not the table already forwards to it; a rollback restores destinations the table already had + * and enables them as they were. + */ + private TableDefinition reconcileKinesisDestinations(Scope scope, String tableName, TableDefinition table, + List desired, boolean fromTemplate) { + if (fromTemplate) { + for (KinesisDestinationSpec destination : desired) { + requireUsableStreamArn(tableName, destination.streamArn()); + } + } + List active = activeKinesisDestinations(table); + for (KinesisDestinationSpec destination : active) { + if (!containsStream(desired, destination.streamArn())) { + table = dynamoDb.tables().disableKinesisStreamingDestination(scope, tableName, + destination.streamArn()); + } + } + for (KinesisDestinationSpec destination : desired) { + if (active.contains(destination)) { + continue; + } + if (containsStream(active, destination.streamArn())) { + table = dynamoDb.tables().updateKinesisStreamingDestination(scope, tableName, + destination.streamArn(), destination.precision()); + } else if (fromTemplate) { + table = enableKinesisDestination(scope, tableName, destination); + } else { + table = dynamoDb.tables().enableKinesisStreamingDestination(scope, tableName, + destination.streamArn(), destination.precision()); + } + } + return table; + } + + /** + * Fails the way the AWS handler does. A {@code StreamArn} outside the API's 37 to 1024 characters + * fails EnableKinesisStreamingDestination's own validation. Any other value that is not a Kinesis + * stream ARN, such as a stream's name from {@code Ref}, never becomes active, so the table does + * not stabilize. + */ + private static void requireUsableStreamArn(String tableName, String streamArn) { + String violation = SmithyValidationErrors.lengthOutOfRange("streamArn", streamArn, + STREAM_ARN_MIN_LENGTH, STREAM_ARN_MAX_LENGTH); + if (violation != null) { + throw SmithyValidationErrors.exception("InvalidRequest", violation); + } + if (!AwsArnUtils.isArnFor(streamArn, "kinesis")) { + throw notStabilized(tableName); + } + } + + /** A stream that does not exist, as the table's account and region see it, never becomes active either. */ + private TableDefinition enableKinesisDestination(Scope scope, String tableName, + KinesisDestinationSpec destination) { + try { + return dynamoDb.tables().enableKinesisStreamingDestination(scope, tableName, destination.streamArn(), + destination.precision()); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + throw notStabilized(tableName); + } + throw e; + } + } + + private static AwsException notStabilized(String tableName) { + return new AwsException("NotStabilized", "Resource of type '" + TABLE + "' with identifier '" + tableName + + "' did not stabilize.", 400); + } + + private static boolean containsStream(List destinations, String streamArn) { + return destinations.stream().anyMatch(destination -> destination.streamArn().equals(streamArn)); + } + + /** + * Keeps the tags, stream setting, TTL setting and active Kinesis streaming destinations the table + * has before an in-place update changes them, with the account and region that address it, so + * {@link #rollbackUpdate} can put all four back. */ private static void snapshotBeforeUpdate(StackResource r, Scope scope, String tableName, TableDefinition table, - Map tags, TimeToLive ttl) { + Map tags, TimeToLive ttl, boolean kinesisManaged) { ObjectNode snapshot = MAPPER.createObjectNode(); snapshot.put("accountId", scope.accountId()); snapshot.put("region", scope.region()); @@ -398,6 +541,14 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { snapshot.put("streamViewType", table.getStreamViewType()); snapshot.put("ttlEnabled", ttl.enabled()); snapshot.put("ttlAttributeName", ttl.attributeName()); + if (kinesisManaged) { + ArrayNode destinations = snapshot.putArray("kinesisDestinations"); + for (KinesisDestinationSpec destination : activeKinesisDestinations(table)) { + destinations.addObject() + .put("streamArn", destination.streamArn()) + .put("precision", destination.precision()); + } + } r.getAttributes().put(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); } @@ -412,9 +563,10 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { } /** - * Puts back the tags, stream setting and TTL setting an in-place table update changed. All - * three go back or none is claimed: restoring one alone would report a rollback while the - * others stayed changed. Only an in-place {@code AWS::DynamoDB::Table} update takes the + * Puts back the tags, stream setting, TTL setting and Kinesis streaming destinations an in-place + * table update changed. All four go back or none is claimed: restoring one alone would report a + * rollback while the others stayed changed. A snapshot without destinations leaves them as they + * are. Only an in-place {@code AWS::DynamoDB::Table} update takes the * snapshot, so a global table or a replacing update still reports that rollback is not * implemented. The snapshot is spent only once the restore succeeded: a restore that throws * leaves it in place for the next attempt. @@ -453,6 +605,15 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner { requireTimeToLiveChangeAllowed(currentTtl, priorTtl); reconcileTimeToLive(scope, tableName, currentTtl, priorTtl); + if (snapshot.has("kinesisDestinations")) { + List priorDestinations = new ArrayList<>(); + for (JsonNode destination : snapshot.path("kinesisDestinations")) { + priorDestinations.add(new KinesisDestinationSpec(destination.path("streamArn").asText(), + destination.path("precision").asText())); + } + table = reconcileKinesisDestinations(scope, tableName, table, priorDestinations, false); + } + publishStreamArn(resource, table); resource.getAttributes().remove(CfnRollback.DYNAMODB_TABLE_UPDATE_SNAPSHOT_ATTR); return true; diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java index f9e695ffb2..749756137a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableService.java @@ -74,7 +74,7 @@ public class NativeDynamoDbTableService { * read-back of the stored {@link KinesisStreamingDestination}: that object is shared across * requests, so reading it again could report a status a concurrent call wrote in the meantime. */ - record KinesisDestination(String tableName, String streamArn, String destinationStatus, + public record KinesisDestination(String tableName, String streamArn, String destinationStatus, String approximateCreationDateTimePrecision) {} /** One GlobalSecondaryIndexOverride or LocalSecondaryIndexOverride entry; LSIs carry no throughput. */ @@ -524,13 +524,13 @@ public class NativeDynamoDbTableService { * @param precision an already validated ApproximateCreationDateTimePrecision * @return a snapshot of what this call left on the destination, with the canonical table name */ - KinesisDestination enableKinesisStreamingDestination(String tableName, String streamArn, String precision, String region) { + public KinesisDestination enableKinesisStreamingDestination(String tableName, String streamArn, String precision, + String region) { TableDefinition table = dynamoDbService.describeTable(tableName, region); String resolvedTableName = table.getTableName(); - String streamName = streamArn.substring(streamArn.lastIndexOf('/') + 1); try { - kinesisService.describeStream(streamName, region); + kinesisService.describeStreamByArn(streamArn, region); } catch (AwsException e) { throw new AwsException("ResourceNotFoundException", "Kinesis stream not found: " + streamArn, 400); @@ -568,7 +568,7 @@ public class NativeDynamoDbTableService { * * @return a snapshot of what this call left on the destination, with the canonical table name */ - KinesisDestination disableKinesisStreamingDestination(String tableName, String streamArn, String region) { + public KinesisDestination disableKinesisStreamingDestination(String tableName, String streamArn, String region) { TableDefinition table = dynamoDbService.describeTable(tableName, region); String resolvedTableName = table.getTableName(); @@ -595,6 +595,35 @@ public class NativeDynamoDbTableService { return disabled; } + /** + * Changes the precision of an active destination in place, as UpdateKinesisStreamingDestination + * does. Forwarding never stops: records already captured are still delivered, and the forwarder + * stamps each later write with the new precision. + * + * @param precision an already validated ApproximateCreationDateTimePrecision + * @return a snapshot of what this call left on the destination, with the canonical table name + */ + public KinesisDestination updateKinesisStreamingDestination(String tableName, String streamArn, String precision, + String region) { + TableDefinition table = dynamoDbService.describeTable(tableName, region); + String resolvedTableName = table.getTableName(); + + Optional existing = table.findKinesisStreamingDestination(streamArn); + if (existing.isEmpty()) { + throw new AwsException("ResourceNotFoundException", + "Kinesis streaming destination not found for stream: " + streamArn, 400); + } + if (!"ACTIVE".equals(existing.get().getDestinationStatus())) { + throw new AwsException("ValidationException", + "Kinesis streaming destination is not active for stream: " + streamArn, 400); + } + + existing.get().setApproximateCreationDateTimePrecision(precision); + KinesisDestination updated = new KinesisDestination(resolvedTableName, streamArn, "ACTIVE", precision); + dynamoDbService.persistTable(resolvedTableName, table, region); + return updated; + } + /** The AWS managed key a table reports when SSE is KMS and no customer key was given. */ static String defaultKmsMasterKeyArn(String region) { return AwsArnUtils.Arn.of("kms", region, DEFAULT_ACCOUNT_ID, diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackend.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackend.java index de311ddb3a..9f4e4dbbba 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackend.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackend.java @@ -13,6 +13,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsPartitions; +import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -23,6 +24,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 jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Typed; import jakarta.inject.Inject; @@ -58,30 +60,35 @@ public class DynamoDbLocalBackend implements DynamoDbBackend { private static final Duration READINESS_BUDGET = Duration.ofSeconds(30); private static final Scope PROBE = new Scope("000000000000", "us-east-1"); // partition-literal: readiness probe namespace, Local accepts any region private static final String REPLICAS_UNSUPPORTED = "Replicas are not supported by the DynamoDB Local backend"; + private static final String KINESIS_DESTINATIONS_UNSUPPORTED = + "Kinesis streaming destinations are not supported by the DynamoDB Local backend"; private static final Pattern PARTITION = Pattern.compile(AwsArnUtils.PARTITION_REGEX); private static final List PUBLIC_ARN_FIELDS = List.of("TableArn", "IndexArn", "LatestStreamArn", "StreamArn", "LastEvaluatedStreamArn", "message", "Message"); private final DynamoDbLocalClient client; private final AccountAwareStorageBackend> tags; + private final KinesisService kinesisService; private final ObjectMapper objectMapper; private final ObjectMapper aws; private final Duration readiness; @Inject - public DynamoDbLocalBackend(EmulatorConfig config, StorageFactory storageFactory, ObjectMapper objectMapper) { + public DynamoDbLocalBackend(EmulatorConfig config, StorageFactory storageFactory, KinesisService kinesisService, + ObjectMapper objectMapper) { this(new DynamoDbLocalClient(validatedEndpoint(config.services().dynamodb().localEndpoint()), Duration.ofSeconds(config.services().dynamodb().localConnectTimeoutSeconds()), Duration.ofSeconds(config.services().dynamodb().localRequestTimeoutSeconds()), objectMapper), storageFactory.create("dynamodb", "dynamodb-local-tags.json", new TypeReference>>() {}), - objectMapper, READINESS_BUDGET); + kinesisService, objectMapper, READINESS_BUDGET); } DynamoDbLocalBackend(DynamoDbLocalClient client, AccountAwareStorageBackend> tags, - ObjectMapper objectMapper, Duration readiness) { + KinesisService kinesisService, ObjectMapper objectMapper, Duration readiness) { this.client = client; this.tags = tags; + this.kinesisService = kinesisService; this.objectMapper = objectMapper; this.aws = objectMapper.copy().setPropertyNamingStrategy(PropertyNamingStrategies.UPPER_CAMEL_CASE); this.readiness = readiness; @@ -536,6 +543,39 @@ public class DynamoDbLocalBackend implements DynamoDbBackend { return key(scope.region(), name); } + /** + * DynamoDB Local has no Kinesis forwarding. The three destination calls leave the table as it is + * and log a warning, so a template declaring {@code KinesisStreamSpecification} deploys on this + * backend without forwarding. Enabling still needs the stream to exist, as on AWS. + */ + @Override + public TableDefinition enableKinesisStreamingDestination(Scope scope, String tableName, String streamArn, + String precision) { + try { + RequestScopes.runAs(scope.accountId(), () -> kinesisService.describeStreamByArn(streamArn, scope.region())); + } catch (AwsException e) { + throw new AwsException("ResourceNotFoundException", "Kinesis stream not found: " + streamArn, 400); + } + return ignoredKinesisDestinationCall(scope, tableName, streamArn); + } + + @Override + public TableDefinition disableKinesisStreamingDestination(Scope scope, String tableName, String streamArn) { + return ignoredKinesisDestinationCall(scope, tableName, streamArn); + } + + @Override + public TableDefinition updateKinesisStreamingDestination(Scope scope, String tableName, String streamArn, + String precision) { + return ignoredKinesisDestinationCall(scope, tableName, streamArn); + } + + private TableDefinition ignoredKinesisDestinationCall(Scope scope, String tableName, String streamArn) { + LOG.warnv("{0}; the destination {1} of table {2} is ignored", KINESIS_DESTINATIONS_UNSUPPORTED, streamArn, + tableName); + return describeTable(scope, tableName); + } + @Override public TableDefinition applyReplicaUpdates(Scope scope, String tableName, List addRegions, List removeRegions) { diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java index 04986d8271..591d860d59 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbTableAccess.java @@ -38,6 +38,14 @@ public interface DynamoDbTableAccess { TableDefinition disableStream(Scope scope, String tableName); + TableDefinition enableKinesisStreamingDestination(Scope scope, String tableName, String streamArn, + String precision); + + TableDefinition disableKinesisStreamingDestination(Scope scope, String tableName, String streamArn); + + TableDefinition updateKinesisStreamingDestination(Scope scope, String tableName, String streamArn, + String precision); + TimeToLive timeToLive(Scope scope, String tableName); void updateTimeToLive(Scope scope, String tableName, String attributeName, boolean enabled); diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java index 0dc67a5aac..25bd8787b6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/NativeDynamoDbBackend.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService; import io.github.hectorvent.floci.services.dynamodb.DynamoDbTtlService; import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbJsonHandler; import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbStreamsJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.NativeDynamoDbTableService; import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; @@ -34,6 +35,7 @@ public class NativeDynamoDbBackend implements DynamoDbBackend { private final NativeDynamoDbJsonHandler jsonHandler; private final NativeDynamoDbStreamsJsonHandler streamsHandler; + private final NativeDynamoDbTableService tableService; private final DynamoDbService dynamoDbService; private final DynamoDbStreamService streamService; private final DynamoDbTtlService ttlService; @@ -42,10 +44,12 @@ public class NativeDynamoDbBackend implements DynamoDbBackend { @Inject public NativeDynamoDbBackend(NativeDynamoDbJsonHandler jsonHandler, NativeDynamoDbStreamsJsonHandler streamsHandler, + NativeDynamoDbTableService tableService, DynamoDbService dynamoDbService, DynamoDbStreamService streamService, DynamoDbTtlService ttlService, ObjectMapper objectMapper) { this.jsonHandler = jsonHandler; this.streamsHandler = streamsHandler; + this.tableService = tableService; this.dynamoDbService = dynamoDbService; this.streamService = streamService; this.ttlService = ttlService; @@ -193,6 +197,32 @@ public class NativeDynamoDbBackend implements DynamoDbBackend { return RequestScopes.callAs(scope.accountId(), () -> dynamoDbService.disableStream(tableName, scope.region())); } + @Override + public TableDefinition enableKinesisStreamingDestination(Scope scope, String tableName, String streamArn, + String precision) { + return RequestScopes.callAs(scope.accountId(), () -> { + tableService.enableKinesisStreamingDestination(tableName, streamArn, precision, scope.region()); + return dynamoDbService.describeTable(tableName, scope.region()); + }); + } + + @Override + public TableDefinition disableKinesisStreamingDestination(Scope scope, String tableName, String streamArn) { + return RequestScopes.callAs(scope.accountId(), () -> { + tableService.disableKinesisStreamingDestination(tableName, streamArn, scope.region()); + return dynamoDbService.describeTable(tableName, scope.region()); + }); + } + + @Override + public TableDefinition updateKinesisStreamingDestination(Scope scope, String tableName, String streamArn, + String precision) { + return RequestScopes.callAs(scope.accountId(), () -> { + tableService.updateKinesisStreamingDestination(tableName, streamArn, precision, scope.region()); + return dynamoDbService.describeTable(tableName, scope.region()); + }); + } + // Mirrors the native DescribeTimeToLive: no attribute name is reported while TTL is off. @Override public TimeToLive timeToLive(Scope scope, String tableName) { diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java index 39631ea02f..9948c70737 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java @@ -207,6 +207,19 @@ public class KinesisService implements ResourceProvider { return resolveStreamForAccount(accountId, streamName, region); } + /** + * The stream whose own ARN is {@code streamArn}, in the caller's account and {@code region}. A + * name alone, or an ARN for another account, region or resource type, names no stream here. + */ + public KinesisStream describeStreamByArn(String streamArn, String region) { + String streamName = streamArn.substring(streamArn.lastIndexOf('/') + 1); + KinesisStream stream = resolveStream(streamName, region); + if (!streamArn.equals(stream.getStreamArn())) { + throw new AwsException("ResourceNotFoundException", "Stream " + streamName + " not found", 400); + } + return stream; + } + public KinesisConsumer registerStreamConsumer(String streamArn, String consumerName, String region) { String consumerArn = streamArn + "/consumer/" + consumerName + ":" + System.currentTimeMillis(); KinesisConsumer consumer = new KinesisConsumer(consumerName, consumerArn, streamArn); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java index e77d35ed5a..3cf8b5cdc8 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java @@ -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, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index ffb5d7201a..7b53253985 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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")))); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbKinesisStreamSpecificationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbKinesisStreamSpecificationIntegrationTest.java new file mode 100644 index 0000000000..3c4d91d9a8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDynamoDbKinesisStreamSpecificationIntegrationTest.java @@ -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 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 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 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 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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java index 34f87498a2..b5fc4ad992 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbCfnProvisionerTest.java @@ -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"))); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbKinesisStreamSpecificationCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbKinesisStreamSpecificationCfnProvisionerTest.java new file mode 100644 index 0000000000..f024fdfd16 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/DynamoDbKinesisStreamSpecificationCfnProvisionerTest.java @@ -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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java index 2169290a48..3286aefdbb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbTableServiceTest.java @@ -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( diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackendTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackendTest.java index 8826a1afb4..f6675643bc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackendTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalBackendTest.java @@ -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> 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java index fbdbb04871..0c4005d22a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbNativeBackendTest.java @@ -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 { diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java index 55de707505..2224fdd1ee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/RecordingDynamoDbBackend.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java index 0f422ca6a6..78bf8d9fed 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kinesis/KinesisServiceTest.java @@ -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); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 24fbbb8191..c487553ca8 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -169,7 +169,6 @@ AWS::DynamoDB::Table BillingMode accepted and ignored AWS::DynamoDB::Table ContributorInsightsSpecification accepted and ignored AWS::DynamoDB::Table DeletionProtectionEnabled accepted and ignored AWS::DynamoDB::Table ImportSourceSpecification accepted and ignored -AWS::DynamoDB::Table KinesisStreamSpecification accepted and ignored AWS::DynamoDB::Table OnDemandThroughput accepted and ignored AWS::DynamoDB::Table PointInTimeRecoverySpecification accepted and ignored AWS::DynamoDB::Table ProvisionedThroughput accepted and ignored diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 1e9cd51273..2c8cc62ccd 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -214,7 +214,7 @@ notes: AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached' AWS::Route53::RecordSetGroup: 'written in one change batch, so a record set that cannot be written leaves the zone unchanged; every record set must be in the group''s hosted zone' Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda - AWS::DynamoDB::Table: '`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one' + AWS::DynamoDB::Table: '`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one. `KinesisStreamSpecification` applied on create and update; with the DynamoDB Local backend, `StreamArn` is checked as on AWS but nothing is forwarded' AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off' AWS::Cognito::UserPoolIdentityProvider: 'Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template''s and the replacement would need the same address' AWS::SES::EmailIdentity: 'BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS''s region- and identity-specific zone assignment'