fix(cloudformation): apply StreamEncryption on AWS::Kinesis::Stream (#9648)

KinesisCfnProvisioner never read StreamEncryption, so a stack with an encrypted AWS::Kinesis::Stream reached CREATE_COMPLETE with an unencrypted stream. The encryption type and key are now set by createStream, so they are in place while the stream is still CREATING. An update with a new or changed type or key calls startStreamEncryption, removing the property calls stopStreamEncryption, and an unchanged setting makes no call.

A setting the resource schema refuses, an EncryptionType other than KMS or a missing EncryptionType or KeyId, fails with InvalidRequest model validation before anything is created or changed.

Closes #9511
This commit is contained in:
Vinícius Ribeiro authored and GitHub committed 2026-11-28 18:39:04 -04:00
1 parent 215ecc91d2
commit 986d774bdf
5 files changed
+214 -16

No files matched your search

@@ -11,6 +11,7 @@ import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -24,6 +25,9 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner {
private static final int STREAM_NAME_MAX_LENGTH = 128;
private static final int DEFAULT_SHARD_COUNT = 1;
private static final String DEFAULT_STREAM_MODE = "PROVISIONED";
private static final String NO_ENCRYPTION = "NONE";
private static final String KMS_ENCRYPTION = "KMS";
private static final String RESOURCE_TYPE = "AWS::Kinesis::Stream";
private final KinesisService kinesisService;
@@ -33,7 +37,7 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::Kinesis::Stream");
return Set.of(RESOURCE_TYPE);
}
@Override
@@ -86,6 +90,15 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner {
}
}
String encryptionType = null;
String encryptionKeyId = null;
JsonNode encryptionNode = props != null ? ctx.engine().resolveNode(props.get("StreamEncryption")) : null;
if (encryptionNode != null && encryptionNode.isObject()) {
encryptionType = blankToNull(ctx.engine().resolve(encryptionNode.path("EncryptionType")));
encryptionKeyId = blankToNull(ctx.engine().resolve(encryptionNode.path("KeyId")));
validateStreamEncryption(encryptionType, encryptionKeyId);
}
// provision() re-runs on every UpdateStack, so a same-named stream already on file must be
// reconciled instead of re-created (createStream throws ResourceInUseException). ShardCount
// changes aren't reconciled here: KinesisService has no UpdateShardCount support to call into.
@@ -114,12 +127,22 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner {
if (!tags.isEmpty() && !existingTags.equals(tags)) {
kinesisService.addTagsToStream(name, tags, ctx.region());
}
// Removing StreamEncryption from the template turns encryption off, as on AWS.
if (encryptionType == null) {
if (!NO_ENCRYPTION.equals(stream.getEncryptionType())) {
kinesisService.stopStreamEncryption(name, ctx.region());
}
} else if (!encryptionType.equals(stream.getEncryptionType())
|| !Objects.equals(encryptionKeyId, stream.getKeyId())) {
kinesisService.startStreamEncryption(name, encryptionType, encryptionKeyId, ctx.region());
}
if (!desiredMode.equals(stream.getStreamMode())) {
kinesisService.updateStreamMode(name, desiredMode, ctx.region());
}
stream = kinesisService.describeStream(name, ctx.region());
} else {
stream = kinesisService.createStream(name, shardCount, streamMode, null, tags, retention, ctx.region());
stream = kinesisService.createStream(name, shardCount, streamMode, null, tags, retention,
encryptionType, encryptionKeyId, ctx.region());
deleteRenamedResource(priorPhysicalId, name,
id -> kinesisService.deleteStream(id, ctx.region()), "Kinesis stream");
}
@@ -129,6 +152,24 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("Arn", stream.getStreamArn());
}
/** aws-kinesis-stream.json: both members are required and KMS is the only EncryptionType. */
private static void validateStreamEncryption(String encryptionType, String keyId) {
if (encryptionType == null) {
throw CfnPropertyTypes.modelValidation("#/StreamEncryption: required key [EncryptionType] not found)");
}
if (keyId == null) {
throw CfnPropertyTypes.modelValidation("#/StreamEncryption: required key [KeyId] not found)");
}
if (!KMS_ENCRYPTION.equals(encryptionType)) {
throw CfnPropertyTypes.modelValidation(
"#/StreamEncryption/EncryptionType: failed validation constraint for keyword [enum])");
}
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
/**
* The resource already on file under this same name, or null when this is a create or a rename.
* Copied from the monolith, which still has callers for it.
@@ -208,6 +208,18 @@ public class KinesisService implements ResourceProvider {
public KinesisStream createStream(String streamName, int shardCount, String streamMode,
Integer maxRecordSizeInKiB, Map<String, String> tags,
Integer retentionPeriodHours, String region) {
return createStream(streamName, shardCount, streamMode, maxRecordSizeInKiB, tags, retentionPeriodHours,
null, null, region);
}
/**
* @param encryptionType the stream's server-side encryption type; null leaves it unencrypted
* @param keyId the KMS key for {@code encryptionType}
*/
public KinesisStream createStream(String streamName, int shardCount, String streamMode,
Integer maxRecordSizeInKiB, Map<String, String> tags,
Integer retentionPeriodHours, String encryptionType, String keyId,
String region) {
String resolvedMode = streamMode != null ? streamMode : DEFAULT_STREAM_MODE;
validateStreamMode(resolvedMode);
if (maxRecordSizeInKiB != null) {
@@ -232,6 +244,10 @@ public class KinesisService implements ResourceProvider {
if (retentionPeriodHours != null) {
stream.setRetentionPeriodHours(retentionPeriodHours);
}
if (encryptionType != null) {
stream.setEncryptionType(encryptionType);
stream.setKeyId(keyId);
}
enterStatusWindow(stream, "CREATING", creatingDelayMillis);
if (maxRecordSizeInKiB != null) {
stream.setMaxRecordSizeInKiB(maxRecordSizeInKiB);
@@ -66,6 +66,13 @@ class KinesisCfnProvisionerTest {
return s;
}
private static KinesisStream encryptedStream(String keyId) {
KinesisStream s = stream("arn", 24);
s.setEncryptionType("KMS");
s.setKeyId(keyId);
return s;
}
private StackResource provision(String json, String priorPhysicalId) {
StackResource r = new StackResource();
r.setLogicalId("Stream");
@@ -79,14 +86,14 @@ class KinesisCfnProvisionerTest {
@Test
void createUsesTheExplicitNameAndExposesTheArn() {
when(kinesis.createStream(eq("s"), anyInt(), any(), any(), anyMap(), any(), eq(REGION)))
when(kinesis.createStream(eq("s"), anyInt(), any(), any(), anyMap(), any(), any(), any(), eq(REGION)))
.thenReturn(stream("arn:aws:kinesis:us-east-1:000000000000:stream/s", 24));
StackResource r = provision("""
{"Name": "s", "ShardCount": "3"}
""", null);
verify(kinesis).createStream("s", 3, null, null, Map.of(), null, REGION);
verify(kinesis).createStream("s", 3, null, null, Map.of(), null, null, null, REGION);
assertEquals("s", r.getPhysicalId(), "Ref is the stream name");
// aws-kinesis-stream.json readOnlyProperties
assertEquals(Map.of("Arn", "arn:aws:kinesis:us-east-1:000000000000:stream/s"), r.getAttributes());
@@ -94,30 +101,89 @@ class KinesisCfnProvisionerTest {
@Test
void shardCountDefaultsToOneWhenAbsentOrUnparseable() {
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
provision("""
{"Name": "a"}
""", null);
verify(kinesis).createStream("a", 1, null, null, Map.of(), null, REGION);
verify(kinesis).createStream("a", 1, null, null, Map.of(), null, null, null, REGION);
provision("""
{"Name": "b", "ShardCount": "many"}
""", null);
verify(kinesis).createStream("b", 1, null, null, Map.of(), null, REGION);
verify(kinesis).createStream("b", 1, null, null, Map.of(), null, null, null, REGION);
}
@Test
void streamModeDetailsAreForwarded() {
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
provision("""
{"Name": "s", "StreamModeDetails": {"StreamMode": "ON_DEMAND"}}
""", null);
verify(kinesis).createStream("s", 1, "ON_DEMAND", null, Map.of(), null, REGION);
verify(kinesis).createStream("s", 1, "ON_DEMAND", null, Map.of(), null, null, null, REGION);
}
@Test
void streamEncryptionIsAppliedOnCreate() {
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
provision("""
{"Name": "s", "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/aws/kinesis"}}
""", null);
verify(kinesis).createStream("s", 1, null, null, Map.of(), null, "KMS", "alias/aws/kinesis", REGION);
}
@Test
void addingStreamEncryptionOnUpdateStartsIt() {
when(kinesis.describeStream("s", REGION)).thenReturn(stream("arn", 24));
provision("""
{"Name": "s", "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/aws/kinesis"}}
""", "s");
verify(kinesis).startStreamEncryption("s", "KMS", "alias/aws/kinesis", REGION);
verify(kinesis, never()).stopStreamEncryption(anyString(), anyString());
}
@Test
void changingTheStreamEncryptionKeyOnUpdateStartsItWithTheNewKey() {
when(kinesis.describeStream("s", REGION)).thenReturn(encryptedStream("alias/old"));
provision("""
{"Name": "s", "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/new"}}
""", "s");
verify(kinesis).startStreamEncryption("s", "KMS", "alias/new", REGION);
}
@Test
void unchangedStreamEncryptionIsLeftAlone() {
when(kinesis.describeStream("s", REGION)).thenReturn(encryptedStream("alias/aws/kinesis"));
provision("""
{"Name": "s", "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/aws/kinesis"}}
""", "s");
verify(kinesis, never()).startStreamEncryption(anyString(), anyString(), anyString(), anyString());
verify(kinesis, never()).stopStreamEncryption(anyString(), anyString());
}
/** "Removing this property from your stack template and updating your stack disables encryption." */
@Test
void removingStreamEncryptionOnUpdateStopsIt() {
when(kinesis.describeStream("s", REGION)).thenReturn(encryptedStream("alias/aws/kinesis"));
provision("""
{"Name": "s"}
""", "s");
verify(kinesis).stopStreamEncryption("s", REGION);
}
/**
@@ -132,7 +198,7 @@ class KinesisCfnProvisionerTest {
{"Name": "s"}
""", "s");
verify(kinesis, never()).createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString());
verify(kinesis, never()).createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString());
verify(kinesis, never()).updateStreamMode("s", "PROVISIONED", REGION);
}
@@ -199,19 +265,19 @@ class KinesisCfnProvisionerTest {
void aMissingStreamFallsBackToCreate() {
when(kinesis.describeStream("s", REGION))
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 400));
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
provision("""
{"Name": "s"}
""", "s");
verify(kinesis).createStream("s", 1, null, null, Map.of(), null, REGION);
verify(kinesis).createStream("s", 1, null, null, Map.of(), null, null, null, REGION);
}
@Test
void aRenameCreatesTheNewStreamAndBestEffortDeletesTheOld() {
when(kinesis.createStream(eq("new"), anyInt(), any(), any(), anyMap(), any(), anyString()))
when(kinesis.createStream(eq("new"), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
StackResource r = provision("""
@@ -225,7 +291,7 @@ class KinesisCfnProvisionerTest {
/** A failure deleting the renamed-away stream must not fail the resource. */
@Test
void aFailedCleanupOfTheRenamedStreamIsSwallowed() {
when(kinesis.createStream(eq("new"), anyInt(), any(), any(), anyMap(), any(), anyString()))
when(kinesis.createStream(eq("new"), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
Mockito.doThrow(new RuntimeException("boom"))
.when(kinesis).deleteStream("old", REGION);
@@ -239,7 +305,7 @@ class KinesisCfnProvisionerTest {
@Test
void anUnnamedStreamGetsAGeneratedNameKeptAcrossUpdates() {
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), anyString()))
when(kinesis.createStream(anyString(), anyInt(), any(), any(), anyMap(), any(), any(), any(), anyString()))
.thenReturn(stream("arn", 24));
StackResource created = provision("{}", null);
@@ -15,6 +15,7 @@ import io.floci.aws.testing.MutableClock;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
@@ -73,6 +74,81 @@ class KinesisCfnServiceTest {
assertEquals(48, restored.getRetentionPeriodHours());
}
@Test
void createEncryptsTheStreamWhileItIsStillCreating() throws Exception {
MutableClock clock = new MutableClock();
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"), clock, 60_000, 0);
provision(service, """
{"Name": "s", "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/aws/kinesis"}}
""", null);
KinesisStream stream = service.describeStream("s", REGION);
assertEquals("CREATING", stream.getStreamStatus(clock.instant()));
assertEquals("KMS", stream.getEncryptionType());
assertEquals("alias/aws/kinesis", stream.getKeyId());
}
@Test
void updateTurnsEncryptionOnAndOffWithTheTemplate() throws Exception {
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
KinesisStream stream = service.createStream("s", 1, REGION);
provision(service, """
{"Name": "s", "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/aws/kinesis"}}
""", "s");
assertEquals("KMS", stream.getEncryptionType());
assertEquals("alias/aws/kinesis", stream.getKeyId());
provision(service, """
{"Name": "s"}
""", "s");
assertEquals("NONE", stream.getEncryptionType());
assertEquals(null, stream.getKeyId());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"{\"EncryptionType\": \"AES\", \"KeyId\": \"alias/aws/kinesis\"}"
+ "|#/StreamEncryption/EncryptionType: failed validation constraint for keyword [enum]",
"{\"EncryptionType\": \"NONE\", \"KeyId\": \"alias/aws/kinesis\"}"
+ "|#/StreamEncryption/EncryptionType: failed validation constraint for keyword [enum]",
"{\"KeyId\": \"alias/aws/kinesis\"}|#/StreamEncryption: required key [EncryptionType] not found",
"{\"EncryptionType\": \"KMS\"}|#/StreamEncryption: required key [KeyId] not found"})
void invalidStreamEncryptionIsRejectedBeforeTheStreamIsCreated(String encryption, String violation)
throws Exception {
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
AwsException error = assertThrows(AwsException.class, () -> provision(service, """
{"Name": "s", "StreamEncryption": %s}
""".formatted(encryption), null));
assertEquals("InvalidRequest", error.getErrorCode());
assertEquals("Model validation failed (" + violation + ")", error.getMessage());
assertEquals(0, service.listStreamDetails(REGION).size());
}
@Test
void invalidStreamEncryptionOnUpdateLeavesTheStreamUntouched() throws Exception {
KinesisService service = new KinesisService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, "000000000000"));
KinesisStream stream = service.createStream("s", 1, REGION);
AwsException error = assertThrows(AwsException.class, () -> provision(service, """
{"Name": "s", "RetentionPeriodHours": "48",
"StreamEncryption": {"EncryptionType": "AES", "KeyId": "alias/aws/kinesis"}}
""", "s"));
assertEquals("InvalidRequest", error.getErrorCode());
assertEquals("Model validation failed (#/StreamEncryption/EncryptionType:"
+ " failed validation constraint for keyword [enum])", error.getMessage());
assertEquals("NONE", stream.getEncryptionType());
assertEquals(24, stream.getRetentionPeriodHours());
}
@ParameterizedTest
@ValueSource(ints = {12, 9000})
void createRejectsOutOfRangeRetentionWithoutLeavingStream(int retentionHours) throws Exception {
@@ -370,7 +370,6 @@ AWS::KMS::Key RotationPeriodInDays accepted and ignored
AWS::Kinesis::Stream DesiredShardLevelMetrics accepted and ignored
AWS::Kinesis::Stream MaxRecordSizeInKiB accepted and ignored
AWS::Kinesis::Stream RecordDistributionStrategy accepted and ignored
AWS::Kinesis::Stream StreamEncryption accepted and ignored
AWS::Kinesis::Stream WarmThroughputMiBps accepted and ignored
AWS::KinesisFirehose::DeliveryStream AmazonOpenSearchServerlessDestinationConfiguration documented as ignored (docs/services/cloudformation.md, Kinesis Data Firehose)
AWS::KinesisFirehose::DeliveryStream AmazonopensearchserviceDestinationConfiguration documented as ignored (docs/services/cloudformation.md, Kinesis Data Firehose)
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
370 AWS::Kinesis::Stream DesiredShardLevelMetrics accepted and ignored
371 AWS::Kinesis::Stream MaxRecordSizeInKiB accepted and ignored
372 AWS::Kinesis::Stream RecordDistributionStrategy accepted and ignored
AWS::Kinesis::Stream StreamEncryption accepted and ignored
373 AWS::Kinesis::Stream WarmThroughputMiBps accepted and ignored
374 AWS::KinesisFirehose::DeliveryStream AmazonOpenSearchServerlessDestinationConfiguration documented as ignored (docs/services/cloudformation.md, Kinesis Data Firehose)
375 AWS::KinesisFirehose::DeliveryStream AmazonopensearchserviceDestinationConfiguration documented as ignored (docs/services/cloudformation.md, Kinesis Data Firehose)