feat(msk): add configuration CRUD (Create/List/Describe/Delete) (#2336)

* feat(msk): add configuration CRUD (Create/List/Describe/Delete)

MskController only served /v1/clusters and /api/v2/clusters, so every
configuration action 404s. An MSK configuration is the only supported
way to set broker-level server_properties, and aws_msk_configuration /
aws_msk_domain_policy are first-class Terraform resources - any stack
setting broker properties failed before the cluster was even attempted.

Adds a second StorageBackend on MskService (msk-configurations.json,
mirroring msk-clusters.json), a new MskConfiguration model, and four
endpoints on MskController mirroring the existing cluster handlers.
serverProperties is base64 on the wire; decoded and kept internal
(@JsonIgnore) since AWS only returns it via DescribeConfigurationRevision,
which is a separate follow-up issue - this stays plain CRUD.

Field names verified against botocore's actual kafka service model
rather than trusting the API reference docs verbatim: every field is
lowerCamelCase, including DeleteConfigurationResponse's `arn` (the
public API reference page shows "Arn" capitalized, which does not
match the real wire format).

* fix(msk): validate request field types and persist serverProperties

CreateConfiguration cast request fields directly (String)/(List<String>),
so a wrong-typed field threw ClassCastException instead of an AWS-shaped
BadRequestException, surfacing as an internal server error.

serverProperties was @JsonIgnore, which excludes it from Jackson
serialization entirely - not just REST responses, but also the
persistent/hybrid/wal StorageBackend serialization that uses the same
model. A configuration would silently lose its broker properties on
reload under any non-memory storage mode. The field now serializes
normally; the controller instead builds explicit response views for
Describe/List/Create so serverProperties still never appears on the
wire outside CreateConfiguration's own request, matching AWS (which
only returns it via the out-of-scope DescribeConfigurationRevision).

* fix(msk): default kafkaVersions to an empty array when omitted

kafkaVersions is optional on CreateConfigurationRequest, but
asStringList returns null when it's absent, and toConfigurationView
put that null straight into the response - AWS's Configuration shape
always populates it as an array. Default it the same way description
already is. No existing test created a configuration without the
field, which is why it slipped through.

* feat(msk): support maxResults/nextToken pagination on ListConfigurations

ListConfigurations previously returned every configuration in one
response, ignoring the maxResults/nextToken query parameters the
model declares. Mirrors the existing pagination pattern from
BedrockAgentCoreGatewayService (ListResult<T> + a private paginate()
helper): the cursor is the last returned item's ARN, base64
URL-encoded, resumed by scanning the ARN-sorted list past that value.
maxResults is bounded to [1, 100] and an undecodable token both throw
BadRequestException, matching CreateConfiguration's existing error
family for this service.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-15 21:50:20 -04:00
1 parent 42022fe937
commit 4c510e576c
9 files changed
+705 -1

No files matched your search

@@ -3,8 +3,17 @@ package io.github.hectorvent.floci.services.msk;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
@QuarkusTest
class MskControllerIntegrationTest {
@@ -71,4 +80,211 @@ class MskControllerIntegrationTest {
.statusCode(200)
.body("clusterInfo.currentBrokerSoftwareInfo.kafkaVersion", equalTo("3.6.0"));
}
@Test
void configurationCrudRoundTrip() {
String properties = "auto.create.topics.enable=true\nlog.retention.hours=168";
String propertiesB64 = Base64.getEncoder().encodeToString(properties.getBytes(StandardCharsets.UTF_8));
String arn = given()
.contentType("application/json")
.body("""
{"name": "test-config", "description": "a test config", "kafkaVersions": ["3.6.0"], "serverProperties": "%s"}
""".formatted(propertiesB64))
.when()
.post("/v1/configurations")
.then()
.statusCode(200)
.body("name", equalTo("test-config"))
.body("state", equalTo("ACTIVE"))
.body("latestRevision.revision", equalTo(1))
.extract().path("arn");
given()
.when()
.get("/v1/configurations/{arn}", arn)
.then()
.statusCode(200)
.body("name", equalTo("test-config"))
.body("description", equalTo("a test config"))
.body("kafkaVersions", hasSize(1))
.body("arn", equalTo(arn));
given()
.when()
.get("/v1/configurations")
.then()
.statusCode(200)
.body("configurations.name", hasItem("test-config"));
given()
.when()
.delete("/v1/configurations/{arn}", arn)
.then()
.statusCode(200)
.body("arn", equalTo(arn))
.body("state", equalTo("DELETING"));
given()
.when()
.get("/v1/configurations/{arn}", arn)
.then()
.statusCode(404);
}
@Test
void createConfigurationRejectsNonBase64ServerProperties() {
given()
.contentType("application/json")
.body("""
{"name": "bad-config", "kafkaVersions": ["3.6.0"], "serverProperties": "not-valid-base64!!"}
""")
.when()
.post("/v1/configurations")
.then()
.statusCode(400);
}
// A wrong-typed field must fail with an AWS-shaped 400, not an unhandled
// ClassCastException surfacing as a 500.
@Test
void createConfigurationRejectsNonStringName() {
given()
.contentType("application/json")
.body("""
{"name": 123, "kafkaVersions": ["3.6.0"], "serverProperties": "cHJvcHM="}
""")
.when()
.post("/v1/configurations")
.then()
.statusCode(400);
}
@Test
void createConfigurationRejectsNonArrayKafkaVersions() {
given()
.contentType("application/json")
.body("""
{"name": "bad-config", "kafkaVersions": "3.6.0", "serverProperties": "cHJvcHM="}
""")
.when()
.post("/v1/configurations")
.then()
.statusCode(400);
}
@Test
void createConfigurationRejectsKafkaVersionsWithNonStringElements() {
given()
.contentType("application/json")
.body("""
{"name": "bad-config", "kafkaVersions": [3.6], "serverProperties": "cHJvcHM="}
""")
.when()
.post("/v1/configurations")
.then()
.statusCode(400);
}
@Test
void describeConfigurationReturnsNotFoundForUnknownArn() {
given()
.when()
.get("/v1/configurations/{arn}", "arn:aws:kafka:us-east-1:000000000000:configuration/missing/id")
.then()
.statusCode(404);
}
// kafkaVersions is optional on CreateConfigurationRequest. Omitting it must not leak a
// null into the "kafkaVersions" field of the Configuration shape returned by
// DescribeConfiguration/ListConfigurations, which AWS always populates as an array.
@Test
void configurationWithoutKafkaVersionsReturnsEmptyArrayNotNull() {
String properties = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));
String arn = given()
.contentType("application/json")
.body("""
{"name": "no-versions-config", "serverProperties": "%s"}
""".formatted(properties))
.when()
.post("/v1/configurations")
.then()
.statusCode(200)
.extract().path("arn");
given()
.when()
.get("/v1/configurations/{arn}", arn)
.then()
.statusCode(200)
.body("kafkaVersions", empty());
given()
.when()
.get("/v1/configurations")
.then()
.statusCode(200)
.body("configurations.find { it.arn == '" + arn + "' }.kafkaVersions", empty());
}
@Test
void listConfigurationsPaginatesWithMaxResultsAndNextToken() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String properties = Base64.getEncoder().encodeToString("props".getBytes(StandardCharsets.UTF_8));
given().contentType("application/json")
.body("""
{"name": "page-a-%s", "serverProperties": "%s"}
""".formatted(suffix, properties))
.when().post("/v1/configurations")
.then().statusCode(200);
given().contentType("application/json")
.body("""
{"name": "page-b-%s", "serverProperties": "%s"}
""".formatted(suffix, properties))
.when().post("/v1/configurations")
.then().statusCode(200);
var page1 = given()
.when().get("/v1/configurations?maxResults=1")
.then().statusCode(200)
.body("configurations", hasSize(1))
.body("nextToken", notNullValue())
.extract().jsonPath();
String page1Arn = page1.getString("configurations[0].arn");
String token = page1.getString("nextToken");
given()
.when().get("/v1/configurations?maxResults=1&nextToken=" + token)
.then().statusCode(200)
.body("configurations", hasSize(1))
.body("configurations[0].arn", not(equalTo(page1Arn)));
}
@Test
void listConfigurationsRejectsMaxResultsAboveLimit() {
given()
.when().get("/v1/configurations?maxResults=101")
.then().statusCode(400);
}
// maxResults is bound as a raw String and parsed by hand rather than @QueryParam
// Integer specifically because a non-numeric value for an Integer-typed @QueryParam
// fails RESTEasy Reactive's own conversion before the method body runs, and its
// default handling for that is a 404, not an AWS-shaped 400.
@Test
void listConfigurationsRejectsNonNumericMaxResults() {
given()
.when().get("/v1/configurations?maxResults=abc")
.then().statusCode(400);
}
@Test
void listConfigurationsRejectsInvalidNextToken() {
given()
.when().get("/v1/configurations?nextToken=not-a-valid-token!!")
.then().statusCode(400);
}
}
@@ -5,8 +5,14 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.msk.model.ClusterState;
import io.github.hectorvent.floci.services.msk.model.ConfigurationState;
import io.github.hectorvent.floci.services.msk.model.ListResult;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@@ -26,8 +32,10 @@ class MskServiceTest {
@BeforeEach
void setUp() {
storageFactory = Mockito.mock(StorageFactory.class);
// A fresh backend per call - MskService now creates two (clusters, configurations),
// and a shared instance would let configuration scans see cluster entries and vice versa.
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
config = Mockito.mock(EmulatorConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
@@ -87,4 +95,114 @@ class MskServiceTest {
mskService.deleteCluster(cluster.getClusterArn());
assertTrue(mskService.listClusters().isEmpty());
}
@Test
void createConfiguration() {
MskConfiguration configuration = mskService.createConfiguration(
"test-config", "a test config", List.of("3.6.0"), "auto.create.topics.enable=true");
assertNotNull(configuration);
assertEquals("test-config", configuration.getName());
assertEquals(ConfigurationState.ACTIVE, configuration.getState());
assertTrue(configuration.getArn().contains("test-config"));
assertNotNull(configuration.getLatestRevision());
assertEquals(1L, configuration.getLatestRevision().getRevision());
assertEquals("auto.create.topics.enable=true", configuration.getServerProperties());
}
@Test
void createConfigurationRejectsMissingName() {
assertThrows(AwsException.class, () ->
mskService.createConfiguration(null, "desc", List.of("3.6.0"), "props"));
}
@Test
void createConfigurationRejectsInvalidNamePattern() {
assertThrows(AwsException.class, () ->
mskService.createConfiguration("bad name!", "desc", List.of("3.6.0"), "props"));
}
@Test
void createConfigurationRejectsMissingServerProperties() {
assertThrows(AwsException.class, () ->
mskService.createConfiguration("test-config", "desc", List.of("3.6.0"), null));
}
@Test
void createConfigurationRejectsDuplicateName() {
mskService.createConfiguration("test-config", "desc", List.of("3.6.0"), "props");
assertThrows(AwsException.class, () ->
mskService.createConfiguration("test-config", "desc", List.of("3.6.0"), "props"));
}
@Test
void describeConfiguration() {
MskConfiguration created = mskService.createConfiguration(
"test-config", "desc", List.of("3.6.0"), "props");
MskConfiguration described = mskService.describeConfiguration(created.getArn());
assertEquals(created.getArn(), described.getArn());
}
@Test
void describeConfigurationNotFoundThrows() {
assertThrows(AwsException.class, () ->
mskService.describeConfiguration("arn:aws:kafka:us-east-1:000000000000:configuration/missing/id"));
}
@Test
void listConfigurations() {
mskService.createConfiguration("config-1", "desc", List.of("3.6.0"), "props");
mskService.createConfiguration("config-2", "desc", List.of("3.6.0"), "props");
List<MskConfiguration> configurations = mskService.listConfigurations(0, null).items();
assertEquals(2, configurations.size());
}
@Test
void listConfigurationsPaginatesWithMaxResultsAndNextToken() {
mskService.createConfiguration("config-1", "desc", List.of("3.6.0"), "props");
mskService.createConfiguration("config-2", "desc", List.of("3.6.0"), "props");
mskService.createConfiguration("config-3", "desc", List.of("3.6.0"), "props");
ListResult<MskConfiguration> firstPage = mskService.listConfigurations(2, null);
assertEquals(2, firstPage.items().size());
assertNotNull(firstPage.nextToken());
ListResult<MskConfiguration> secondPage = mskService.listConfigurations(2, firstPage.nextToken());
assertEquals(1, secondPage.items().size());
assertNull(secondPage.nextToken());
}
@Test
void listConfigurationsRejectsMaxResultsAboveLimit() {
assertThrows(AwsException.class, () -> mskService.listConfigurations(101, null));
}
@Test
void listConfigurationsRejectsInvalidNextToken() {
assertThrows(AwsException.class, () -> mskService.listConfigurations(0, "not-a-valid-token!!"));
}
@Test
void deleteConfiguration() {
MskConfiguration configuration = mskService.createConfiguration(
"test-config", "desc", List.of("3.6.0"), "props");
mskService.deleteConfiguration(configuration.getArn());
assertTrue(mskService.listConfigurations(0, null).items().isEmpty());
}
// StorageBackend persists this model via plain Jackson serialization (PersistentStorage,
// HybridStorage, WalStorage all call ObjectMapper#writeValue on it directly), so
// serverProperties must round-trip through JSON or persistent/hybrid/wal storage modes
// silently discard the broker configuration on reload.
@Test
void configurationServerPropertiesSurvivesJsonRoundTrip() throws Exception {
MskConfiguration configuration = mskService.createConfiguration(
"test-config", "desc", List.of("3.6.0"), "auto.create.topics.enable=true");
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
String json = mapper.writeValueAsString(configuration);
MskConfiguration restored = mapper.readValue(json, MskConfiguration.class);
assertEquals("auto.create.topics.enable=true", restored.getServerProperties());
}
}