diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java new file mode 100644 index 0000000000..0438282dbf --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java @@ -0,0 +1,250 @@ +package com.floci.test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +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 software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.VerifiedAttributeType; + +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Compatibility tests for Cognito ConfirmSignUp verified attribute updates (Issue #1654). + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoConfirmSignUpVerificationTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final HttpClient HTTP = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .build(); + private static final Pattern SIX_DIGIT_CODE_PATTERN = Pattern.compile("\\b(\\d{6})\\b"); + private static final String PASSWORD = "Passw0rd!"; + + private static CognitoIdentityProviderClient cognitoClient; + private String poolId; + + @BeforeAll + static void setup() { + cognitoClient = TestFixtures.cognitoClient(); + } + + @AfterAll + static void cleanup() { + if (cognitoClient != null) { + cognitoClient.close(); + } + } + + @AfterEach + void tearDown() { + if (poolId != null) { + try { + cognitoClient.deleteUserPool(b -> b.userPoolId(poolId)); + } catch (Exception ignored) { + } + poolId = null; + } + } + + @Test + @Order(1) + @DisplayName("ConfirmSignUp marks email_verified=true when email is the auto verified attribute") + void confirmSignUpMarksEmailVerified() throws Exception { + clearInspectionEndpoint("/_aws/ses"); + + String poolName = "email-verify-" + UUID.randomUUID(); + + CreateUserPoolResponse poolResp = cognitoClient.createUserPool(b -> b + .poolName(poolName) + .autoVerifiedAttributes(VerifiedAttributeType.EMAIL)); + poolId = poolResp.userPool().id(); + + String clientId = cognitoClient.createUserPoolClient(b -> b + .userPoolId(poolId) + .clientName("email-verify-client")) + .userPoolClient().clientId(); + + String email = "alice+" + UUID.randomUUID() + "@example.com"; + + cognitoClient.signUp(b -> b + .clientId(clientId) + .username(email) + .password(PASSWORD) + .userAttributes(AttributeType.builder() + .name("email") + .value(email) + .build())); + + String confirmationCode = fetchVerificationCodeFromSes(email); + + cognitoClient.confirmSignUp(b -> b + .clientId(clientId) + .username(email) + .confirmationCode(confirmationCode)); + + AdminGetUserResponse user = cognitoClient.adminGetUser(b -> b + .userPoolId(poolId) + .username(email)); + + assertThat(user.userStatusAsString()) + .as("ConfirmSignUp should confirm the user") + .isEqualTo("CONFIRMED"); + + String emailVerified = makeAttributeValue(user.userAttributes(), "email_verified"); + assertThat(emailVerified) + .as("ConfirmSignUp should set email_verified=true for the email auto verified attribute") + .isEqualTo("true"); + } + + @Test + @Order(2) + @DisplayName("ConfirmSignUp marks phone_number_verified=true when phone_number is the auto verified attribute") + void confirmSignUpMarksPhoneNumberVerified() throws Exception { + clearInspectionEndpoint("/_aws/sns"); + + String poolName = "phone-verify-" + UUID.randomUUID(); + + CreateUserPoolResponse poolResp = cognitoClient.createUserPool(b -> b + .poolName(poolName) + .autoVerifiedAttributes(VerifiedAttributeType.PHONE_NUMBER)); + poolId = poolResp.userPool().id(); + + String clientId = cognitoClient.createUserPoolClient(b -> b + .userPoolId(poolId) + .clientName("phone-verify-client")) + .userPoolClient().clientId(); + + String username = "phone-user-" + UUID.randomUUID(); + String phoneNumber = "+49170" + ThreadLocalRandom.current().nextLong(1_000_000, 10_000_000); + + cognitoClient.signUp(b -> b + .clientId(clientId) + .username(username) + .password(PASSWORD) + .userAttributes(AttributeType.builder() + .name("phone_number") + .value(phoneNumber) + .build())); + + String confirmationCode = fetchVerificationCodeFromSns(phoneNumber); + + cognitoClient.confirmSignUp(b -> b + .clientId(clientId) + .username(username) + .confirmationCode(confirmationCode)); + + AdminGetUserResponse user = cognitoClient.adminGetUser(b -> b + .userPoolId(poolId) + .username(username)); + + assertThat(user.userStatusAsString()) + .as("ConfirmSignUp should confirm the user") + .isEqualTo("CONFIRMED"); + + String phoneVerified = makeAttributeValue(user.userAttributes(), "phone_number_verified"); + assertThat(phoneVerified) + .as("ConfirmSignUp should set phone_number_verified=true for the phone_number auto-verified attribute (Issue #1654)") + .isEqualTo("true"); + } + + private static String makeAttributeValue(List attributes, String name) { + return attributes.stream() + .filter(a -> name.equals(a.name())) + .map(AttributeType::value) + .findFirst() + .orElse(null); + } + + private static void clearInspectionEndpoint(String path) throws Exception { + HttpResponse resp = HTTP.send( + HttpRequest.newBuilder() + .uri(TestFixtures.endpoint().resolve(path)) + .DELETE() + .timeout(Duration.ofSeconds(10)) + .build(), + HttpResponse.BodyHandlers.ofString() + ); + + assertThat(resp.statusCode()) + .as("clearing inspection endpoint %s should succeed", path) + .isEqualTo(200); + } + + private static String fetchVerificationCodeFromSes(String recipient) throws Exception { + URI uri = TestFixtures.endpoint() + .resolve("/_aws/ses?email=" + URLEncoder.encode(recipient, StandardCharsets.UTF_8)); + + HttpResponse resp = HTTP.send( + HttpRequest.newBuilder() + .uri(uri) + .GET() + .timeout(Duration.ofSeconds(10)) + .build(), + HttpResponse.BodyHandlers.ofString() + ); + + JsonNode messages = JSON.readTree(resp.body()).path("messages"); + assertThat(messages.isArray() && !messages.isEmpty()) + .as("SES should have received a verification email for %s", recipient) + .isTrue(); + + String body = messages.get(0).path("Body").path("text_part").asText(); + return extractSixDigitCode(body); + } + + private static String fetchVerificationCodeFromSns(String phoneNumber) throws Exception { + URI uri = TestFixtures.endpoint() + .resolve("/_aws/sns?phone=" + URLEncoder.encode(phoneNumber, StandardCharsets.UTF_8)); + + HttpResponse resp = HTTP.send( + HttpRequest.newBuilder() + .uri(uri) + .GET() + .timeout(Duration.ofSeconds(10)) + .build(), + HttpResponse.BodyHandlers.ofString() + ); + + JsonNode messages = JSON.readTree(resp.body()).path("messages"); + assertThat(messages.isArray() && !messages.isEmpty()) + .as("SNS should have received a verification SMS for %s", phoneNumber) + .isTrue(); + + String body = messages.get(0).path("Message").asText(); + return extractSixDigitCode(body); + } + + private static String extractSixDigitCode(String body) { + Matcher matcher = SIX_DIGIT_CODE_PATTERN.matcher(body); + assertThat(matcher.find()) + .as("Verification message body should contain a 6-digit code") + .isTrue(); + + return matcher.group(1); + } + +} 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.java index 147f81eabe..7be4f47a3e 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 @@ -12,7 +12,14 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; -import io.github.hectorvent.floci.services.cognito.model.*; +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; +import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope; +import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo; +import io.github.hectorvent.floci.services.cognito.model.UserPool; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret; import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher; import io.github.hectorvent.floci.services.cognito.verification.VerificationCode; import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException; @@ -28,13 +35,32 @@ import org.jspecify.annotations.Nullable; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; -import java.security.*; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.time.Clock; import java.time.Duration; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags; @@ -1322,6 +1348,16 @@ public class CognitoService { } catch (VerificationCodeException e) { throw mapVerificationCodeException(e); } + + var signupDeliveryTarget = resolveSignUpDeliveryTarget(pool, user); + + if (signupDeliveryTarget != null) { + if ("email".equals(signupDeliveryTarget.attributeName())) { + user.getAttributes().put("email_verified", "true"); + } else if ("phone_number".equals(signupDeliveryTarget.attributeName())) { + user.getAttributes().put("phone_number_verified", "true"); + } + } } user.setUserStatus("CONFIRMED"); user.setLastModifiedDate(System.currentTimeMillis() / 1000L); 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.java index 125a626c43..e576b88d7e 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 @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDi import io.github.hectorvent.floci.services.cognito.verification.VerificationCode; import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -30,10 +31,7 @@ import java.util.function.Function; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; class CognitoServiceTest { @@ -2271,7 +2269,7 @@ class CognitoServiceTest { // ========================================================================= @ParameterizedTest - @CsvSource( { + @CsvSource({ "use-name,basic-client", "prepend-to-name:prepended-,prepended-basic-client", "append-to-name:-appended,basic-client-appended", @@ -2288,7 +2286,7 @@ class CognitoServiceTest { "us-east-1" ); - assertEquals("test",pool.getUserPoolTags().get("env")); + assertEquals("test", pool.getUserPoolTags().get("env")); assertFalse(pool.getUserPoolTags().containsKey(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY)); assertFalse(pool.getUserPoolTags().containsKey(ReservedTags.OVERRIDE_COGNITO_CLIENT_SECRET_KEY)); @@ -2307,7 +2305,7 @@ class CognitoServiceTest { } @ParameterizedTest - @CsvSource( { + @CsvSource({ "prepend-to-name: prepended- ,secret", "append-to-name: -appended ,secret", "append-to-name:-appended,", @@ -2315,7 +2313,7 @@ class CognitoServiceTest { }) void createUserPoolWithInvalidOverrideForClientIdAndClientSecret(String overrideClientId, String secret) { Map createUserPool = new HashMap<>(); - Map userPoolTags = new HashMap<>(); + Map userPoolTags = new HashMap<>(); userPoolTags.put(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY, overrideClientId); userPoolTags.put(ReservedTags.OVERRIDE_COGNITO_CLIENT_SECRET_KEY, secret); createUserPool.put("PoolName", "InvalidOverridesPool"); @@ -2329,4 +2327,226 @@ class CognitoServiceTest { assertEquals("InvalidParameterException", ex.getErrorCode()); } + + // Issue #1654: ConfirmSignUp updates verified attribute + @Nested + class ConfirmSignUpVerifiedAttributes { + + private CognitoService svc; + + @BeforeEach + void setUpVerificationService() { + svc = createVerificationEnabledService(); + } + + @Test + void confirmSignUpSetsEmailVerifiedAndDoesNotWritePhoneVerifiedForEmailOnlyUser() { + String poolName = "EmailVerifyPool"; + String username = "alice@example.com"; + String password = "Passw0rd!"; + + UserPool pool = svc.createUserPool(Map.of( + "PoolName", poolName, + "AutoVerifiedAttributes", List.of("email") + ), "us-east-1"); + UserPoolClient client = svc.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + svc.signUp(client.getClientId(), username, password, + Map.of("email", username)); + svc.confirmSignUp(client.getClientId(), username, "123456"); + + CognitoUser user = svc.adminGetUser(pool.getId(), username); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertEquals("true", user.getAttributes().get("email_verified"), + "ConfirmSignUp should set email_verified=true when email is the auto-verified attribute"); + assertFalse(user.getAttributes().containsKey("phone_number_verified"), + "ConfirmSignUp should not proactively write phone_number_verified when the user has no phone"); + } + + @Test + void confirmSignUpSetsPhoneNumberVerifiedAndDoesNotWriteEmailVerifiedForPhoneOnlyUser() { + String poolName = "PhoneVerifyPool"; + String username = "phone-user"; + String password = "Passw0rd!"; + String phoneNumber = "+491701234567"; + + UserPool pool = svc.createUserPool(Map.of( + "PoolName", poolName, + "AutoVerifiedAttributes", List.of("phone_number") + ), "us-east-1"); + UserPoolClient client = svc.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + svc.signUp(client.getClientId(), username, password, + Map.of("phone_number", phoneNumber)); + svc.confirmSignUp(client.getClientId(), username, "123456"); + + CognitoUser user = svc.adminGetUser(pool.getId(), username); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertEquals("true", user.getAttributes().get("phone_number_verified"), + "ConfirmSignUp should set phone_number_verified=true when phone_number is the auto-verified attribute"); + assertFalse(user.getAttributes().containsKey("email_verified"), + "ConfirmSignUp should not proactively write email_verified when the user has no email"); + } + + @Test + void confirmSignUpMarksOnlyPhoneNumberVerifiedWhenBothAutoVerifiedEvenWhenEmailListedFirst() { + String poolName = "BothVerifyEmailFirstPool"; + String email = "dual-user@example.com"; + String password = "Passw0rd!"; + String phoneNumber = "+491701234567"; + + UserPool pool = svc.createUserPool(Map.of( + "PoolName", poolName, + "AutoVerifiedAttributes", List.of("email", "phone_number") + ), "us-east-1"); + UserPoolClient client = svc.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + svc.signUp(client.getClientId(), email, password, + Map.of("email", email, "phone_number", phoneNumber)); + svc.confirmSignUp(client.getClientId(), email, "123456"); + + CognitoUser user = svc.adminGetUser(pool.getId(), email); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertEquals("true", user.getAttributes().get("phone_number_verified"), + "ConfirmSignUp should set phone_number_verified=true when both contacts are auto-verified, regardless of list order"); + assertFalse(user.getAttributes().containsKey("email_verified"), + "ConfirmSignUp should not set email_verified when the code was delivered to phone, not email"); + } + + @Test + void confirmSignUpMarksOnlyPhoneNumberVerifiedWhenBothAutoVerifiedAndPhoneIsFirstDeliveryTarget() { + String poolName = "BothVerifyPhoneFirstPool"; + String email = "dual-user2@example.com"; + String password = "Passw0rd!"; + String phoneNumber = "+491701234567"; + + UserPool pool = svc.createUserPool(Map.of( + "PoolName", poolName, + "AutoVerifiedAttributes", List.of("phone_number", "email") + ), "us-east-1"); + UserPoolClient client = svc.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + svc.signUp(client.getClientId(), email, password, + Map.of("email", email, "phone_number", phoneNumber)); + svc.confirmSignUp(client.getClientId(), email, "123456"); + + CognitoUser user = svc.adminGetUser(pool.getId(), email); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertEquals("true", user.getAttributes().get("phone_number_verified"), + "ConfirmSignUp should set phone_number_verified=true when phone_number is the first auto-verified delivery target"); + assertFalse(user.getAttributes().containsKey("email_verified"), + "ConfirmSignUp should not set email_verified when the code was delivered to phone, not email"); + } + + @Test + void confirmSignUpDoesNotSetVerifiedFlagsWhenPoolHasNoAutoVerifiedAttributes() { + String poolName = "NoAutoVerifyPool"; + String username = "no-auto-verify@example.com"; + String password = "Passw0rd!"; + + UserPool pool = svc.createUserPool(Map.of("PoolName", poolName), "us-east-1"); + UserPoolClient client = svc.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + svc.signUp(client.getClientId(), username, password, + Map.of("email", username)); + svc.confirmSignUp(client.getClientId(), username, "123456"); + + CognitoUser user = svc.adminGetUser(pool.getId(), username); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertFalse(user.getAttributes().containsKey("email_verified"), + "ConfirmSignUp should not set email_verified when the pool has no auto-verified attributes"); + assertFalse(user.getAttributes().containsKey("phone_number_verified"), + "ConfirmSignUp should not set phone_number_verified when the pool has no auto-verified attributes"); + } + + @Test + void confirmSignUpDoesNotSetVerifiedFlagsWhenVerificationServiceIsAbsent() { + String poolName = "NoVerificationServicePool"; + String username = "no-verification@example.com"; + String password = "Passw0rd!"; + + // The default service from setUp() has verificationCodeService == null. + UserPool pool = service.createUserPool(Map.of( + "PoolName", poolName, + "AutoVerifiedAttributes", List.of("email") + ), "us-east-1"); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + service.signUp(client.getClientId(), username, password, + Map.of("email", username)); + + service.confirmSignUp(client.getClientId(), username); + + CognitoUser user = service.adminGetUser(pool.getId(), username); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertFalse(user.getAttributes().containsKey("email_verified"), + "ConfirmSignUp should not set email_verified when no verification service is configured"); + assertFalse(user.getAttributes().containsKey("phone_number_verified"), + "ConfirmSignUp should not set phone_number_verified when no verification service is configured"); + } + + @Test + void confirmSignUpDoesNotSetVerifiedFlagsWhenDeliveryTargetIsNull() { + String poolName = "NullDeliveryTargetPool"; + String username = "email-only@example.com"; + String password = "Passw0rd!"; + + UserPool pool = svc.createUserPool(Map.of( + "PoolName", poolName, + "AutoVerifiedAttributes", List.of("email") + ), "us-east-1"); + UserPoolClient client = svc.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + svc.signUp(client.getClientId(), username, password, + Map.of("email", username)); + svc.updateUserPool(Map.of( + "UserPoolId", pool.getId(), + "AutoVerifiedAttributes", List.of("phone_number") + ), "us-east-1"); + + svc.confirmSignUp(client.getClientId(), username, "123456"); + + CognitoUser user = svc.adminGetUser(pool.getId(), username); + + assertEquals("CONFIRMED", user.getUserStatus()); + assertFalse(user.getAttributes().containsKey("email_verified"), + "ConfirmSignUp should not set email_verified when the user has no matching attribute for the updated auto verified attribute"); + assertFalse(user.getAttributes().containsKey("phone_number_verified"), + "ConfirmSignUp should not set phone_number_verified when the delivery target is null"); + } + + private CognitoService createVerificationEnabledService() { + VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) + .thenReturn("123456"); + return new CognitoService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + "http://localhost:4566", + regionResolver, + null, + verificationCodeService, + messageDispatcher + ); + } + } + }