fix(msk): persist CreateCluster broker node groups, encryption, client auth, logging, configuration and tags (#2366)

* fix(msk): persist CreateCluster broker node group, encryption, client auth, logging, configuration and tags

* fix(msk): return the v2 Provisioned envelope and keep internal cluster state persistable

Addresses the two review findings on #2366, plus adjacent parity gaps.

Persistence: MskCluster is the shape WalStorage/PersistentStorage/HybridStorage
serialize, all with a plain ObjectMapper. Marking bootstrapBrokers, containerId
and volumeId @JsonIgnore to keep them out of API responses also stripped them
from the store, so a restart on non-mock storage came back with no bootstrap
brokers (breaking GetBootstrapBrokers and the Pipes Kafka source) and no
container or volume ID (orphaning the Docker resources). Those fields are
serializable again - as is accountId, which putCluster needs to write back to
the right account partition - and the API-facing exclusion moved to explicit
response views in MskController, matching toConfigurationView.

V2 shape: DescribeClusterV2/ListClustersV2 returned the flat v1 ClusterInfo.
The real v2 Cluster nests broker node group, encryption, client auth, monitoring,
logging, broker count and kafka version under Provisioned, with a top-level
ClusterType. An AWS SDK v2 client - what terraform-provider-aws calls - reads
them only there, so the flat shape left them invisible to exactly the callers
this fix is for.

Also:
- configurationInfo is a request-only member; the configuration is now reported
  on currentBrokerSoftwareInfo as configurationArn/configurationRevision, where
  the Terraform provider reads it from. It has no top-level response member on
  either API version.
- Apply AWS's server-side defaults for enhancedMonitoring (DEFAULT) and
  encryptionInTransit (TLS_PLAINTEXT / inCluster true), so an omitted member
  does not read back as drift.
- Omit absent optional members instead of serializing them as null.
- Cover the v2 envelope through the real AWS SDK in the compatibility suite, and
  add a plain-ObjectMapper round-trip test guarding the persistence regression.

* test(msk): mirror the storage mapper's configuration in the round-trip test

* fix(msk): round-trip openMonitoring, storageMode and rebalancing too

Three more CreateCluster request members that were discarded the same way, and
that AWS echoes on DescribeCluster (flat) and DescribeClusterV2 (under
Provisioned). openMonitoring and storageMode both map to terraform-provider-aws
attributes on aws_msk_cluster, so dropping them left the same non-converging
plan this change set is about.

* feat(msk): add the tag API, serverless clusters and CreateCluster validation

Closes the four gaps left open by the metadata round-trip work.

Tags: MSK had no tag endpoints at all, so tags could be set at create time and
read back from Describe but never updated. AWS puts them on /v1/tags/{arn},
which AppSync already owned - and two JAX-RS resource methods cannot claim the
same path and method. Resolved the way /tags/{arn} already was: the dispatch and
wire-shape logic moved out of SharedTagsController into a shared TagDispatcher,
a V1TagsController serves /v1/tags/{arn} on top of it, and the two handler sets
are kept apart by a @V1Tags qualifier so each service stays reachable only on
the path AWS defines for it. AppSync's three controller methods became
AppSyncTagHandler with its wire shape unchanged; MskTagHandler is new. MSK tags
clusters and configurations, so MskConfiguration gained a persisted tags map.

Serverless: CreateClusterV2 silently flattened a serverless request into a
provisioned cluster, which then reported itself as provisioned and echoed broker
metadata the caller never sent. It is now a first-class shape - clusterType,
a serverless envelope on the v2 response, and exactly one of provisioned and
serverless per request. The v1 API predates serverless and its ClusterInfo
cannot represent one, so DescribeCluster rejects it the way AWS does and
ListClusters omits it.

Validation: a create with no clusterName built an ARN containing
cluster/null/<uuid> and stored a cluster unaddressable by name. clusterName is
now required and length-checked, and the members AWS documents a range or an
enum for are checked too. The presence of kafkaVersion, numberOfBrokerNodes and
brokerNodeGroupInfo is deliberately still not required - the emulator has always
defaulted those, and tightening it is a separate, deliberate break.

Also: MskConfiguration.accountId was @JsonIgnore, the same persistence bug the
cluster model had - an async write-back after a reload had no account to target.
ConnectivityInfo gained the networkType member it was missing on both shapes.

* test(msk): point the v2 kafkaVersion assertions at the provisioned envelope

These two predate the v2 shape fix and asserted
clusterInfo.currentBrokerSoftwareInfo.kafkaVersion - the flat v1 layout on a v2
response, which is exactly what that fix corrected. They were codifying the bug,
so they moved to clusterInfo.provisioned.currentBrokerSoftwareInfo.kafkaVersion
rather than the view changing back.

* fix(msk): drop the broker-count ceiling and name the invalid parameter

Applies the two findings from the #2571 review to the code that is actually
going to land.

The 1-15 range came from the SDK/CLI reference, which carries an
__integerMin1Max15 shape for numberOfBrokerNodes. Two other AWS sources
contradict it: the REST API reference documents no minimum or maximum for that
member - on a page that does give ranges for its neighbours, volumeSize 1-16384
and revision min 1 - and the quota page allows 30 brokers per ZooKeeper cluster
and 60 per KRaft cluster, both adjustable upward. Capping at 15 rejected
clusters real MSK creates, turning "converges on the wrong number" into an
outright apply failure for every count from 16 up. The floor stays: a zero or
negative broker count is nonsense and every source agrees.

MSK's Error schema is message plus invalidParameter, "the parameter that caused
the error". Every validation failure now names the member it rejected, via the
four-argument AwsException the mapper already splats into the body. The
pre-existing configuration validations are left as they are - that is merged
code, not this change's.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
MAN$I VERMAandPriamo Germosen authored and GitHub committed 2026-08-26 23:17:03 -04:00
1 parent 2e843e9f23
commit 0205e4ed7e
48 files changed
+3090 -252

No files matched your search

@@ -59,7 +59,7 @@ class MskControllerIntegrationTest {
.get("/api/v2/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.5.1"));
.body("clusterInfo.provisioned.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.5.1"));
}
@Test
@@ -80,7 +80,326 @@ class MskControllerIntegrationTest {
.get("/api/v2/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.6.0"));
.body("clusterInfo.provisioned.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.6.0"));
}
@Test
void createClusterV1EchoesBrokerNodeGroupInfoNumberOfBrokerNodesAndTags() {
String clusterArn = given()
.contentType("application/json")
.body("""
{
"clusterName": "v1-metadata-test",
"kafkaVersion": "3.6.0",
"numberOfBrokerNodes": 3,
"brokerNodeGroupInfo": {
"instanceType": "kafka.m5.large",
"clientSubnets": ["subnet-aaa", "subnet-bbb"],
"securityGroups": ["sg-111"],
"storageInfo": {"ebsStorageInfo": {"volumeSize": 100}}
},
"tags": {"Environment": "example"}
}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.numberOfBrokerNodes", equalTo(3))
.body("clusterInfo.brokerNodeGroupInfo.instanceType", equalTo("kafka.m5.large"))
.body("clusterInfo.brokerNodeGroupInfo.clientSubnets", hasItem("subnet-aaa"))
.body("clusterInfo.brokerNodeGroupInfo.securityGroups", hasItem("sg-111"))
.body("clusterInfo.brokerNodeGroupInfo.storageInfo.ebsStorageInfo.volumeSize", equalTo(100))
.body("clusterInfo.tags.Environment", equalTo("example"));
}
@Test
void createClusterV1EchoesEncryptionClientAuthenticationAndLogging() {
String clusterArn = given()
.contentType("application/json")
.body("""
{
"clusterName": "v1-security-test",
"kafkaVersion": "3.6.0",
"numberOfBrokerNodes": 2,
"brokerNodeGroupInfo": {
"instanceType": "kafka.m5.large",
"clientSubnets": ["subnet-aaa"]
},
"encryptionInfo": {
"encryptionInTransit": {"clientBroker": "TLS", "inCluster": true},
"encryptionAtRest": {"dataVolumeKMSKeyId": "arn:aws:kms:us-east-1:123456789012:key/abc"}
},
"clientAuthentication": {
"sasl": {"scram": {"enabled": true}, "iam": {"enabled": false}},
"tls": {"certificateAuthorityArnList": ["arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/ca-1"], "enabled": true}
},
"enhancedMonitoring": "PER_BROKER",
"loggingInfo": {"brokerLogs": {"s3": {"bucket": "msk-logs", "enabled": true, "prefix": "kafka"}}}
}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.encryptionInfo.encryptionInTransit.clientBroker", equalTo("TLS"))
.body("clusterInfo.encryptionInfo.encryptionInTransit.inCluster", equalTo(true))
.body("clusterInfo.encryptionInfo.encryptionAtRest.dataVolumeKMSKeyId", equalTo("arn:aws:kms:us-east-1:123456789012:key/abc"))
.body("clusterInfo.clientAuthentication.sasl.scram.enabled", equalTo(true))
.body("clusterInfo.clientAuthentication.sasl.iam.enabled", equalTo(false))
.body("clusterInfo.clientAuthentication.tls.enabled", equalTo(true))
.body("clusterInfo.enhancedMonitoring", equalTo("PER_BROKER"))
.body("clusterInfo.loggingInfo.brokerLogs.s3.bucket", equalTo("msk-logs"))
.body("clusterInfo.loggingInfo.brokerLogs.s3.prefix", equalTo("kafka"));
}
// configurationInfo is a CreateCluster request member with no matching response member:
// AWS reports the cluster's configuration on currentBrokerSoftwareInfo instead, which is
// where terraform-provider-aws reads it back from.
@Test
void createClusterV1ReportsConfigurationOnCurrentBrokerSoftwareInfo() {
String clusterArn = given()
.contentType("application/json")
.body("""
{
"clusterName": "v1-configuration-test",
"kafkaVersion": "3.6.0",
"numberOfBrokerNodes": 1,
"configurationInfo": {
"arn": "arn:aws:kafka:us-east-1:123456789012:configuration/conf/1",
"revision": 3
}
}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.currentBrokerSoftwareInfo.configurationArn",
equalTo("arn:aws:kafka:us-east-1:123456789012:configuration/conf/1"))
.body("clusterInfo.currentBrokerSoftwareInfo.configurationRevision", equalTo(3))
.body("clusterInfo.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.6.0"))
.body("clusterInfo", not(hasKey("configurationInfo")));
}
// AWS resolves these server-side when CreateCluster omits them and echoes the resolved
// value back; returning null instead leaves a terraform plan permanently dirty.
@Test
void createClusterV1AppliesServerSideDefaultsForMonitoringAndEncryptionInTransit() {
String clusterArn = given()
.contentType("application/json")
.body("""
{"clusterName": "v1-defaults-test", "kafkaVersion": "3.6.0", "numberOfBrokerNodes": 1}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.enhancedMonitoring", equalTo("DEFAULT"))
.body("clusterInfo.encryptionInfo.encryptionInTransit.clientBroker", equalTo("TLS_PLAINTEXT"))
.body("clusterInfo.encryptionInfo.encryptionInTransit.inCluster", equalTo(true));
}
// The v2 ClusterInfo is not the flat v1 shape: everything provisioned-specific nests under
// "provisioned", which is the only place an AWS SDK v2 client looks for it.
@Test
void describeClusterV2NestsProvisionedMetadataAndKeepsTagsTopLevel() {
String clusterArn = given()
.contentType("application/json")
.body("""
{
"clusterName": "v2-metadata-test",
"tags": {"Environment": "prod"},
"provisioned": {
"kafkaVersion": "3.5.1",
"numberOfBrokerNodes": 3,
"brokerNodeGroupInfo": {
"instanceType": "kafka.t3.small",
"clientSubnets": ["subnet-ccc"]
},
"clientAuthentication": {"unauthenticated": {"enabled": true}},
"loggingInfo": {"brokerLogs": {"cloudWatchLogs": {"enabled": true, "logGroup": "msk-logs"}}},
"configurationInfo": {
"arn": "arn:aws:kafka:us-east-1:123456789012:configuration/conf/2",
"revision": 7
}
}
}
""")
.when()
.post("/api/v2/clusters")
.then()
.statusCode(200)
.body("clusterType", equalTo("PROVISIONED"))
.extract().path("clusterArn");
given()
.when()
.get("/api/v2/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.clusterType", equalTo("PROVISIONED"))
.body("clusterInfo.clusterArn", equalTo(clusterArn))
.body("clusterInfo.tags.Environment", equalTo("prod"))
.body("clusterInfo.provisioned.numberOfBrokerNodes", equalTo(3))
.body("clusterInfo.provisioned.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.5.1"))
.body("clusterInfo.provisioned.currentBrokerSoftwareInfo.configurationArn",
equalTo("arn:aws:kafka:us-east-1:123456789012:configuration/conf/2"))
.body("clusterInfo.provisioned.currentBrokerSoftwareInfo.configurationRevision", equalTo(7))
.body("clusterInfo.provisioned.brokerNodeGroupInfo.instanceType", equalTo("kafka.t3.small"))
.body("clusterInfo.provisioned.brokerNodeGroupInfo.clientSubnets", hasItem("subnet-ccc"))
.body("clusterInfo.provisioned.clientAuthentication.unauthenticated.enabled", equalTo(true))
.body("clusterInfo.provisioned.loggingInfo.brokerLogs.cloudWatchLogs.logGroup", equalTo("msk-logs"))
.body("clusterInfo.provisioned.zookeeperConnectString", notNullValue())
// the same members must NOT also appear flat, where a v2 client would not read them
.body("clusterInfo", not(hasKey("numberOfBrokerNodes")))
.body("clusterInfo", not(hasKey("brokerNodeGroupInfo")))
.body("clusterInfo", not(hasKey("currentBrokerSoftwareInfo")))
.body("clusterInfo", not(hasKey("clientAuthentication")))
.body("clusterInfo", not(hasKey("loggingInfo")));
}
@Test
void createClusterEchoesOpenMonitoringStorageModeAndRebalancing() {
String clusterArn = given()
.contentType("application/json")
.body("""
{
"clusterName": "v1-open-monitoring-test",
"kafkaVersion": "3.6.0",
"numberOfBrokerNodes": 1,
"storageMode": "TIERED",
"rebalancing": {"status": "ACTIVE"},
"openMonitoring": {
"prometheus": {
"jmxExporter": {"enabledInBroker": true},
"nodeExporter": {"enabledInBroker": false}
}
}
}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.storageMode", equalTo("TIERED"))
.body("clusterInfo.rebalancing.status", equalTo("ACTIVE"))
.body("clusterInfo.openMonitoring.prometheus.jmxExporter.enabledInBroker", equalTo(true))
.body("clusterInfo.openMonitoring.prometheus.nodeExporter.enabledInBroker", equalTo(false));
// and the v2 view nests them under provisioned, like every other provisioned member
given()
.when()
.get("/api/v2/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.provisioned.storageMode", equalTo("TIERED"))
.body("clusterInfo.provisioned.openMonitoring.prometheus.jmxExporter.enabledInBroker", equalTo(true))
.body("clusterInfo", not(hasKey("storageMode")))
.body("clusterInfo", not(hasKey("openMonitoring")));
}
@Test
void listClustersV2NestsProvisionedMetadataTheSameWayDescribeDoes() {
given()
.contentType("application/json")
.body("""
{
"clusterName": "v2-list-test",
"provisioned": {"kafkaVersion": "3.6.0", "numberOfBrokerNodes": 2}
}
""")
.when()
.post("/api/v2/clusters")
.then()
.statusCode(200);
given()
.when()
.get("/api/v2/clusters")
.then()
.statusCode(200)
.body("clusterInfoList.find { it.clusterName == 'v2-list-test' }.clusterType",
equalTo("PROVISIONED"))
.body("clusterInfoList.find { it.clusterName == 'v2-list-test' }.provisioned.numberOfBrokerNodes",
equalTo(2))
.body("clusterInfoList.find { it.clusterName == 'v2-list-test' }.provisioned.currentBrokerSoftwareInfo.kafkaVersion",
equalTo("3.6.0"));
}
@Test
void describeClusterDoesNotLeakInternalFields() {
String clusterArn = given()
.contentType("application/json")
.body("""
{"clusterName": "v1-no-internal-fields-test", "kafkaVersion": "3.6.0"}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo", notNullValue())
.body("clusterInfo.clusterArn", equalTo(clusterArn))
.body("clusterInfo", not(hasKey("bootstrapBrokers")))
.body("clusterInfo", not(hasKey("containerId")))
.body("clusterInfo", not(hasKey("accountId")))
.body("clusterInfo", not(hasKey("volumeId")));
given()
.when()
.get("/api/v2/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo", not(hasKey("bootstrapBrokers")))
.body("clusterInfo", not(hasKey("containerId")))
.body("clusterInfo", not(hasKey("accountId")))
.body("clusterInfo", not(hasKey("volumeId")))
.body("clusterInfo.provisioned", not(hasKey("bootstrapBrokers")))
.body("clusterInfo.provisioned", not(hasKey("containerId")))
.body("clusterInfo.provisioned", not(hasKey("accountId")))
.body("clusterInfo.provisioned", not(hasKey("volumeId")));
}
@Test
@@ -505,4 +824,304 @@ class MskControllerIntegrationTest {
.then()
.statusCode(400);
}
// ── Tags (/v1/tags/{arn}, shared with AppSync behind V1TagsController) ────────────────
@Test
void clusterTagsRoundTripThroughTheTagEndpoints() {
String clusterArn = given()
.contentType("application/json")
.body("""
{"clusterName": "tag-cluster", "kafkaVersion": "3.6.0", "tags": {"Environment": "example"}}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
// tags set at create time are visible to ListTagsForResource
given()
.urlEncodingEnabled(false)
.when()
.get("/v1/tags/" + clusterArn)
.then()
.statusCode(200)
.body("tags.Environment", equalTo("example"));
given()
.contentType("application/json")
.body("""
{"tags": {"Team": "data", "Environment": "prod"}}
""")
.urlEncodingEnabled(false)
.when()
.post("/v1/tags/" + clusterArn)
.then()
.statusCode(204);
given()
.urlEncodingEnabled(false)
.when()
.get("/v1/tags/" + clusterArn)
.then()
.statusCode(200)
.body("tags.Team", equalTo("data"))
.body("tags.Environment", equalTo("prod"));
// and DescribeCluster echoes the same set, so a tag update is not invisible to a refresh
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.tags.Team", equalTo("data"))
.body("clusterInfo.tags.Environment", equalTo("prod"));
given()
.queryParam("tagKeys", "Team")
.urlEncodingEnabled(false)
.when()
.delete("/v1/tags/" + clusterArn)
.then()
.statusCode(204);
given()
.urlEncodingEnabled(false)
.when()
.get("/v1/tags/" + clusterArn)
.then()
.statusCode(200)
.body("tags", not(hasKey("Team")))
.body("tags.Environment", equalTo("prod"));
}
@Test
void configurationTagsRoundTripThroughTheTagEndpoints() {
String properties = Base64.getEncoder()
.encodeToString("auto.create.topics.enable=true".getBytes(StandardCharsets.UTF_8));
String arn = given()
.contentType("application/json")
.body("""
{"name": "tagged-config", "description": "d", "kafkaVersions": ["3.6.0"], "serverProperties": "%s"}
""".formatted(properties))
.when()
.post("/v1/configurations")
.then()
.statusCode(200)
.extract().path("arn");
given()
.contentType("application/json")
.body("""
{"tags": {"Owner": "platform"}}
""")
.urlEncodingEnabled(false)
.when()
.post("/v1/tags/" + arn)
.then()
.statusCode(204);
given()
.urlEncodingEnabled(false)
.when()
.get("/v1/tags/" + arn)
.then()
.statusCode(200)
.body("tags.Owner", equalTo("platform"));
// AWS's DescribeConfiguration shape has no tags member, so they stay out of that view
given()
.when()
.get("/v1/configurations/{arn}", arn)
.then()
.statusCode(200)
.body("$", not(hasKey("tags")));
}
@Test
void tagEndpointsReturnNotFoundForAnUnknownKafkaArn() {
String missing = "arn:aws:kafka:us-east-1:000000000000:cluster/nope/00000000-0000-0000-0000-000000000000";
given()
.urlEncodingEnabled(false)
.when()
.get("/v1/tags/" + missing)
.then()
.statusCode(404);
}
// ── CreateCluster validation ─────────────────────────────────────────────────────────
@Test
void createClusterRejectsAMissingClusterName() {
given()
.contentType("application/json")
.body("""
{"kafkaVersion": "3.6.0"}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(400)
.body("message", containsString("clusterName"));
}
@Test
void createClusterRejectsOutOfRangeAndUnknownEnumValues() {
given()
.contentType("application/json")
.body("""
{"clusterName": "zero-brokers", "kafkaVersion": "3.6.0", "numberOfBrokerNodes": 0}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(400)
.body("message", containsString("numberOfBrokerNodes"))
// MSK's Error schema names the offending member alongside the message
.body("invalidParameter", equalTo("numberOfBrokerNodes"));
given()
.contentType("application/json")
.body("""
{
"clusterName": "bad-volume-size",
"kafkaVersion": "3.6.0",
"brokerNodeGroupInfo": {"storageInfo": {"ebsStorageInfo": {"volumeSize": 0}}}
}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(400)
.body("message", containsString("volumeSize"));
given()
.contentType("application/json")
.body("""
{"clusterName": "bad-monitoring", "kafkaVersion": "3.6.0", "enhancedMonitoring": "SOMETIMES"}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(400)
.body("message", containsString("enhancedMonitoring"));
given()
.contentType("application/json")
.body("""
{
"clusterName": "bad-client-broker",
"kafkaVersion": "3.6.0",
"encryptionInfo": {"encryptionInTransit": {"clientBroker": "MAYBE"}}
}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(400)
.body("message", containsString("clientBroker"));
}
// The SDK model caps numberOfBrokerNodes at 15, but the REST API reference documents no
// maximum and the quota page allows 30 per ZooKeeper cluster and 60 per KRaft cluster, both
// adjustable. Rejecting these would break clusters real MSK creates happily.
@Test
void createClusterAcceptsBrokerCountsAboveTheSdkModelCap() {
String clusterArn = given()
.contentType("application/json")
.body("""
{"clusterName": "thirty-brokers", "kafkaVersion": "3.6.0", "numberOfBrokerNodes": 30}
""")
.when()
.post("/v1/clusters")
.then()
.statusCode(200)
.extract().path("clusterArn");
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.numberOfBrokerNodes", equalTo(30));
}
// ── Serverless clusters ──────────────────────────────────────────────────────────────
@Test
void createClusterV2SupportsServerlessAndKeepsItOutOfTheV1Api() {
String clusterArn = given()
.contentType("application/json")
.body("""
{
"clusterName": "serverless-cluster",
"tags": {"Environment": "prod"},
"serverless": {
"vpcConfigs": [{"subnetIds": ["subnet-aaa", "subnet-bbb"], "securityGroupIds": ["sg-111"]}],
"clientAuthentication": {"sasl": {"iam": {"enabled": true}}}
}
}
""")
.when()
.post("/api/v2/clusters")
.then()
.statusCode(200)
.body("clusterType", equalTo("SERVERLESS"))
.extract().path("clusterArn");
given()
.when()
.get("/api/v2/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(200)
.body("clusterInfo.clusterType", equalTo("SERVERLESS"))
.body("clusterInfo.tags.Environment", equalTo("prod"))
.body("clusterInfo.serverless.vpcConfigs[0].subnetIds", hasItem("subnet-aaa"))
.body("clusterInfo.serverless.vpcConfigs[0].securityGroupIds", hasItem("sg-111"))
.body("clusterInfo.serverless.clientAuthentication.sasl.iam.enabled", equalTo(true))
// a serverless cluster has no provisioned envelope at all
.body("clusterInfo", not(hasKey("provisioned")));
// the v1 API predates serverless and cannot describe one
given()
.when()
.get("/v1/clusters/{clusterArn}", clusterArn)
.then()
.statusCode(400)
.body("message", containsString("DescribeClusterV2"));
given()
.when()
.get("/v1/clusters")
.then()
.statusCode(200)
.body("clusterInfoList.findAll { it.clusterName == 'serverless-cluster' }", hasSize(0));
given()
.when()
.get("/api/v2/clusters")
.then()
.statusCode(200)
.body("clusterInfoList.findAll { it.clusterName == 'serverless-cluster' }", hasSize(1));
}
@Test
void createClusterV2RejectsBothProvisionedAndServerless() {
given()
.contentType("application/json")
.body("""
{
"clusterName": "both-shapes",
"provisioned": {"kafkaVersion": "3.6.0"},
"serverless": {"vpcConfigs": [{"subnetIds": ["subnet-aaa"]}]}
}
""")
.when()
.post("/api/v2/clusters")
.then()
.statusCode(400)
.body("message", containsString("Exactly one"));
}
}
@@ -9,19 +9,40 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.msk.model.ClusterState;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.hectorvent.floci.services.msk.model.BrokerNodeGroupInfo;
import io.github.hectorvent.floci.services.msk.model.ClientAuthentication;
import io.github.hectorvent.floci.services.msk.model.ConfigurationInfo;
import io.github.hectorvent.floci.services.msk.model.ConfigurationRevision;
import io.github.hectorvent.floci.services.msk.model.ConfigurationRevisionDetail;
import io.github.hectorvent.floci.services.msk.model.ConfigurationState;
import io.github.hectorvent.floci.services.msk.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.msk.model.CreateClusterV2Request;
import io.github.hectorvent.floci.services.msk.model.EncryptionInTransit;
import io.github.hectorvent.floci.services.msk.model.EbsStorageInfo;
import io.github.hectorvent.floci.services.msk.model.EncryptionInfo;
import io.github.hectorvent.floci.services.msk.model.JmxExporter;
import io.github.hectorvent.floci.services.msk.model.LoggingInfo;
import io.github.hectorvent.floci.services.msk.model.OpenMonitoring;
import io.github.hectorvent.floci.services.msk.model.Prometheus;
import io.github.hectorvent.floci.services.msk.model.Rebalancing;
import io.github.hectorvent.floci.services.msk.model.MskCluster;
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.hectorvent.floci.services.msk.model.ProvisionedRequest;
import io.github.hectorvent.floci.services.msk.model.Sasl;
import io.github.hectorvent.floci.services.msk.model.Scram;
import io.github.hectorvent.floci.services.msk.model.Serverless;
import io.github.hectorvent.floci.services.msk.model.StorageInfo;
import io.github.hectorvent.floci.services.msk.model.VpcConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@@ -115,6 +136,204 @@ class MskServiceTest {
assertTrue(mskService.listClusters().isEmpty());
}
@Test
void createClusterPersistsRequestMetadata() {
CreateClusterRequest request = new CreateClusterRequest();
request.setClusterName("meta-cluster");
request.setKafkaVersion("3.5.1");
request.setNumberOfBrokerNodes(3);
BrokerNodeGroupInfo nodeGroup = new BrokerNodeGroupInfo();
nodeGroup.setInstanceType("kafka.m5.large");
nodeGroup.setClientSubnets(List.of("subnet-aaa", "subnet-bbb"));
nodeGroup.setSecurityGroups(List.of("sg-111"));
request.setBrokerNodeGroupInfo(nodeGroup);
EncryptionInTransit encryptionInTransit = new EncryptionInTransit();
encryptionInTransit.setClientBroker("TLS");
encryptionInTransit.setInCluster(true);
EncryptionInfo encryptionInfo = new EncryptionInfo();
encryptionInfo.setEncryptionInTransit(encryptionInTransit);
request.setEncryptionInfo(encryptionInfo);
Sasl sasl = new Sasl();
Scram scram = new Scram();
scram.setEnabled(true);
sasl.setScram(scram);
ClientAuthentication clientAuthentication = new ClientAuthentication();
clientAuthentication.setSasl(sasl);
request.setClientAuthentication(clientAuthentication);
request.setEnhancedMonitoring("PER_BROKER");
request.setLoggingInfo(new LoggingInfo());
ConfigurationInfo configurationInfo = new ConfigurationInfo();
configurationInfo.setArn("arn:aws:kafka:us-east-1:123456789012:configuration/conf/1");
configurationInfo.setRevision(2L);
request.setConfigurationInfo(configurationInfo);
request.setTags(Map.of("Environment", "example"));
MskCluster cluster = mskService.createCluster(request);
assertEquals(3, cluster.getNumberOfBrokerNodes());
assertEquals("kafka.m5.large", cluster.getBrokerNodeGroupInfo().getInstanceType());
assertEquals(List.of("subnet-aaa", "subnet-bbb"), cluster.getBrokerNodeGroupInfo().getClientSubnets());
assertEquals(List.of("sg-111"), cluster.getBrokerNodeGroupInfo().getSecurityGroups());
assertEquals("TLS", cluster.getEncryptionInfo().getEncryptionInTransit().getClientBroker());
assertTrue(cluster.getEncryptionInfo().getEncryptionInTransit().getInCluster());
assertTrue(cluster.getClientAuthentication().getSasl().getScram().getEnabled());
assertEquals("PER_BROKER", cluster.getEnhancedMonitoring());
assertNotNull(cluster.getLoggingInfo());
assertEquals("arn:aws:kafka:us-east-1:123456789012:configuration/conf/1",
cluster.getCurrentBrokerSoftwareInfo().getConfigurationArn());
assertEquals(2L, cluster.getCurrentBrokerSoftwareInfo().getConfigurationRevision());
assertEquals("example", cluster.getTags().get("Environment"));
MskCluster described = mskService.describeCluster(cluster.getClusterArn());
assertEquals(3, described.getNumberOfBrokerNodes());
assertEquals("kafka.m5.large", described.getBrokerNodeGroupInfo().getInstanceType());
assertEquals("example", described.getTags().get("Environment"));
}
@Test
void createClusterV2MergesTopLevelTagsAndProvisionedFields() {
CreateClusterV2Request request = new CreateClusterV2Request();
request.setClusterName("v2-meta-cluster");
request.setTags(Map.of("Team", "data"));
ProvisionedRequest provisioned = new ProvisionedRequest();
provisioned.setKafkaVersion("3.4.0");
provisioned.setNumberOfBrokerNodes(5);
BrokerNodeGroupInfo nodeGroup = new BrokerNodeGroupInfo();
nodeGroup.setInstanceType("kafka.t3.small");
nodeGroup.setClientSubnets(List.of("subnet-ccc"));
provisioned.setBrokerNodeGroupInfo(nodeGroup);
request.setProvisioned(provisioned);
MskCluster cluster = mskService.createCluster(request);
assertEquals("v2-meta-cluster", cluster.getClusterName());
assertEquals("3.4.0", cluster.getCurrentBrokerSoftwareInfo().getKafkaVersion());
assertEquals(5, cluster.getNumberOfBrokerNodes());
assertEquals("kafka.t3.small", cluster.getBrokerNodeGroupInfo().getInstanceType());
assertEquals(List.of("subnet-ccc"), cluster.getBrokerNodeGroupInfo().getClientSubnets());
assertEquals("data", cluster.getTags().get("Team"));
}
@Test
void createClusterV2MapsProvisionedConfigurationOntoCurrentBrokerSoftwareInfo() {
CreateClusterV2Request request = new CreateClusterV2Request();
request.setClusterName("v2-configuration-cluster");
ProvisionedRequest provisioned = new ProvisionedRequest();
provisioned.setKafkaVersion("3.6.0");
ConfigurationInfo configurationInfo = new ConfigurationInfo();
configurationInfo.setArn("arn:aws:kafka:us-east-1:123456789012:configuration/conf/9");
configurationInfo.setRevision(4L);
provisioned.setConfigurationInfo(configurationInfo);
request.setProvisioned(provisioned);
MskCluster cluster = mskService.createCluster(request);
assertEquals("arn:aws:kafka:us-east-1:123456789012:configuration/conf/9",
cluster.getCurrentBrokerSoftwareInfo().getConfigurationArn());
assertEquals(4L, cluster.getCurrentBrokerSoftwareInfo().getConfigurationRevision());
}
@Test
void createClusterV2PersistsOpenMonitoringStorageModeAndRebalancing() {
CreateClusterV2Request request = new CreateClusterV2Request();
request.setClusterName("v2-open-monitoring-cluster");
JmxExporter jmxExporter = new JmxExporter();
jmxExporter.setEnabledInBroker(true);
Prometheus prometheus = new Prometheus();
prometheus.setJmxExporter(jmxExporter);
OpenMonitoring openMonitoring = new OpenMonitoring();
openMonitoring.setPrometheus(prometheus);
Rebalancing rebalancing = new Rebalancing();
rebalancing.setStatus("PAUSED");
ProvisionedRequest provisioned = new ProvisionedRequest();
provisioned.setKafkaVersion("3.6.0");
provisioned.setOpenMonitoring(openMonitoring);
provisioned.setStorageMode("TIERED");
provisioned.setRebalancing(rebalancing);
request.setProvisioned(provisioned);
MskCluster cluster = mskService.createCluster(request);
assertTrue(cluster.getOpenMonitoring().getPrometheus().getJmxExporter().getEnabledInBroker());
assertEquals("TIERED", cluster.getStorageMode());
assertEquals("PAUSED", cluster.getRebalancing().getStatus());
}
@Test
void createClusterAppliesServerSideDefaultsWhenMembersAreAbsent() {
CreateClusterRequest request = new CreateClusterRequest();
request.setClusterName("defaults-cluster");
request.setKafkaVersion("3.6.0");
MskCluster cluster = mskService.createCluster(request);
assertEquals("DEFAULT", cluster.getEnhancedMonitoring());
assertEquals("TLS_PLAINTEXT", cluster.getEncryptionInfo().getEncryptionInTransit().getClientBroker());
assertTrue(cluster.getEncryptionInfo().getEncryptionInTransit().getInCluster());
}
@Test
void createClusterDoesNotOverrideExplicitlyRequestedEncryptionInTransit() {
CreateClusterRequest request = new CreateClusterRequest();
request.setClusterName("explicit-encryption-cluster");
request.setKafkaVersion("3.6.0");
EncryptionInTransit inTransit = new EncryptionInTransit();
inTransit.setClientBroker("PLAINTEXT");
inTransit.setInCluster(false);
EncryptionInfo encryptionInfo = new EncryptionInfo();
encryptionInfo.setEncryptionInTransit(inTransit);
request.setEncryptionInfo(encryptionInfo);
MskCluster cluster = mskService.createCluster(request);
assertEquals("PLAINTEXT", cluster.getEncryptionInfo().getEncryptionInTransit().getClientBroker());
assertFalse(cluster.getEncryptionInfo().getEncryptionInTransit().getInCluster());
}
// MskCluster is the shape WalStorage/PersistentStorage/HybridStorage write. All three build
// their mapper the same way this test does - JavaTimeModule and a date format, no view or
// mixin - so a @JsonIgnore on the model hides the field from the store, not just from the
// API: a restart would come back with no bootstrap brokers (breaking GetBootstrapBrokers
// and the Pipes Kafka source) and no container or volume ID (orphaning the Docker
// resources). Responses stay clean through MskController's views instead - see
// MskControllerIntegrationTest#describeClusterDoesNotLeakInternalFields.
@Test
void clusterSurvivesTheStorageMapperRoundTripWithItsInternalFields() throws Exception {
CreateClusterRequest request = new CreateClusterRequest();
request.setClusterName("persistence-cluster");
request.setKafkaVersion("3.6.0");
request.setNumberOfBrokerNodes(3);
request.setTags(Map.of("Environment", "example"));
MskCluster cluster = mskService.createCluster(request);
cluster.setContainerId("container-abc");
ObjectMapper storageMapper = new ObjectMapper();
storageMapper.registerModule(new JavaTimeModule());
storageMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
MskCluster reloaded = storageMapper.readValue(storageMapper.writeValueAsString(cluster), MskCluster.class);
assertEquals(cluster.getBootstrapBrokers(), reloaded.getBootstrapBrokers());
assertNotNull(reloaded.getBootstrapBrokers());
assertEquals("container-abc", reloaded.getContainerId());
assertEquals(cluster.getVolumeId(), reloaded.getVolumeId());
assertNotNull(reloaded.getVolumeId());
assertEquals(cluster.getAccountId(), reloaded.getAccountId());
assertNotNull(reloaded.getAccountId());
// and the client-facing metadata survives too
assertEquals(3, reloaded.getNumberOfBrokerNodes());
assertEquals("example", reloaded.getTags().get("Environment"));
assertEquals("3.6.0", reloaded.getCurrentBrokerSoftwareInfo().getKafkaVersion());
}
@Test
void createConfiguration() {
MskConfiguration configuration = mskService.createConfiguration(
@@ -562,4 +781,166 @@ class MskServiceTest {
"revision " + revision + " lost its serverProperties");
}
}
// ── Tags ─────────────────────────────────────────────────────────────────────────────
@Test
void tagAndUntagResourceWorkOnClustersAndConfigurations() {
MskCluster cluster = mskService.createCluster("tagged-cluster");
mskService.tagResource(cluster.getClusterArn(), Map.of("Environment", "example"));
assertEquals("example", mskService.listTagsForResource(cluster.getClusterArn()).get("Environment"));
MskConfiguration configuration = mskService.createConfiguration(
"tagged-config", "d", List.of("3.6.0"), "auto.create.topics.enable=true");
mskService.tagResource(configuration.getArn(), Map.of("Owner", "platform"));
assertEquals("platform", mskService.listTagsForResource(configuration.getArn()).get("Owner"));
mskService.untagResource(cluster.getClusterArn(), List.of("Environment"));
assertTrue(mskService.listTagsForResource(cluster.getClusterArn()).isEmpty());
}
// createCluster stores whatever map the request carried, which for an immutable Map.of would
// reject an in-place putAll - the tag write has to copy instead.
@Test
void tagResourceCanExtendAnImmutableTagMapSetAtCreateTime() {
CreateClusterRequest request = new CreateClusterRequest();
request.setClusterName("immutable-tags-cluster");
request.setTags(Map.of("Environment", "example"));
MskCluster cluster = mskService.createCluster(request);
mskService.tagResource(cluster.getClusterArn(), Map.of("Team", "data"));
Map<String, String> tags = mskService.listTagsForResource(cluster.getClusterArn());
assertEquals("example", tags.get("Environment"));
assertEquals("data", tags.get("Team"));
}
@Test
void tagOperationsOnAnUnknownArnAreNotFound() {
String missing = "arn:aws:kafka:us-east-1:000000000000:cluster/nope/id";
assertThrows(AwsException.class, () -> mskService.listTagsForResource(missing));
assertThrows(AwsException.class, () -> mskService.tagResource(missing, Map.of("a", "b")));
assertThrows(AwsException.class, () -> mskService.untagResource(missing, List.of("a")));
}
@Test
void configurationKeepsTagsAndAccountIdAcrossTheStorageMapperRoundTrip() throws Exception {
MskConfiguration configuration = mskService.createConfiguration(
"persisted-config", "d", List.of("3.6.0"), "auto.create.topics.enable=true");
mskService.tagResource(configuration.getArn(), Map.of("Owner", "platform"));
MskConfiguration tagged = mskService.describeConfiguration(configuration.getArn());
ObjectMapper storageMapper = new ObjectMapper();
storageMapper.registerModule(new JavaTimeModule());
storageMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
MskConfiguration reloaded = storageMapper.readValue(
storageMapper.writeValueAsString(tagged), MskConfiguration.class);
assertEquals("platform", reloaded.getTags().get("Owner"));
assertEquals(tagged.getAccountId(), reloaded.getAccountId());
assertNotNull(reloaded.getAccountId());
}
// ── CreateCluster validation ─────────────────────────────────────────────────────────
@Test
void createClusterRejectsAMissingOrOversizedClusterName() {
CreateClusterRequest noName = new CreateClusterRequest();
noName.setKafkaVersion("3.6.0");
assertThrows(AwsException.class, () -> mskService.createCluster(noName));
CreateClusterRequest longName = new CreateClusterRequest();
longName.setClusterName("c".repeat(65));
assertThrows(AwsException.class, () -> mskService.createCluster(longName));
}
@Test
void createClusterRejectsOnlyNonsensicalBrokerCountsAndOutOfRangeVolumeSize() {
// No upper bound: the SDK model says 15, but the REST reference documents no maximum and
// the quota page allows 30 (ZooKeeper) / 60 (KRaft), adjustable upward.
CreateClusterRequest manyBrokers = new CreateClusterRequest();
manyBrokers.setClusterName("many-brokers");
manyBrokers.setNumberOfBrokerNodes(30);
assertEquals(30, mskService.createCluster(manyBrokers).getNumberOfBrokerNodes());
CreateClusterRequest tooFew = new CreateClusterRequest();
tooFew.setClusterName("too-few");
tooFew.setNumberOfBrokerNodes(0);
assertThrows(AwsException.class, () -> mskService.createCluster(tooFew));
CreateClusterRequest badVolume = new CreateClusterRequest();
badVolume.setClusterName("bad-volume");
EbsStorageInfo ebs = new EbsStorageInfo();
ebs.setVolumeSize(16385);
StorageInfo storageInfo = new StorageInfo();
storageInfo.setEbsStorageInfo(ebs);
BrokerNodeGroupInfo nodeGroup = new BrokerNodeGroupInfo();
nodeGroup.setStorageInfo(storageInfo);
badVolume.setBrokerNodeGroupInfo(nodeGroup);
assertThrows(AwsException.class, () -> mskService.createCluster(badVolume));
}
@Test
void createClusterRejectsUnknownEnumValuesButAcceptsTheDocumentedOnes() {
CreateClusterRequest bad = new CreateClusterRequest();
bad.setClusterName("bad-monitoring");
bad.setEnhancedMonitoring("SOMETIMES");
assertThrows(AwsException.class, () -> mskService.createCluster(bad));
CreateClusterRequest good = new CreateClusterRequest();
good.setClusterName("good-monitoring");
good.setEnhancedMonitoring("PER_TOPIC_PER_PARTITION");
good.setStorageMode("TIERED");
assertEquals("PER_TOPIC_PER_PARTITION", mskService.createCluster(good).getEnhancedMonitoring());
}
// ── Serverless ───────────────────────────────────────────────────────────────────────
@Test
void createClusterV2CreatesAServerlessClusterWithoutProvisionedMetadata() {
VpcConfig vpcConfig = new VpcConfig();
vpcConfig.setSubnetIds(List.of("subnet-aaa"));
Serverless serverless = new Serverless();
serverless.setVpcConfigs(List.of(vpcConfig));
CreateClusterV2Request request = new CreateClusterV2Request();
request.setClusterName("serverless-cluster");
request.setServerless(serverless);
MskCluster cluster = mskService.createCluster(request);
assertTrue(mskService.isServerless(cluster));
assertEquals("SERVERLESS", cluster.getClusterType());
assertEquals(List.of("subnet-aaa"), cluster.getServerless().getVpcConfigs().get(0).getSubnetIds());
assertNull(cluster.getBrokerNodeGroupInfo());
assertNull(cluster.getCurrentBrokerSoftwareInfo());
assertEquals(0, cluster.getNumberOfBrokerNodes());
}
@Test
void v1ReadsExcludeServerlessClusters() {
Serverless serverless = new Serverless();
serverless.setVpcConfigs(List.of(new VpcConfig()));
CreateClusterV2Request request = new CreateClusterV2Request();
request.setClusterName("serverless-cluster");
request.setServerless(serverless);
MskCluster serverlessCluster = mskService.createCluster(request);
mskService.createCluster("provisioned-cluster");
assertThrows(AwsException.class, () -> mskService.describeClusterV1(serverlessCluster.getClusterArn()));
assertEquals(2, mskService.listClusters().size());
assertEquals(1, mskService.listProvisionedClusters().size());
assertEquals("provisioned-cluster", mskService.listProvisionedClusters().get(0).getClusterName());
}
@Test
void createClusterV2RejectsBothProvisionedAndServerless() {
CreateClusterV2Request request = new CreateClusterV2Request();
request.setClusterName("both-shapes");
request.setProvisioned(new ProvisionedRequest());
request.setServerless(new Serverless());
assertThrows(AwsException.class, () -> mskService.createCluster(request));
}
}