fix(cloudformation): apply SSESpecification to a DynamoDB table on create (#9379)

This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-24 16:41:13 -04:00
1 parent 4a9ae4a569
commit bc6a2279d4
12 files changed
+271 -11

No files matched your search

+1 -1
View File
@@ -208,7 +208,7 @@ cross-resource references.
| SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) |
| SNS | `Topic`, `Subscription`, `TopicPolicy` |
| SES | `ConfigurationSet` (only `Name` is supported; option and tag properties fail validation instead of being silently ignored; Ref returns the set name), `ConfigurationSetEventDestination`, `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. `KinesisStreamSpecification` applied on create and update; with the DynamoDB Local backend, `StreamArn` is checked as on AWS but nothing is forwarded), `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. `SSESpecification` applied on create, not on update; the DynamoDB Local backend keeps no encryption setting), `GlobalTable` (`SSESpecification` applied on create, not on update, with the AWS managed key; a replica's own `SSESpecification` is not read) |
| 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`, `CodeSigningConfig`, `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. |
| Signer | `SigningProfile` (identifiers only; Floci has no Signer API) |
| IAM | `Role`, `User` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
@@ -185,6 +185,7 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
boolean plainTable = TABLE.equals(r.getResourceType());
ThroughputSpec tableThroughput = plainTable ? declaredThroughput(props, "#", ctx) : NO_THROUGHPUT;
Map<String, ThroughputSpec> indexThroughput = new LinkedHashMap<>();
JsonNode sseSpec = props != null ? engine.resolveNode(props.get("SSESpecification")) : null;
List<KeySchemaElement> keySchema = new ArrayList<>();
List<AttributeDefinition> attrDefs = new ArrayList<>();
@@ -308,6 +309,12 @@ public class DynamoDbCfnProvisioner implements CfnResourceProvisioner {
}
try {
// CreateTable takes SSESpecification itself; applied right after it, a refused SSEType
// still leaves no table, as the failure below deletes the one this attempt created.
if (created && sseSpec != null && "true".equalsIgnoreCase(ctx.resolveOptional(sseSpec, "SSEEnabled"))) {
table = dynamoDb.tables().enableServerSideEncryption(scope, tableName,
ctx.resolveOptional(sseSpec, "SSEType"), ctx.resolveOptional(sseSpec, "KMSMasterKeyId"));
}
// TTL is read when the template declares it, and on an in-place update for the rollback
// snapshot, so UpdateTimeToLive is called only when something differs. A rename of an
// enabled TTL attribute fails here, and the snapshot is taken here, before anything changes.
@@ -2601,13 +2601,8 @@ public class NativeDynamoDbJsonHandler {
addIndexViolations(request.path("GlobalSecondaryIndexes"), "globalSecondaryIndexes", true, violations);
addOlderEnumError(request, "BillingMode", "billingMode", DynamoDbService.BILLING_MODES, violations);
JsonNode sse = request.path("SSESpecification");
String kmsMasterKeyId = textOrNull(sse, "KMSMasterKeyId");
if (kmsMasterKeyId != null) {
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(
"sSESpecification.kMSMasterKeyId", kmsMasterKeyId, 1, 2048));
}
addOlderEnumError(sse, "SSEType", "sSESpecification.sSEType", NativeDynamoDbTableService.SSE_TYPES,
violations);
violations.addAll(NativeDynamoDbTableService.sseSpecificationViolations(textOrNull(sse, "SSEType"),
textOrNull(sse, "KMSMasterKeyId")));
addKeySchemaViolations(request.path("KeySchema"), "keySchema", violations);
violations.addAll(throughputViolations(request.path("ProvisionedThroughput"), "provisionedThroughput"));
JsonNode stream = request.path("StreamSpecification");
@@ -435,6 +435,16 @@ public class NativeDynamoDbTableService {
warm(change.table().warm())), region);
}
/** The UpdateTable that turns server-side encryption on, with the checks of the API. */
public TableDefinition enableServerSideEncryption(String tableName, String sseType, String kmsMasterKeyId,
String region) {
requireValidSseSpecification(sseType, kmsMasterKeyId);
TableSettings settings = new TableSettings(null, null, null, null, null, null, true, sseType,
kmsMasterKeyId);
return updateTable(new UpdateTableRequest(tableName, null, List.of(), List.of(), List.of(), List.of(),
List.of(), List.of(), List.of(), List.of(), List.of(), settings, null), region);
}
private static Throughput throughput(CapacityUnits capacity) {
return capacity == null ? null : new Throughput(capacity.readCapacityUnits(), capacity.writeCapacityUnits());
}
@@ -849,6 +859,30 @@ public class NativeDynamoDbTableService {
return kmsMasterKeyId != null ? kmsMasterKeyId : defaultKmsMasterKeyArn(region);
}
/** CreateTable's checks on the members of {@code SSESpecification}, in the order DynamoDB reports them. */
static List<String> sseSpecificationViolations(String sseType, String kmsMasterKeyId) {
List<String> violations = new ArrayList<>();
if (kmsMasterKeyId != null) {
String keyViolation = SmithyValidationErrors.lengthOutOfRange("sSESpecification.kMSMasterKeyId",
kmsMasterKeyId, 1, 2048);
if (keyViolation != null) {
violations.add(keyViolation);
}
}
if (sseType != null && !SSE_TYPES.contains(sseType)) {
violations.add(SmithyValidationErrors.notInEnum(sseType, "sSESpecification.sSEType", SSE_TYPES));
}
return violations;
}
/** Refuses an {@code SSESpecification} that CreateTable would refuse, whichever engine keeps the table. */
public static void requireValidSseSpecification(String sseType, String kmsMasterKeyId) {
List<String> violations = sseSpecificationViolations(sseType, kmsMasterKeyId);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
}
private static void validateSseType(String sseType) {
if (!SSE_TYPES.contains(sseType)) {
throw SmithyValidationErrors.validationException(
@@ -19,6 +19,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.dynamodb.DynamoDbTableNames;
import io.floci.aws.services.dynamodb.DynamoDbTtlIdentity;
import io.floci.aws.services.dynamodb.NativeDynamoDbTableService;
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
import io.floci.aws.services.dynamodb.model.GlobalSecondaryIndex;
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
@@ -461,6 +462,15 @@ public class DynamoDbLocalBackend implements DynamoDbBackend {
return table(call(scope, "UpdateTable", body).path("TableDescription"));
}
// ponytail: Local keeps no encryption setting and answers an UpdateTable that only sets one with
// "Nothing to update", so the setting gets CreateTable's checks and the table is left as it is.
@Override
public TableDefinition enableServerSideEncryption(Scope scope, String tableName, String sseType,
String kmsMasterKeyId) {
NativeDynamoDbTableService.requireValidSseSpecification(sseType, kmsMasterKeyId);
return describeTable(scope, tableName);
}
private ObjectNode capacity(CapacityUnits capacity) {
return aws.createObjectNode()
.put("ReadCapacityUnits", capacity.readCapacityUnits())
@@ -52,6 +52,12 @@ public interface DynamoDbTableAccess {
/** One UpdateTable that changes the capacity and warm throughput of the table and of the named indexes. */
TableDefinition updateThroughput(Scope scope, String tableName, ThroughputChange change);
/**
* Turns server-side encryption on as CreateTable's {@code SSESpecification} does, with its checks.
* A null {@code sseType} means KMS, and a null {@code kmsMasterKeyId} the AWS managed key.
*/
TableDefinition enableServerSideEncryption(Scope scope, String tableName, String sseType, String kmsMasterKeyId);
TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions,
List<GlobalSecondaryIndex> globalSecondaryIndexes,
@@ -197,6 +197,13 @@ public class NativeDynamoDbBackend implements DynamoDbBackend {
() -> tableService.updateThroughput(tableName, change, scope.region()));
}
@Override
public TableDefinition enableServerSideEncryption(Scope scope, String tableName, String sseType,
String kmsMasterKeyId) {
return RequestScopes.callAs(scope.accountId(),
() -> tableService.enableServerSideEncryption(tableName, sseType, kmsMasterKeyId, scope.region()));
}
@Override
public TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions,
@@ -0,0 +1,141 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.SSEDescription;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@code SSESpecification} on {@code AWS::DynamoDB::Table} and {@code AWS::DynamoDB::GlobalTable}: "If enabled (true), server-side
* encryption type is set to KMS and an AWS managed key is used" (AWS::DynamoDB::Table
* SSESpecification), so DescribeTable reports the {@code SSEDescription} that CreateTable with the
* same setting gives.
*/
@QuarkusTest
class CloudFormationDynamoDbSseSpecificationIntegrationTest {
private static final String TEMPLATE = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"BillingMode": "PAY_PER_REQUEST",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"SSESpecification": %s
}
}
}
}
""";
private static final String GLOBAL_TEMPLATE = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::GlobalTable",
"Properties": {
"TableName": "%s",
"BillingMode": "PAY_PER_REQUEST",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"Replicas": [{"Region": "us-east-1"}],
"SSESpecification": {"SSEEnabled": true, "SSEType": "KMS"}
}
}
}
}
""";
private CloudFormationClient cfn;
private DynamoDbClient dynamoDb;
private String stackName;
private String tableName;
@BeforeEach
void setUp() {
cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
dynamoDb = AwsTestClients.create(DynamoDbClient.builder(), "test", Region.US_EAST_1);
String suffix = Long.toString(System.nanoTime(), 36);
stackName = "cfn-ddb-sse-" + suffix;
tableName = "sse-table-" + suffix;
}
@AfterEach
void cleanUp() {
try {
CfnStackWaits.deleteStack(cfn, stackName);
} finally {
cfn.close();
dynamoDb.close();
}
}
@Test
void sseEnabledEncryptsTheTableWithTheAwsManagedKey() {
CfnStackWaits.createStack(cfn, stackName, TEMPLATE.formatted(tableName, "{\"SSEEnabled\": true}"),
"CREATE_COMPLETE");
SSEDescription sse = dynamoDb.describeTable(r -> r.tableName(tableName)).table().sseDescription();
assertEquals("ENABLED", sse.statusAsString());
assertEquals("KMS", sse.sseTypeAsString());
assertTrue(sse.kmsMasterKeyArn().endsWith(":key/aws-managed-dynamodb"), sse.kmsMasterKeyArn());
}
@Test
void kmsMasterKeyIdIsTheKeyTheTableReports() {
String key = "arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab";
CfnStackWaits.createStack(cfn, stackName, TEMPLATE.formatted(tableName,
"{\"SSEEnabled\": true, \"SSEType\": \"KMS\", \"KMSMasterKeyId\": \"" + key + "\"}"),
"CREATE_COMPLETE");
SSEDescription sse = dynamoDb.describeTable(r -> r.tableName(tableName)).table().sseDescription();
assertEquals(key, sse.kmsMasterKeyArn());
}
@Test
void globalTableSseEnabledEncryptsTheTableWithTheAwsManagedKey() {
CfnStackWaits.createStack(cfn, stackName, GLOBAL_TEMPLATE.formatted(tableName), "CREATE_COMPLETE");
SSEDescription sse = dynamoDb.describeTable(r -> r.tableName(tableName)).table().sseDescription();
assertEquals("ENABLED", sse.statusAsString());
assertEquals("KMS", sse.sseTypeAsString());
assertTrue(sse.kmsMasterKeyArn().endsWith(":key/aws-managed-dynamodb"), sse.kmsMasterKeyArn());
}
@Test
void unknownSseTypeFailsTheStackAndLeavesNoTable() {
CfnStackWaits.createStack(cfn, stackName, TEMPLATE.formatted(tableName,
"{\"SSEEnabled\": true, \"SSEType\": \"DES\"}"), "ROLLBACK_COMPLETE");
String reason = CfnStackWaits.failedResourceReason(stackName);
assertTrue(reason.contains("Value 'DES' at 'sSESpecification.sSEType' failed to satisfy constraint"), reason);
assertThrows(ResourceNotFoundException.class, () -> dynamoDb.describeTable(r -> r.tableName(tableName)));
}
@Test
void emptyKmsMasterKeyIdFailsTheStackAndLeavesNoTable() {
CfnStackWaits.createStack(cfn, stackName, TEMPLATE.formatted(tableName,
"{\"SSEEnabled\": true, \"KMSMasterKeyId\": \"\"}"), "ROLLBACK_COMPLETE");
String reason = CfnStackWaits.failedResourceReason(stackName);
assertTrue(reason.contains("Value '' at 'sSESpecification.kMSMasterKeyId' failed to satisfy constraint"), reason);
assertThrows(ResourceNotFoundException.class, () -> dynamoDb.describeTable(r -> r.tableName(tableName)));
}
}
@@ -293,6 +293,61 @@ class DynamoDbLocalBackendIntegrationTest {
.body("TimeToLiveDescription.AttributeName", equalTo("expiresAt"));
}
@Test
void aStackDeclaringEncryptionCreatesItsTableOnLocal() {
String table = tableName("sse");
String stack = "local-it-sse-" + UUID.randomUUID();
String template = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST",
"SSESpecification": {"SSEEnabled": true}
}
}
}
}
""".formatted(table);
cloudFormation(A_EAST, "CreateStack", stack, template);
created.add(new CreatedTable(A_EAST, table));
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", A_EAST.authorization("cloudformation"));
dynamoDb(A_EAST, "DescribeTable", "{\"TableName\": \"" + table + "\"}").statusCode(200);
}
@Test
void aStackDeclaringAnUnknownSseTypeRollsBackOnLocal() {
String table = tableName("sse-des");
String stack = "local-it-sse-des-" + UUID.randomUUID();
String template = """
{
"Resources": {
"Orders": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST",
"SSESpecification": {"SSEEnabled": true, "SSEType": "DES"}
}
}
}
}
""".formatted(table);
cloudFormation(A_EAST, "CreateStack", stack, template);
CfnStackWaits.awaitStatus(stack, "ROLLBACK_COMPLETE", A_EAST.authorization("cloudformation"));
dynamoDb(A_EAST, "DescribeTable", "{\"TableName\": \"" + table + "\"}").statusCode(400);
}
@Test
void resetIsRefused() {
given().when().post("/_floci/state/reset").then().statusCode(409);
@@ -105,6 +105,12 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
return record("updateThroughput", scope);
}
@Override
public TableDefinition enableServerSideEncryption(Scope scope, String tableName, String sseType,
String kmsMasterKeyId) {
return record("enableServerSideEncryption", scope);
}
@Override
public TableDefinition createOnDemandTable(Scope scope, String tableName, List<KeySchemaElement> keySchema,
List<AttributeDefinition> attributeDefinitions,
@@ -163,7 +163,6 @@ AWS::DynamoDB::GlobalTable GlobalTableWitnesses accepted and ignored
AWS::DynamoDB::GlobalTable MultiRegionConsistency accepted and ignored
AWS::DynamoDB::GlobalTable ReadOnDemandThroughputSettings accepted and ignored
AWS::DynamoDB::GlobalTable ReadProvisionedThroughputSettings accepted and ignored
AWS::DynamoDB::GlobalTable SSESpecification accepted and ignored
AWS::DynamoDB::GlobalTable TableType accepted and ignored
AWS::DynamoDB::GlobalTable VectorIndexes accepted and ignored
AWS::DynamoDB::GlobalTable WriteOnDemandThroughputSettings accepted and ignored
@@ -174,7 +173,6 @@ AWS::DynamoDB::Table ImportSourceSpecification accepted and ignored
AWS::DynamoDB::Table OnDemandThroughput accepted and ignored
AWS::DynamoDB::Table PointInTimeRecoverySpecification accepted and ignored
AWS::DynamoDB::Table ResourcePolicy accepted and ignored
AWS::DynamoDB::Table SSESpecification accepted and ignored
AWS::DynamoDB::Table TableClass accepted and ignored
AWS::DynamoDB::Table VectorIndexes accepted and ignored
AWS::EC2::EIP Address accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
163 AWS::DynamoDB::GlobalTable MultiRegionConsistency accepted and ignored
164 AWS::DynamoDB::GlobalTable ReadOnDemandThroughputSettings accepted and ignored
165 AWS::DynamoDB::GlobalTable ReadProvisionedThroughputSettings accepted and ignored
AWS::DynamoDB::GlobalTable SSESpecification accepted and ignored
166 AWS::DynamoDB::GlobalTable TableType accepted and ignored
167 AWS::DynamoDB::GlobalTable VectorIndexes accepted and ignored
168 AWS::DynamoDB::GlobalTable WriteOnDemandThroughputSettings accepted and ignored
173 AWS::DynamoDB::Table OnDemandThroughput accepted and ignored
174 AWS::DynamoDB::Table PointInTimeRecoverySpecification accepted and ignored
175 AWS::DynamoDB::Table ResourcePolicy accepted and ignored
AWS::DynamoDB::Table SSESpecification accepted and ignored
176 AWS::DynamoDB::Table TableClass accepted and ignored
177 AWS::DynamoDB::Table VectorIndexes accepted and ignored
178 AWS::EC2::EIP Address accepted and ignored
+2 -1
View File
@@ -255,7 +255,8 @@ 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. `KinesisStreamSpecification` applied on create and update; with the DynamoDB Local backend, `StreamArn` is checked as on AWS but nothing is forwarded'
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. `SSESpecification` applied on create, not on update; the DynamoDB Local backend keeps no encryption setting'
AWS::DynamoDB::GlobalTable: '`SSESpecification` applied on create, not on update, with the AWS managed key; a replica''s own `SSESpecification` is not read'
AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`; `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::ConfigurationSet: 'only `Name` is supported; option and tag properties fail validation instead of being silently ignored; Ref returns the set name'