Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): implement log delivery configuration (#2867)
Brian Taylorb8f1e22c742a
diff --git a/compatibility-tests/sdk-test-python/tests/test_cognito.py b/compatibility-tests/sdk-test-python/tests/test_cognito.pyindex 07e452d7e5..238c7d0385 100644--- a/compatibility-tests/sdk-test-python/tests/test_cognito.py+++ b/compatibility-tests/sdk-test-python/tests/test_cognito.py@@ -191,6 +191,147 @@ class TestCognitoAuth:cognito_client.delete_user_pool(UserPoolId=pool_id)+class TestCognitoLogDeliveryConfiguration:+ """Test Cognito log delivery configuration operations.++ ``LogConfigurations`` is always present on the response, as ``[]`` when nothing+ is configured, and ``SetLogDeliveryConfiguration`` replaces the list rather than+ merging into it.+ """++ LOG_GROUP_ARN = "arn:aws:logs:us-east-1:000000000000:log-group:pytest-cognito-logs"++ @pytest.fixture+ def pool_id(self, cognito_client, unique_name):+ response = cognito_client.create_user_pool(PoolName=f"pytest-log-pool-{unique_name}")+ pool_id = response["UserPool"]["Id"]+ yield pool_id+ cognito_client.delete_user_pool(UserPoolId=pool_id)++ def test_get_returns_an_empty_list_before_anything_is_configured(+ self, cognito_client, pool_id+ ):+ """An unconfigured pool still returns the LogConfigurations member."""+ config = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[+ "LogDeliveryConfiguration"+ ]++ assert config["UserPoolId"] == pool_id+ assert config["LogConfigurations"] == []++ def test_set_round_trips_and_replaces(self, cognito_client, pool_id):+ """Set stores the configuration, and a second Set replaces rather than merges."""+ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id,+ LogConfigurations=[+ {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},+ }+ ],+ )++ config = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[+ "LogDeliveryConfiguration"+ ]+ assert len(config["LogConfigurations"]) == 1+ assert config["LogConfigurations"][0]["EventSource"] == "userNotification"+ assert (+ config["LogConfigurations"][0]["CloudWatchLogsConfiguration"]["LogGroupArn"]+ == self.LOG_GROUP_ARN+ )++ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id,+ LogConfigurations=[+ {+ "LogLevel": "INFO",+ "EventSource": "userAuthEvents",+ "CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},+ }+ ],+ )+ replaced = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[+ "LogDeliveryConfiguration"+ ]+ assert len(replaced["LogConfigurations"]) == 1+ assert replaced["LogConfigurations"][0]["EventSource"] == "userAuthEvents"++ def test_empty_list_clears_the_configuration(self, cognito_client, pool_id):+ """An empty LogConfigurations clears what was stored."""+ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id,+ LogConfigurations=[+ {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},+ }+ ],+ )++ cognito_client.set_log_delivery_configuration(UserPoolId=pool_id, LogConfigurations=[])++ config = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[+ "LogDeliveryConfiguration"+ ]+ assert config["LogConfigurations"] == []++ def test_set_rejects_a_configuration_with_no_destination(self, cognito_client, pool_id):+ """Every event source in the request must name a destination."""+ with pytest.raises(cognito_client.exceptions.InvalidParameterException):+ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id,+ LogConfigurations=[{"LogLevel": "ERROR", "EventSource": "userNotification"}],+ )++ def test_set_rejects_more_than_two_configurations(self, cognito_client, pool_id):+ """LogConfigurations is bounded at 2 entries."""+ config = {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},+ }+ with pytest.raises(cognito_client.exceptions.InvalidParameterException) as excinfo:+ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id, LogConfigurations=[config, config, config]+ )++ assert "Member must have length less than or equal to 2" in str(excinfo.value)++ def test_set_rejects_a_repeated_event_source(self, cognito_client, pool_id):+ """An event source may appear at most once across the configurations."""+ config = {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},+ }+ with pytest.raises(cognito_client.exceptions.InvalidParameterException) as excinfo:+ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id, LogConfigurations=[config, config]+ )++ assert "appear more then once in a request" in str(excinfo.value)++ def test_a_rejected_request_leaves_the_configuration_alone(self, cognito_client, pool_id):+ """An oversized request must not be stored."""+ config = {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": self.LOG_GROUP_ARN},+ }+ with pytest.raises(cognito_client.exceptions.InvalidParameterException):+ cognito_client.set_log_delivery_configuration(+ UserPoolId=pool_id, LogConfigurations=[config, config, config]+ )++ stored = cognito_client.get_log_delivery_configuration(UserPoolId=pool_id)[+ "LogDeliveryConfiguration"+ ]+ assert stored["LogConfigurations"] == []++class TestCognitoDescribeUserPoolStandardAttributes:"""DescribeUserPool must return all 20 standard OIDC attributes."""diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 8aed6209bf..54cc64c608 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -64,6 +64,35 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource`| DescribeUserPoolDomain | Returns a domain's description, including `CloudFrontDistribution` for custom domains. || DeleteUserPoolDomain | Deletes a domain from its user pool. |+### Log Delivery++| Action | Description |+|--------|-------------|+| SetLogDeliveryConfiguration | Replaces a user pool's log delivery configuration. |+| GetLogDeliveryConfiguration | Returns a user pool's log delivery configuration. |++`LogLevel` accepts `ERROR` or `INFO`, and `EventSource` accepts `userNotification` or+`userAuthEvents`. `LogConfigurations` holds at most 2 entries, and an event source may+appear only once across them. Each entry must name a destination:+`CloudWatchLogsConfiguration`, `FirehoseConfiguration` or `S3Configuration`, and a request+that omits one is rejected the way AWS rejects it. `Set` replaces the whole list rather+than merging, so an empty `LogConfigurations` is what clears it, and `Get` always returns+the member, as `[]` when nothing is configured.++The length and enum checks run before the pool is looked up, so an oversized or malformed+request naming a pool that does not exist reports the request problem rather than+`ResourceNotFoundException`, and every violation of them is reported in one message.++Floci stores the configuration and never delivers anything to the destination: the log+group, delivery stream or bucket is not written to, and is not required to exist. Two+further divergences, both deliberate:++- **No pricing-tier gate.** AWS refuses `userAuthEvents` on a pool in the `ESSENTIALS`+ tier with `FeatureUnavailableInTierException`; Floci accepts either event source+ whatever `UserPoolTier` says.+- **No destination validation.** AWS checks the ARN it is handed; Floci stores it as+ given.+### Admin User Management| Action | Description |diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.javaindex 9122667460..b7431f7791 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java@@ -19,6 +19,7 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import jakarta.ws.rs.core.Response;+import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -61,6 +62,8 @@ public class CognitoJsonHandler {case "CreateUserPoolDomain" -> handleCreateUserPoolDomain(request);case "DescribeUserPoolDomain" -> handleDescribeUserPoolDomain(request);case "DeleteUserPoolDomain" -> handleDeleteUserPoolDomain(request);+ case "SetLogDeliveryConfiguration" -> handleSetLogDeliveryConfiguration(request);+ case "GetLogDeliveryConfiguration" -> handleGetLogDeliveryConfiguration(request);case "AdminResetUserPassword" -> handleAdminResetUserPassword(request);case "AdminCreateUser" -> handleAdminCreateUser(request);case "AdminGetUser" -> handleAdminGetUser(request);@@ -373,6 +376,57 @@ public class CognitoJsonHandler {return Response.ok(response).build();}+ private Response handleSetLogDeliveryConfiguration(JsonNode request) {+ UserPool pool = service.setLogDeliveryConfiguration(+ request.path("UserPoolId").asText(),+ readObjectList(request, "LogConfigurations")+ );+ ObjectNode response = objectMapper.createObjectNode();+ response.set("LogDeliveryConfiguration", logDeliveryConfigurationToNode(pool));+ return Response.ok(response).build();+ }++ private Response handleGetLogDeliveryConfiguration(JsonNode request) {+ UserPool pool = service.getLogDeliveryConfiguration(request.path("UserPoolId").asText());+ ObjectNode response = objectMapper.createObjectNode();+ response.set("LogDeliveryConfiguration", logDeliveryConfigurationToNode(pool));+ return Response.ok(response).build();+ }++ private ObjectNode logDeliveryConfigurationToNode(UserPool pool) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("UserPoolId", pool.getId());+ ArrayNode configurations = node.putArray("LogConfigurations");+ pool.getLogConfigurations().forEach(config -> configurations.add(objectMapper.valueToTree(config)));+ return node;+ }++ /**+ * Absent or null yields null so the service can reject it. A value of the wrong JSON type is+ * a deserialization failure, which AWS reports as SerializationException, and a null element+ * inside the array is dropped, which is what AWS does with it.+ */+ private List<Map<String, Object>> readObjectList(JsonNode request, String member) {+ JsonNode node = request.get(member);+ if (node == null || node.isNull()) {+ return null;+ }+ if (!node.isArray()) {+ throw new AwsException("SerializationException", "Expected list or null", 400);+ }+ List<Map<String, Object>> values = new ArrayList<>();+ for (JsonNode element : node) {+ if (element.isNull()) {+ continue;+ }+ if (!element.isObject()) {+ throw new AwsException("SerializationException", "Expected null", 400);+ }+ values.add(objectMapper.convertValue(element, new TypeReference<Map<String, Object>>() {}));+ }+ return values;+ }+private Response handleDeleteUserPoolDomain(JsonNode request) {service.deleteUserPoolDomain(request.path("Domain").asText(),diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex d9820713a4..fedc5faa1c 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -946,6 +946,140 @@ public class CognitoService implements ResourceProvider {.format(java.time.Instant.now());}+ // ──────────────────────────── Log Delivery ────────────────────────────++ private static final Set<String> LOG_LEVELS = Set.of("ERROR", "INFO");+ private static final Set<String> LOG_EVENT_SOURCES = Set.of("userAuthEvents", "userNotification");+ private static final int MAX_LOG_CONFIGURATIONS = 2;++ /**+ * Replaces the pool's log configuration wholesale: AWS has no merge semantics here, and an+ * empty list is what clears it.+ */+ public UserPool setLogDeliveryConfiguration(String userPoolId, List<Map<String, Object>> logConfigurations) {+ validateLogConfigurations(logConfigurations);+ rejectUnusableEventSources(logConfigurations);++ UserPool pool = describeUserPool(userPoolId);+ pool.setLogConfigurations(new ArrayList<>(logConfigurations));+ poolStore.put(userPoolId, pool);+ return pool;+ }++ public UserPool getLogDeliveryConfiguration(String userPoolId) {+ return describeUserPool(userPoolId);+ }++ /**+ * The shape checks AWS runs before it looks the pool up, so an oversized or malformed request+ * against a pool that does not exist reports the request problem rather than the missing pool.+ * Every violation is collected into one message, the list-length one ahead of the per-element+ * ones, the way the service reports them.+ */+ private void validateLogConfigurations(List<Map<String, Object>> configs) {+ if (configs == null) {+ throw validationErrors(List.of(+ "Value null at 'logConfigurations' failed to satisfy constraint: Member must not be null"));+ }++ List<String> errors = new ArrayList<>();+ if (configs.size() > MAX_LOG_CONFIGURATIONS) {+ errors.add("Value '" + renderLogConfigurations(configs) + "' at 'logConfigurations' failed to "+ + "satisfy constraint: Member must have length less than or equal to " + MAX_LOG_CONFIGURATIONS);+ }+ for (int i = 0; i < configs.size(); i++) {+ Map<String, Object> config = configs.get(i);+ collectLogMemberError(errors, config.get("LogLevel"), LOG_LEVELS, i, "logLevel", "[ERROR, INFO]");+ collectLogMemberError(errors, config.get("EventSource"), LOG_EVENT_SOURCES, i, "eventSource",+ "[userAuthEvents, userNotification]");+ }+ if (!errors.isEmpty()) {+ throw validationErrors(errors);+ }+ }++ /**+ * Both complaints share one message, the missing-destination clause first, and each event+ * source is named once however many configurations carry it.+ *+ * <p>"more then once" is the service's own spelling, kept so the message matches byte for byte.+ */+ private void rejectUnusableEventSources(List<Map<String, Object>> configs) {+ Set<String> withoutDestination = new LinkedHashSet<>();+ Set<String> seen = new LinkedHashSet<>();+ Set<String> duplicated = new LinkedHashSet<>();+ for (Map<String, Object> config : configs) {+ String eventSource = String.valueOf(config.get("EventSource"));+ if (!hasLogDestination(config)) {+ withoutDestination.add(eventSource);+ }+ if (!seen.add(eventSource)) {+ duplicated.add(eventSource);+ }+ }++ StringBuilder message = new StringBuilder();+ if (!withoutDestination.isEmpty()) {+ message.append(" Following event sources in request have no destination: ")+ .append(new ArrayList<>(withoutDestination)).append(".");+ }+ if (!duplicated.isEmpty()) {+ message.append(" Following event sources appear more then once in a request: ")+ .append(new ArrayList<>(duplicated)).append(".");+ }+ if (!message.isEmpty()) {+ throw new AwsException("InvalidParameterException", "Request validation Failed." + message, 400);+ }+ }++ private AwsException validationErrors(List<String> errors) {+ String header = errors.size() == 1+ ? "1 validation error detected: "+ : errors.size() + " validation errors detected: ";+ return new AwsException("InvalidParameterException", header + String.join("; ", errors), 400);+ }++ /** Mirrors the request model's {@code toString}, which AWS embeds in the length-constraint message. */+ private String renderLogConfigurations(List<Map<String, Object>> configs) {+ List<String> rendered = new ArrayList<>();+ for (Map<String, Object> config : configs) {+ rendered.add("LogConfigurationType(logLevel=" + config.get("LogLevel")+ + ", eventSource=" + config.get("EventSource")+ + ", cloudWatchLogsConfiguration=" + renderLogDestination(+ config.get("CloudWatchLogsConfiguration"), "CloudWatchLogsConfigurationType",+ "LogGroupArn", "logGroupArn")+ + ", s3Configuration=" + renderLogDestination(+ config.get("S3Configuration"), "S3ConfigurationType", "BucketArn", "bucketArn")+ + ", firehoseConfiguration=" + renderLogDestination(+ config.get("FirehoseConfiguration"), "FirehoseConfigurationType",+ "StreamArn", "streamArn")+ + ")");+ }+ return "[" + String.join(", ", rendered) + "]";+ }++ private String renderLogDestination(Object value, String typeName, String requestMember, String modelMember) {+ if (!(value instanceof Map<?, ?> destination)) {+ return "null";+ }+ return typeName + "(" + modelMember + "=" + destination.get(requestMember) + ")";+ }++ private boolean hasLogDestination(Map<String, Object> config) {+ return config.get("CloudWatchLogsConfiguration") != null+ || config.get("FirehoseConfiguration") != null+ || config.get("S3Configuration") != null;+ }++ /** AWS reports the offending member with a 1-based index, e.g. {@code logConfigurations.1.member.logLevel}. */+ private void collectLogMemberError(List<String> errors, Object value, Set<String> allowed, int index,+ String member, String enumSet) {+ if (value == null || !allowed.contains(String.valueOf(value))) {+ errors.add("Value '" + value + "' at 'logConfigurations." + (index + 1) + ".member." + member+ + "' failed to satisfy constraint: Member must satisfy enum value set: " + enumSet);+ }+ }+// ──────────────────────────── Users ────────────────────────────public CognitoUser adminCreateUser(String userPoolId, String username, Map<String, String> attributes,diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.javaindex 5c3316084d..29153230cd 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java@@ -49,6 +49,9 @@ public class UserPool {private String clientIdOverride = null;private String clientSecretOverride = null;+ /** Empty until SetLogDeliveryConfiguration sets it; GetLogDeliveryConfiguration always returns it. */+ private List<Map<String, Object>> logConfigurations = new ArrayList<>();+public UserPool() {long now = System.currentTimeMillis() / 1000L;this.creationDate = now;@@ -159,4 +162,9 @@ public class UserPool {public String getClientSecretOverride() { return clientSecretOverride; }public void setClientSecretOverride(String clientSecretOverride) { this.clientSecretOverride = clientSecretOverride; }++ public List<Map<String, Object>> getLogConfigurations() { return logConfigurations; }+ public void setLogConfigurations(List<Map<String, Object>> logConfigurations) {+ this.logConfigurations = logConfigurations;+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLogDeliveryConfigurationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLogDeliveryConfigurationIntegrationTest.javanew file mode 100644index 0000000000..ce4494ed4d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLogDeliveryConfigurationIntegrationTest.java@@ -0,0 +1,450 @@+package io.github.hectorvent.floci.services.cognito;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Covers SetLogDeliveryConfiguration and GetLogDeliveryConfiguration.+ *+ * <p>The enum sets, the missing-destination rejection and the 1-based validation path were+ * measured against the live Cognito API.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class CognitoLogDeliveryConfigurationIntegrationTest {++ private static String poolId;++ private static final String LOG_GROUP_ARN =+ "arn:aws:logs:us-east-1:000000000000:log-group:cognito-test-logs";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ @Order(1)+ void createPool() throws Exception {+ JsonNode response = cognitoJson("CreateUserPool", """+ {+ "PoolName": "LogDeliveryTestPool"+ }+ """);+ poolId = response.path("UserPool").path("Id").asText();+ }++ @Test+ @Order(2)+ void getReturnsAnEmptyListBeforeAnythingIsConfigured() throws Exception {+ JsonNode config = cognitoJson("GetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration");++ assertEquals(poolId, config.path("UserPoolId").asText());+ assertTrue(config.path("LogConfigurations").isArray());+ assertEquals(0, config.path("LogConfigurations").size());+ }++ @Test+ @Order(3)+ void setStoresAndEchoesTheConfiguration() throws Exception {+ JsonNode config = cognitoJson("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}+ }+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN)).path("LogDeliveryConfiguration");++ assertEquals(1, config.path("LogConfigurations").size());+ JsonNode entry = config.path("LogConfigurations").get(0);+ assertEquals("ERROR", entry.path("LogLevel").asText());+ assertEquals("userNotification", entry.path("EventSource").asText());+ assertEquals(LOG_GROUP_ARN,+ entry.path("CloudWatchLogsConfiguration").path("LogGroupArn").asText());++ JsonNode readBack = cognitoJson("GetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration");+ assertEquals(config.path("LogConfigurations"), readBack.path("LogConfigurations"));+ }++ @Test+ @Order(4)+ void setRejectsAnUnknownLogLevel() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {+ "LogLevel": "TRACE",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}+ }+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "1 validation error detected: Value 'TRACE' at "+ + "'logConfigurations.1.member.logLevel' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [ERROR, INFO]"));+ }++ @Test+ @Order(5)+ void setRejectsAnUnknownEventSource() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {+ "LogLevel": "ERROR",+ "EventSource": "notAThing",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}+ }+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "1 validation error detected: Value 'notAThing' at "+ + "'logConfigurations.1.member.eventSource' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [userAuthEvents, userNotification]"));+ }++ @Test+ @Order(6)+ void setRejectsAConfigurationWithNoDestination() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {+ "LogLevel": "ERROR",+ "EventSource": "userNotification"+ }+ ]+ }+ """.formatted(poolId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "Request validation Failed. Following event sources in request have no "+ + "destination: [userNotification]."));+ }++ @Test+ @Order(7)+ void setReplacesRatherThanMerges() throws Exception {+ JsonNode config = cognitoJson("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {+ "LogLevel": "INFO",+ "EventSource": "userAuthEvents",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}+ }+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN)).path("LogDeliveryConfiguration");++ assertEquals(1, config.path("LogConfigurations").size(),+ "Set replaces the whole list; the userNotification entry must be gone");+ assertEquals("userAuthEvents", config.path("LogConfigurations").get(0).path("EventSource").asText());+ }++ @Test+ @Order(8)+ void anEmptyListClearsTheConfiguration() throws Exception {+ assertEquals(0, cognitoJson("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": []+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration").path("LogConfigurations").size());++ assertEquals(0, cognitoJson("GetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration").path("LogConfigurations").size());+ }++ /**+ * A malformed request must not be read as an intentional clear: AWS rejects a null+ * LogConfigurations outright, and reports a wrong JSON type as a serialization failure.+ */+ @Test+ @Order(9)+ void malformedRequestsAreRejectedRatherThanClearingTheConfiguration() throws Exception {+ cognitoJson("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {+ "LogLevel": "ERROR",+ "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}+ }+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN));++ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "1 validation error detected: Value null at 'logConfigurations' failed to "+ + "satisfy constraint: Member must not be null"));++ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": "nope"+ }+ """.formatted(poolId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("SerializationException"));++ assertEquals(1, cognitoJson("GetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration").path("LogConfigurations").size(),+ "a rejected request must leave the stored configuration untouched");+ }++ /**+ * A scalar inside the array is a deserialization failure for AWS, not a 500, and a null+ * element is dropped rather than rejected.+ */+ @Test+ @Order(10)+ void malformedArrayElementsMatchAwsHandling() throws Exception {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [1, 2]+ }+ """.formatted(poolId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("SerializationException"));++ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": ["a string"]+ }+ """.formatted(poolId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("SerializationException"));++ assertEquals(0, cognitoJson("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [null]+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration").path("LogConfigurations").size(),+ "AWS drops a null element rather than rejecting it");+ }++ @Test+ @Order(11)+ void unknownPoolIsRejected() {+ cognitoAction("GetLogDeliveryConfiguration", """+ {+ "UserPoolId": "us-east-1_nosuchpool"+ }+ """)+ .then()+ .statusCode(400)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ @Order(12)+ void setRejectsMoreThanTwoConfigurations() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {"LogLevel": "ERROR", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}},+ {"LogLevel": "INFO", "EventSource": "userAuthEvents",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}},+ {"LogLevel": "ERROR", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}}+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN, LOG_GROUP_ARN, LOG_GROUP_ARN))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "1 validation error detected: Value '["+ + cloudWatchConfig("ERROR", "userNotification") + ", "+ + cloudWatchConfig("INFO", "userAuthEvents") + ", "+ + cloudWatchConfig("ERROR", "userNotification")+ + "]' at 'logConfigurations' failed to satisfy constraint: "+ + "Member must have length less than or equal to 2"));+ }++ @Test+ @Order(13)+ void theLengthViolationIsReportedAlongsideElementViolations() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {"LogLevel": "ERROR", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}},+ {"LogLevel": "BOGUS", "EventSource": "userAuthEvents",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}},+ {"LogLevel": "ERROR", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}}+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN, LOG_GROUP_ARN, LOG_GROUP_ARN))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "2 validation errors detected: Value '["+ + cloudWatchConfig("ERROR", "userNotification") + ", "+ + cloudWatchConfig("BOGUS", "userAuthEvents") + ", "+ + cloudWatchConfig("ERROR", "userNotification")+ + "]' at 'logConfigurations' failed to satisfy constraint: "+ + "Member must have length less than or equal to 2; "+ + "Value 'BOGUS' at 'logConfigurations.2.member.logLevel' failed to satisfy "+ + "constraint: Member must satisfy enum value set: [ERROR, INFO]"));+ }++ @Test+ @Order(14)+ void shapeViolationsAreReportedBeforeTheMissingPool() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "us-east-1_nosuchpool",+ "LogConfigurations": [+ {"LogLevel": "BOGUS", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}}+ ]+ }+ """.formatted(LOG_GROUP_ARN))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "1 validation error detected: Value 'BOGUS' at "+ + "'logConfigurations.1.member.logLevel' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [ERROR, INFO]"));+ }++ @Test+ @Order(15)+ void setRejectsARepeatedEventSource() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {"LogLevel": "ERROR", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}},+ {"LogLevel": "INFO", "EventSource": "userNotification",+ "CloudWatchLogsConfiguration": {"LogGroupArn": "%s"}}+ ]+ }+ """.formatted(poolId, LOG_GROUP_ARN, LOG_GROUP_ARN))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "Request validation Failed. Following event sources appear more then once "+ + "in a request: [userNotification]."));+ }++ @Test+ @Order(16)+ void aRepeatedEventSourceWithNoDestinationReportsBothClauses() {+ cognitoAction("SetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s",+ "LogConfigurations": [+ {"LogLevel": "ERROR", "EventSource": "userNotification"},+ {"LogLevel": "ERROR", "EventSource": "userNotification"}+ ]+ }+ """.formatted(poolId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(+ "Request validation Failed. Following event sources in request have no "+ + "destination: [userNotification]. Following event sources appear "+ + "more then once in a request: [userNotification]."));+ }++ @Test+ @Order(17)+ void aRejectedOversizedRequestLeavesTheConfigurationAlone() throws Exception {+ assertEquals(0, cognitoJson("GetLogDeliveryConfiguration", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId)).path("LogDeliveryConfiguration").path("LogConfigurations").size());+ }++ @Test+ @Order(18)+ void deletePool() {+ cognitoAction("DeleteUserPool", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId))+ .then()+ .statusCode(200);+ }++ private static String cloudWatchConfig(String logLevel, String eventSource) {+ return "LogConfigurationType(logLevel=" + logLevel + ", eventSource=" + eventSource+ + ", cloudWatchLogsConfiguration=CloudWatchLogsConfigurationType(logGroupArn="+ + LOG_GROUP_ARN + "), s3Configuration=null, firehoseConfiguration=null)";+ }+}