From 068c96eb2e2e3fbb9afad63d19798550ceebead8 Mon Sep 17 00:00:00 2001 From: James McMahon Date: Tue, 10 Nov 2026 02:10:32 +0000 Subject: [PATCH] chore(cognito): share secret hash test helper (#7866) --- .../CognitoAliasUsernameIntegrationTest.java | 21 ++-------- .../cognito/CognitoLambdaTriggersTest.java | 22 +++------- .../CognitoOAuthTokenIntegrationTest.java | 8 +--- ...CognitoOptionalTotpMfaIntegrationTest.java | 12 +----- .../cognito/CognitoSecretHashTestHelper.java | 24 +++++++++++ .../CognitoSecretHashTestHelperTest.java | 23 +++++++++++ .../services/cognito/CognitoServiceTest.java | 40 +++++++------------ 7 files changed, 73 insertions(+), 77 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelper.java create mode 100644 src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelperTest.java diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoAliasUsernameIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoAliasUsernameIntegrationTest.java index a6c6476c61..9362c5bf90 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoAliasUsernameIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoAliasUsernameIntegrationTest.java @@ -12,14 +12,12 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.UUID; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -184,7 +182,7 @@ class CognitoAliasUsernameIntegrationTest { "SECRET_HASH": "%s" } } - """.formatted(clientId, EMAIL, PASSWORD, secretHash(uuidUsername))) + """.formatted(clientId, EMAIL, PASSWORD, secretHash(clientId, clientSecret, uuidUsername))) .then() .statusCode(400) .body("__type", containsString("NotAuthorizedException")); @@ -218,7 +216,7 @@ class CognitoAliasUsernameIntegrationTest { "SECRET_HASH": "%s" } } - """.formatted(clientId, EMAIL, PASSWORD, secretHash(EMAIL))) + """.formatted(clientId, EMAIL, PASSWORD, secretHash(clientId, clientSecret, EMAIL))) .then() .statusCode(400) .body("__type", containsString("UserNotFoundException")); @@ -245,18 +243,7 @@ class CognitoAliasUsernameIntegrationTest { "SECRET_HASH": "%s" } } - """.formatted(clientId, username, PASSWORD, secretHash(username))); - } - - private static String secretHash(String username) { - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - byte[] sig = mac.doFinal((username + clientId).getBytes(StandardCharsets.UTF_8)); - return Base64.getEncoder().encodeToString(sig); - } catch (Exception e) { - throw new RuntimeException(e); - } + """.formatted(clientId, username, PASSWORD, secretHash(clientId, clientSecret, username))); } private static boolean isUuid(String value) { diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java index 5462630e96..be6c2b2d0a 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java @@ -32,8 +32,6 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -54,6 +52,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash; import static io.floci.aws.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -2246,14 +2245,14 @@ class CognitoLambdaTriggersTest { AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session, Map.of("USERNAME", uuid, "ANSWER", "blue", - "SECRET_HASH", secretHash(secret, "custom@example.com", client.getClientId())))); + "SECRET_HASH", secretHash(client.getClientId(), secret, "custom@example.com")))); assertEquals("NotAuthorizedException", ex.getErrorCode()); // Round 2 with USERNAME=UUID and a matching SECRET_HASH over the UUID -> tokens issued. Map tokens = service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session, Map.of("USERNAME", uuid, "ANSWER", "blue", - "SECRET_HASH", secretHash(secret, uuid, client.getClientId()))); + "SECRET_HASH", secretHash(client.getClientId(), secret, uuid))); assertNotNull(((Map) tokens.get("AuthenticationResult")).get("AccessToken")); } @@ -2296,7 +2295,7 @@ class CognitoLambdaTriggersTest { AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session, Map.of("USERNAME", other.getUsername(), "ANSWER", "blue", - "SECRET_HASH", secretHash(secret, other.getUsername(), client.getClientId())))); + "SECRET_HASH", secretHash(client.getClientId(), secret, other.getUsername())))); assertEquals("NotAuthorizedException", ex.getErrorCode()); // The session user's own email alias still resolves to the session user, so it is accepted @@ -2304,21 +2303,10 @@ class CognitoLambdaTriggersTest { Map tokens = service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session, Map.of("USERNAME", "victim@example.com", "ANSWER", "blue", - "SECRET_HASH", secretHash(secret, "victim@example.com", client.getClientId()))); + "SECRET_HASH", secretHash(client.getClientId(), secret, "victim@example.com"))); assertNotNull(((Map) tokens.get("AuthenticationResult")).get("AccessToken")); } - private static String secretHash(String secret, String username, String clientId) { - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - byte[] sig = mac.doFinal((username + clientId).getBytes(StandardCharsets.UTF_8)); - return Base64.getEncoder().encodeToString(sig); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - // ========================================================================= // CustomMessage // ========================================================================= diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java index 765cc10c43..294ee48cd3 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java @@ -13,8 +13,6 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; @@ -34,6 +32,7 @@ import static io.floci.aws.services.cognito.CognitoCustomDomainFixtures.refreshG import static io.floci.aws.services.cognito.CognitoCustomDomainFixtures.signIn; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -856,10 +855,7 @@ class CognitoOAuthTokenIntegrationTest { cognitoAction("AdminSetUserPassword", """ {"UserPoolId": "%s", "Username": "%s", "Password": "%s", "Permanent": true} """.formatted(poolId, username, PASSWORD)).then().statusCode(200); - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - String secretHash = Base64.getEncoder().encodeToString( - mac.doFinal((username + confidentialId).getBytes(StandardCharsets.UTF_8))); + String secretHash = secretHash(confidentialId, secret, username); return cognitoJson("AdminInitiateAuth", """ {"UserPoolId": "%s", "ClientId": "%s", "AuthFlow": "ADMIN_USER_PASSWORD_AUTH", "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s", "SECRET_HASH": "%s"}} diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java index 3a0326966d..6e0604c237 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java @@ -9,15 +9,12 @@ import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.nio.charset.StandardCharsets; import java.time.Clock; -import java.util.Base64; import java.util.UUID; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; @@ -360,11 +357,4 @@ class CognitoOptionalTotpMfaIntegrationTest { {"AccessToken":"%s"} """.formatted(accessToken); } - - private static String secretHash(String clientId, String clientSecret, String username) throws Exception { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - return Base64.getEncoder().encodeToString( - mac.doFinal((username + clientId).getBytes(StandardCharsets.UTF_8))); - } } diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelper.java b/src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelper.java new file mode 100644 index 0000000000..44d990e34d --- /dev/null +++ b/src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelper.java @@ -0,0 +1,24 @@ +package io.floci.aws.services.cognito; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Base64; + +final class CognitoSecretHashTestHelper { + + private CognitoSecretHashTestHelper() { + } + + static String secretHash(String clientId, String clientSecret, String username) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return Base64.getEncoder().encodeToString( + mac.doFinal((username + clientId).getBytes(StandardCharsets.UTF_8))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Cannot calculate Cognito client secret hash", e); + } + } +} diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelperTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelperTest.java new file mode 100644 index 0000000000..bf18631932 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cognito/CognitoSecretHashTestHelperTest.java @@ -0,0 +1,23 @@ +package io.floci.aws.services.cognito; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CognitoSecretHashTestHelperTest { + + // Fixed vectors calculated independently with Python's hmac, hashlib and base64 modules. + @ParameterizedTest + @CsvSource({ + "client123, secret456, Alice@example.com, UAF9CmSqTygxn4m0hhVjVVBPyztYjZBZxbhPZIwkrYU=", + "client123, secret456, alice@example.com, VBQmj4yOlg2dnLjdFUcJTQKJxJp8nnjFCjgK0LPAsao=", + "other-client, secret456, Alice@example.com, xmSh78fSroLosX7/3koymYFUYqP808ITCcp9MzgSOzQ=", + "client123, other-secret, Alice@example.com, 8CiSDeuqhPw0+TSZpusFhWU6v+bSVtCrS+sLrcoNZZg=", + "clïent, sëcret🔑, 用户@example.com, eth4htEdy7jhZnEVn3LX34SfM8WhSb82MKvn8LPiig0=" + }) + void secretHashMatchesKnownVectors(String clientId, String clientSecret, String username, String expected) { + assertEquals(expected, secretHash(clientId, clientSecret, username)); + } +} diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java index 24feca91ca..857ca1a274 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java @@ -39,9 +39,6 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; @@ -70,6 +67,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash; import static io.floci.aws.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; @@ -5491,11 +5489,7 @@ class CognitoServiceTest { UserPool pool = createPoolAndUser(); UserPoolClient client = openClient(service, pool.getId(), "c", true); - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec( - client.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - String secretHash = Base64.getEncoder().encodeToString( - mac.doFinal(("alice" + client.getClientId()).getBytes(StandardCharsets.UTF_8))); + String secretHash = secretHash(client.getClientId(), client.getClientSecret(), "alice"); Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", Map.of("USERNAME", "alice", @@ -6021,7 +6015,7 @@ class CognitoServiceTest { client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_USER_SRP_AUTH")); String supplied = "Fixture@Example.com"; - String secretHash = secretHash(client, supplied); + String secretHash = secretHash(client.getClientId(), client.getClientSecret(), supplied); Map params = Map.of("USERNAME", supplied, "PASSWORD", password, "SECRET_HASH", secretHash); Map authenticated = initiateAuth(admin, pool, client, "USER_PASSWORD_AUTH", params); Map tokens = (Map) authenticated.get("AuthenticationResult"); @@ -6037,7 +6031,7 @@ class CognitoServiceTest { assertEquals(user.getUsername(), challenge.get("USER_ID_FOR_SRP")); Map proof = new HashMap<>(CognitoSrpTestClient.proof( pool.getId(), user.getUsername(), password, challenge)); - proof.put("SECRET_HASH", secretHash(client, user.getUsername())); + proof.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), user.getUsername())); Map completed = respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", (String) started.get("Session"), proof); assertNotNull(completed.get("AuthenticationResult")); } @@ -6056,13 +6050,6 @@ class CognitoServiceTest { : service.respondToAuthChallenge(client.getClientId(), challenge, session, responses); } - private String secretHash(UserPoolClient client, String username) throws Exception { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(client.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - return Base64.getEncoder().encodeToString( - mac.doFinal((username + client.getClientId()).getBytes(StandardCharsets.UTF_8))); - } - @ParameterizedTest @CsvSource({"false,false", "true,false", "false,true", "true,true", "false,default", "true,default"}) void srpChallengeRespectsUsernameCaseSensitivity(boolean admin, String setting) throws Exception { @@ -6078,7 +6065,7 @@ class CognitoServiceTest { String supplied = "false".equals(setting) ? "fixture" : user.getUsername(); Map started = initiateAuth(admin, pool, client, "USER_SRP_AUTH", Map.of("USERNAME", supplied, "SRP_A", CognitoSrpTestClient.publicA(), - "SECRET_HASH", secretHash(client, supplied))); + "SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), supplied))); Map challenge = (Map) started.get("ChallengeParameters"); assertEquals("Fixture", challenge.get("USER_ID_FOR_SRP")); String session = (String) started.get("Session"); @@ -6088,16 +6075,16 @@ class CognitoServiceTest { assertEquals("InvalidParameterException", assertThrows(AwsException.class, () -> respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof)).getErrorCode()); proof.put("USERNAME", "other"); - proof.put("SECRET_HASH", secretHash(client, "other")); + proof.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), "other")); assertEquals("NotAuthorizedException", assertThrows(AwsException.class, () -> respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof)).getErrorCode()); proof.put("USERNAME", "fixture"); - proof.put("SECRET_HASH", secretHash(client, "fixture")); + proof.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), "fixture")); if (!"false".equals(setting)) { assertEquals("NotAuthorizedException", assertThrows(AwsException.class, () -> respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof)).getErrorCode()); proof.put("USERNAME", user.getUsername()); - proof.put("SECRET_HASH", secretHash(client, user.getUsername())); + proof.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), user.getUsername())); } Map tokens = (Map) respondToChallenge(admin, pool, client, "PASSWORD_VERIFIER", session, proof).get("AuthenticationResult"); String accessToken = (String) tokens.get("AccessToken"); @@ -6120,7 +6107,7 @@ class CognitoServiceTest { String supplied = "false".equals(setting) ? "fixture" : user.getUsername(); Map started = initiateAuth(admin, pool, client, "USER_PASSWORD_AUTH", Map.of("USERNAME", supplied, "PASSWORD", temporaryPassword, - "SECRET_HASH", secretHash(client, supplied))); + "SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), supplied))); assertEquals("NEW_PASSWORD_REQUIRED", started.get("ChallengeName")); String session = (String) started.get("Session"); String newPassword = "Permanent-password123!"; @@ -6129,25 +6116,26 @@ class CognitoServiceTest { () -> respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses)) .getErrorCode()); responses.put("USERNAME", "other"); - responses.put("SECRET_HASH", secretHash(client, "other")); + responses.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), "other")); assertEquals("NotAuthorizedException", assertThrows(AwsException.class, () -> respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses)) .getErrorCode()); responses.put("USERNAME", "fixture"); - responses.put("SECRET_HASH", secretHash(client, "fixture")); + responses.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), "fixture")); if (!"false".equals(setting)) { assertEquals("NotAuthorizedException", assertThrows(AwsException.class, () -> respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses)) .getErrorCode()); responses.put("USERNAME", user.getUsername()); - responses.put("SECRET_HASH", secretHash(client, user.getUsername())); + responses.put("SECRET_HASH", secretHash(client.getClientId(), client.getClientSecret(), user.getUsername())); } Map tokens = (Map) respondToChallenge(admin, pool, client, "NEW_PASSWORD_REQUIRED", session, responses).get("AuthenticationResult"); assertNotNull(tokens.get("AccessToken")); assertEquals("Fixture", service.adminGetUser(pool.getId(), supplied).getUsername()); assertNotNull(initiateAuth(admin, pool, client, "USER_PASSWORD_AUTH", - Map.of("USERNAME", supplied, "PASSWORD", newPassword, "SECRET_HASH", secretHash(client, supplied))) + Map.of("USERNAME", supplied, "PASSWORD", newPassword, "SECRET_HASH", + secretHash(client.getClientId(), client.getClientSecret(), supplied))) .get("AuthenticationResult")); }