Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): do not return optional blocks in CreateUserPoolClient when they are not set (#1615)
Maciej6c5f533f346b
diff --git a/compatibility-tests/compat-opentofu/main.tf b/compatibility-tests/compat-opentofu/main.tfindex 84ab32953e..ec056e343e 100644--- a/compatibility-tests/compat-opentofu/main.tf+++ b/compatibility-tests/compat-opentofu/main.tf@@ -257,3 +257,50 @@ output "zone_id" {output "health_check_id" {value = aws_route53_health_check.app.id}++# ── Cognito User Pool ─────────────────────────────────────────────────────+resource "aws_cognito_user_pool" "pool" {+ name = "floci-compat-pool"++ password_policy {+ minimum_length = 12+ require_lowercase = true+ require_numbers = true+ require_symbols = true+ require_uppercase = true+ }++ auto_verified_attributes = ["email"]+ username_attributes = ["email"]++ admin_create_user_config {+ allow_admin_create_user_only = false+ }++ verification_message_template {+ default_email_option = "CONFIRM_WITH_CODE"+ email_message = "Your code is {####}"+ email_subject = "Verify your account"+ }++ account_recovery_setting {+ recovery_mechanism {+ name = "verified_email"+ priority = 1+ }+ }+}++output "user_pool_id" {+ value = aws_cognito_user_pool.pool.id+}++output "user_pool_arn" {+ value = aws_cognito_user_pool.pool.arn+}++# ── Cognito User Pool Client ──────────────────────────────────────────────+resource "aws_cognito_user_pool_client" "client" {+ name = "floci-compat-pool-client"+ user_pool_id = aws_cognito_user_pool.pool.id+}diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.batsindex d631763c48..40e54ba4c7 100644--- a/compatibility-tests/compat-opentofu/test/opentofu.bats+++ b/compatibility-tests/compat-opentofu/test/opentofu.bats@@ -174,3 +174,14 @@ setup() {assert_successassert_output --partial "compat-test"}++@test "OpenTofu: Cognito user pool client created without optional blocks" {+ POOL_ID=$(aws_cmd cognito-idp list-user-pools --max-results 10 \+ --query "UserPools[?Name=='floci-compat-pool'].Id | [0]" --output text)+ [ -n "$POOL_ID" ]+ run aws_cmd cognito-idp list-user-pool-clients --user-pool-id "$POOL_ID" \+ --query "UserPoolClients[?ClientName=='floci-compat-pool-client'].ClientId | [0]" --output text+ assert_success+ [ -n "$output" ]+ [ "$output" != "None" ]+}diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tfindex 5ac3e2a9a1..7aae451beb 100644--- a/compatibility-tests/compat-terraform/main.tf+++ b/compatibility-tests/compat-terraform/main.tf@@ -187,6 +187,12 @@ output "user_pool_arn" {value = aws_cognito_user_pool.pool.arn}+# -- Cognito User Pool Client --------------------------------------------------+resource "aws_cognito_user_pool_client" "client" {+ name = "floci-compat-pool-client"+ user_pool_id = aws_cognito_user_pool.pool.id+}+# -- CloudWatch Alarms ---------------------------------------------------------resource "aws_cloudwatch_metric_alarm" "cpu" {alarm_name = "floci-compat-cpu-alarm"diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.batsindex 42c261ef22..c4480bafec 100644--- a/compatibility-tests/compat-terraform/test/terraform.bats+++ b/compatibility-tests/compat-terraform/test/terraform.bats@@ -193,3 +193,14 @@ setup() {assert_successassert_output --partial "compat-test"}++@test "Terraform: Cognito user pool client created without optional blocks" {+ POOL_ID=$(aws_cmd cognito-idp list-user-pools --max-results 10 \+ --query "UserPools[?Name=='floci-compat-pool'].Id | [0]" --output text)+ [ -n "$POOL_ID" ]+ run aws_cmd cognito-idp list-user-pool-clients --user-pool-id "$POOL_ID" \+ --query "UserPoolClients[?ClientName=='floci-compat-pool-client'].ClientId | [0]" --output text+ assert_success+ [ -n "$output" ]+ [ "$output" != "None" ]+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.javaindex 874044a840..5e5ce93107 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java@@ -32,11 +32,12 @@ import static org.assertj.core.api.Assertions.*;* #229 — InitiateAuth rejects auth when no password hash is set* #233 — ListUsers respects Filter parameter* #235 — AdminSetUserPassword(Permanent=false) changes the password+ * #1505 — CreateUserPoolClient must not return empty {} for unset optional blocks** Note: Issue #234 (GetTokensFromRefreshToken) is tested in sdk-test-node/tests/cognito-features.test.ts* because GetTokensFromRefreshTokenCommand is not present in Java SDK 2.31.8.*/-@DisplayName("Cognito IDP — bug fixes #218 #220 #228 #229 #233 #235")+@DisplayName("Cognito IDP — bug fixes #218 #220 #228 #229 #233 #235 #1505")@TestMethodOrder(MethodOrderer.OrderAnnotation.class)class CognitoFeaturesTest {@@ -48,6 +49,7 @@ class CognitoFeaturesTest {private static CognitoIdentityProviderClient cognito;private static String poolId;+ private static String userPoolClientId;private static String poolArn;private static String clientId;private static final String USERNAME = "compat-user-" + UUID.randomUUID() + "@example.com";@@ -63,6 +65,12 @@ class CognitoFeaturesTest {static void cleanup() {if (cognito == null) return;try {+ if (userPoolClientId != null) {+ cognito.deleteUserPoolClient(b -> b+ .userPoolId(poolId)+ .clientId(userPoolClientId)+ );+ }if (poolId != null) {cognito.deleteUserPool(b -> b.userPoolId(poolId));}@@ -144,6 +152,26 @@ class CognitoFeaturesTest {assertThat(userSub).isNotBlank();}+ @Test+ @Order(6)+ void createUserPoolClientDoesNotReturnEmptyOptionalBlocks() {+ CreateUserPoolClientResponse resp = cognito.createUserPoolClient(b -> b+ .userPoolId(poolId)+ .clientName("user-pool-client"));+ UserPoolClientType client = resp.userPoolClient();+ userPoolClientId = client.clientId();++ assertThat(client.analyticsConfiguration())+ .as("analyticsConfiguration must be null when not set")+ .isNull();+ assertThat(client.tokenValidityUnits())+ .as("tokenValidityUnits must be null when not set")+ .isNull();+ assertThat(client.refreshTokenRotation())+ .as("refreshTokenRotation must be null when not set")+ .isNull();+ }+// ── Issue #229 — InitiateAuth rejects when no password hash is set ────────@Testdiff --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 789afd1cfe..4dbf8041fa 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@@ -1,12 +1,12 @@package io.github.hectorvent.floci.services.cognito;-import io.github.hectorvent.floci.core.common.AwsErrorResponse;-import io.github.hectorvent.floci.core.common.AwsException;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;import io.github.hectorvent.floci.services.cognito.model.CognitoUser;import io.github.hectorvent.floci.services.cognito.model.ResourceServer;@@ -21,6 +21,7 @@ import jakarta.ws.rs.core.Response;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.Optional;@ApplicationScopedpublic class CognitoJsonHandler {@@ -681,8 +682,8 @@ public class CognitoJsonHandler {c.getAllowedOAuthFlows().forEach(flows::add);ArrayNode scopes = node.putArray("AllowedOAuthScopes");c.getAllowedOAuthScopes().forEach(scopes::add);- node.set("AnalyticsConfiguration", objectMapper.valueToTree(- c.getAnalyticsConfiguration() != null ? c.getAnalyticsConfiguration() : new HashMap<>()));+ Optional.ofNullable(c.getAnalyticsConfiguration())+ .ifPresent(it -> node.set("AnalyticsConfiguration", objectMapper.valueToTree(it)));ArrayNode callbackUrls = node.putArray("CallbackURLs");c.getCallbackURLs().forEach(callbackUrls::add);if (c.getDefaultRedirectURI() != null) {@@ -708,12 +709,12 @@ public class CognitoJsonHandler {}ArrayNode supportedIdentityProviders = node.putArray("SupportedIdentityProviders");c.getSupportedIdentityProviders().forEach(supportedIdentityProviders::add);- node.set("TokenValidityUnits", objectMapper.valueToTree(- c.getTokenValidityUnits() != null ? c.getTokenValidityUnits() : new HashMap<>()));+ Optional.ofNullable(c.getTokenValidityUnits())+ .ifPresent(it -> node.set("TokenValidityUnits", objectMapper.valueToTree(it)));ArrayNode writeAttributes = node.putArray("WriteAttributes");c.getWriteAttributes().forEach(writeAttributes::add);- node.set("RefreshTokenRotation", objectMapper.valueToTree(- c.getRefreshTokenRotation() != null ? c.getRefreshTokenRotation() : new HashMap<>()));+ Optional.ofNullable(c.getRefreshTokenRotation())+ .ifPresent(it -> node.set("RefreshTokenRotation", objectMapper.valueToTree(it)));if (c.getEnableTokenRevocation() != null) {node.put("EnableTokenRevocation", c.getEnableTokenRevocation());}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.javaindex a13a792b69..afa062d145 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java@@ -5,8 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;-import io.github.hectorvent.floci.core.common.ReservedTags;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.ReservedTags;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import jakarta.ws.rs.core.Response;import org.junit.jupiter.api.BeforeEach;@@ -360,10 +360,36 @@ class CognitoJsonHandlerTest {assertEquals("ValidationException", exception.getErrorCode());}+ // Issue #1505: CreateUserPoolClient must not emit optional block fields+ // as empty {} in the JSON response when they were not set+ @Test+ void createUserPoolClientDoesNotReturnOptionalBlockKeysWhenNotSet() {+ ObjectNode poolReq = mapper.createObjectNode();+ poolReq.put("PoolName", "minimal-pool");+ JsonNode poolBody = (JsonNode) handler.handle("CreateUserPool", poolReq, "us-east-1").getEntity();+ String poolId = poolBody.get("UserPool").get("Id").asText();++ ObjectNode clientReq = mapper.createObjectNode();+ clientReq.put("UserPoolId", poolId);+ clientReq.put("ClientName", "minimal-client");++ Response createResp = handler.handle("CreateUserPoolClient", clientReq, "us-east-1");+ assertEquals(200, createResp.getStatus());+ JsonNode createClient = ((JsonNode) createResp.getEntity()).get("UserPoolClient");++ assertFalse(createClient.has("AnalyticsConfiguration"),+ "CreateUserPoolClient must not return AnalyticsConfiguration when not set");+ assertFalse(createClient.has("TokenValidityUnits"),+ "CreateUserPoolClient must not return TokenValidityUnits when not set");+ assertFalse(createClient.has("RefreshTokenRotation"),+ "CreateUserPoolClient must not return RefreshTokenRotation when not set");+ }+private Set<String> schemaNames(JsonNode pool) {return StreamSupport.stream(Spliterators.spliteratorUnknownSize(pool.get("SchemaAttributes").elements(), 0), false).map(n -> n.get("Name").asText()).collect(Collectors.toSet());}+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javaindex d30ca70a06..3fa6f53c20 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -483,6 +483,25 @@ class CognitoServiceTest {assertEquals("InvalidParameterException", exception.getErrorCode());}+ // Issue #1505: CreateUserPoolClient must not set optional block fields when they were not provided+ @Test+ void createUserPoolClientWithNoOptionalBlocksLeavesThemNull() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "MinimalPool"), "us-east-1");++ UserPoolClient client = service.createUserPoolClient(+ pool.getId(),+ "minimal-client",+ false,+ false,+ List.of(),+ List.of()+ );++ assertNull(client.getAnalyticsConfiguration(), "analyticsConfiguration must be null when not provided");+ assertNull(client.getTokenValidityUnits(), "tokenValidityUnits must be null when not provided");+ assertNull(client.getRefreshTokenRotation(), "refreshTokenRotation must be null when not provided");+ }+@Testvoid updateUserPoolClientAllowsClearingListFieldsWithEmptyArrays() {UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");