fix(cognito): return USER_ID_FOR_SRP in the SOFTWARE_TOKEN_MFA challenge (#6086)

* fix(cognito): return USER_ID_FOR_SRP in the SOFTWARE_TOKEN_MFA challenge

The SOFTWARE_TOKEN_MFA challenge carried the canonical username under
USERNAME. AWS returns it as USER_ID_FOR_SRP, the key clients read to
build USERNAME and SECRET_HASH for the challenge response, so they could
not answer the challenge.

The challenge now carries USER_ID_FOR_SRP (the sub in a pool with
UsernameAttributes) and FRIENDLY_DEVICE_NAME when one was set, matching
the InitiateAuth API reference example. VerifySoftwareToken keeps the
FriendlyDeviceName on the user and replaces it with each newly verified
authenticator. Every flow that ends in SOFTWARE_TOKEN_MFA shares the
same builder, so password, admin password, SRP, USER_AUTH,
NEW_PASSWORD_REQUIRED and SELECT_MFA_TYPE all get the new parameters.
MFA_SETUP is unchanged.

Fixes #6074

* fix(cognito): reject an over-long FriendlyDeviceName in VerifySoftwareToken

VerifySoftwareToken stored a FriendlyDeviceName of any length and later
returned it in the SOFTWARE_TOKEN_MFA challenge. The service model caps
the member at 131072 characters, and AWS rejects a longer value during
request validation, before the code is checked.

A longer name now fails with InvalidParameterException and the Smithy
length-constraint message, before any session, token or code is looked
at, so the user's authenticator, pending association and remaining
attempts are left as they were. The length counts Unicode code points,
as Smithy's length trait does, so a name of supplementary characters
such as emoji is measured in characters rather than UTF-16 units. An
absent or empty name is unchanged.
This commit is contained in:
Mohith authored and GitHub committed 2026-10-20 13:02:17 -04:00
1 parent 17f32c9d04
commit 645c97c803
9 files changed
+388 -9

No files matched your search

@@ -1,13 +1,19 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
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.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
@@ -18,10 +24,12 @@ import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CognitoOptionalTotpMfaIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String PASSWORD = "Perm1234!";
@Inject
@@ -150,6 +158,173 @@ class CognitoOptionalTotpMfaIntegrationTest {
assertTrue(challenged.path("AuthenticationResult").isMissingNode());
}
@Test
void softwareTokenChallengeNamesTheSubAndDeviceOfAnEmailUsernameUser() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"EmailTotpPool","UsernameAttributes":["email"]}
""").path("UserPool").path("Id").asText();
cognitoJson("SetUserPoolMfaConfig", """
{"UserPoolId":"%s","MfaConfiguration":"OPTIONAL",
"SoftwareTokenMfaConfiguration":{"Enabled":true}}
""".formatted(poolId));
JsonNode client = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"email-totp-client","GenerateSecret":true,
"ExplicitAuthFlows":["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]}
""".formatted(poolId)).path("UserPoolClient");
String clientId = client.path("ClientId").asText();
String clientSecret = client.path("ClientSecret").asText();
String email = "totp-" + UUID.randomUUID() + "@example.com";
String sub = cognitoJson("AdminCreateUser", """
{"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS",
"UserAttributes":[{"Name":"email","Value":"%s"},{"Name":"email_verified","Value":"true"}]}
""".formatted(poolId, email, email)).path("User").path("Username").asText();
assertNotEquals(email, sub);
cognitoJson("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
""".formatted(poolId, email, PASSWORD));
String loginRequest = """
{"UserPoolId":"%s","ClientId":"%s","AuthFlow":"ADMIN_USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s","SECRET_HASH":"%s"}}
""".formatted(poolId, clientId, email, PASSWORD, secretHash(clientId, clientSecret, email));
String accessToken = cognitoJson("AdminInitiateAuth", loginRequest)
.path("AuthenticationResult").path("AccessToken").asText();
String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
.path("SecretCode").asText();
assertEquals("SUCCESS", cognitoJson("VerifySoftwareToken", """
{"AccessToken":"%s","UserCode":"%s","FriendlyDeviceName":"repro-device"}
""".formatted(accessToken, CognitoTotp.code(secret, clock.instant()))).path("Status").asText());
cognitoAction("AdminSetUserMFAPreference", """
{"UserPoolId":"%s","Username":"%s",
"SoftwareTokenMfaSettings":{"Enabled":true,"PreferredMfa":true}}
""".formatted(poolId, email))
.then().statusCode(200);
JsonNode challenged = cognitoJson("AdminInitiateAuth", loginRequest);
assertEquals("SOFTWARE_TOKEN_MFA", challenged.path("ChallengeName").asText());
JsonNode parameters = challenged.path("ChallengeParameters");
assertEquals(sub, parameters.path("USER_ID_FOR_SRP").asText());
assertEquals("repro-device", parameters.path("FRIENDLY_DEVICE_NAME").asText());
assertEquals(2, parameters.size());
String userIdForSrp = parameters.path("USER_ID_FOR_SRP").asText();
JsonNode signedIn = cognitoJson("AdminRespondToAuthChallenge", """
{"UserPoolId":"%s","ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s",
"ChallengeResponses":{"USERNAME":"%s","SECRET_HASH":"%s","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
""".formatted(poolId, clientId, challenged.path("Session").asText(), userIdForSrp,
secretHash(clientId, clientSecret, userIdForSrp), CognitoTotp.code(secret, clock.instant())));
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
}
@Test
void softwareTokenChallengeOmitsTheDeviceNameWhenNoneWasGiven() throws Exception {
String poolId = createOptionalPool();
String clientId = createClient(poolId);
String username = "unnamed-" + UUID.randomUUID();
createUser(poolId, username);
String loginRequest = """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(clientId, username, PASSWORD);
String accessToken = cognitoJson("InitiateAuth", loginRequest)
.path("AuthenticationResult").path("AccessToken").asText();
String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
.path("SecretCode").asText();
cognitoJson("VerifySoftwareToken", """
{"AccessToken":"%s","UserCode":"%s"}
""".formatted(accessToken, CognitoTotp.code(secret, clock.instant())));
cognitoAction("SetUserMFAPreference", """
{"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true,"PreferredMfa":true}}
""".formatted(accessToken))
.then().statusCode(200);
JsonNode challenged = cognitoJson("InitiateAuth", loginRequest);
assertEquals("SOFTWARE_TOKEN_MFA", challenged.path("ChallengeName").asText());
JsonNode parameters = challenged.path("ChallengeParameters");
assertEquals(username, parameters.path("USER_ID_FOR_SRP").asText());
assertEquals(1, parameters.size());
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", """
{"ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s",
"ChallengeResponses":{"USERNAME":"%s","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
""".formatted(clientId, challenged.path("Session").asText(),
parameters.path("USER_ID_FOR_SRP").asText(), CognitoTotp.code(secret, clock.instant())));
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
}
@Test
void verifySoftwareTokenRejectsAnOverLongFriendlyDeviceName() throws Exception {
String poolId = createOptionalPool();
String clientId = createClient(poolId);
String username = "long-name-" + UUID.randomUUID();
createUser(poolId, username);
String accessToken = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(clientId, username, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
.path("SecretCode").asText();
String tooLong = "d".repeat(CognitoAuthFlowHandler.MAX_FRIENDLY_DEVICE_NAME_LENGTH + 1);
cognitoAction("VerifySoftwareToken", """
{"AccessToken":"%s","UserCode":"%s","FriendlyDeviceName":"%s"}
""".formatted(accessToken, CognitoTotp.code(secret, clock.instant()), tooLong))
.then().statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", equalTo("1 validation error detected: Value '" + tooLong
+ "' at 'friendlyDeviceName' failed to satisfy constraint: "
+ "Member must have length less than or equal to 131072"));
cognitoAction("SetUserMFAPreference", """
{"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true}}
""".formatted(accessToken))
.then().statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
}
@Test
void friendlyDeviceNameOfSupplementaryCharactersIsLimitedByCharacterCount() throws Exception {
String poolId = createOptionalPool();
String clientId = createClient(poolId);
String username = "emoji-name-" + UUID.randomUUID();
createUser(poolId, username);
String loginRequest = """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(clientId, username, PASSWORD);
String accessToken = cognitoJson("InitiateAuth", loginRequest)
.path("AuthenticationResult").path("AccessToken").asText();
int limit = CognitoAuthFlowHandler.MAX_FRIENDLY_DEVICE_NAME_LENGTH;
// JSON escapes keep the request ASCII whatever charset the client encodes it with.
String escapedEmoji = "\\uD83D\\uDE00";
String rejectedSecret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
.path("SecretCode").asText();
Response rejected = cognitoAction("VerifySoftwareToken", """
{"AccessToken":"%s","UserCode":"%s","FriendlyDeviceName":"%s"}
""".formatted(accessToken, CognitoTotp.code(rejectedSecret, clock.instant()),
escapedEmoji.repeat(limit + 1)));
assertEquals(400, rejected.statusCode());
JsonNode error = JSON.readTree(rejected.asByteArray());
assertEquals("InvalidParameterException", error.path("__type").asText());
assertEquals("1 validation error detected: Value '" + "\uD83D\uDE00".repeat(limit + 1)
+ "' at 'friendlyDeviceName' failed to satisfy constraint: "
+ "Member must have length less than or equal to 131072", error.path("message").asText());
String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
.path("SecretCode").asText();
assertEquals("SUCCESS", cognitoJson("VerifySoftwareToken", """
{"AccessToken":"%s","UserCode":"%s","FriendlyDeviceName":"%s"}
""".formatted(accessToken, CognitoTotp.code(secret, clock.instant()), escapedEmoji.repeat(limit)))
.path("Status").asText());
cognitoAction("SetUserMFAPreference", """
{"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true,"PreferredMfa":true}}
""".formatted(accessToken))
.then().statusCode(200);
JsonNode challenged = JSON.readTree(cognitoAction("InitiateAuth", loginRequest).asByteArray());
assertEquals("\uD83D\uDE00".repeat(limit),
challenged.path("ChallengeParameters").path("FRIENDLY_DEVICE_NAME").asText());
}
private static String createOptionalPool() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"OptionalTotpPool","UserPoolTier":"ESSENTIALS",
@@ -185,4 +360,11 @@ 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)));
}
}
@@ -155,6 +155,92 @@ class CognitoOptionalTotpMfaTest {
"TIMESTAMP", timestamp));
assertEquals("SOFTWARE_TOKEN_MFA", verified.get("ChallengeName"));
assertFalse(verified.containsKey("AuthenticationResult"));
assertEquals(Map.of("USER_ID_FOR_SRP", USERNAME), verified.get("ChallengeParameters"));
}
@Test
void softwareTokenChallengeNamesTheVerifiedDeviceUntilItIsReplaced() throws Exception {
String accessToken = accessToken();
String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
service.verifySoftwareToken(accessToken, null, CognitoTotp.code(secret, clock.instant()), "work-phone");
service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED);
Map<String, Object> challenged = service.adminInitiateAuth(pool.getId(), client.getClientId(),
"ADMIN_USER_PASSWORD_AUTH", Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD));
assertEquals("SOFTWARE_TOKEN_MFA", challenged.get("ChallengeName"));
assertEquals(Map.of("USER_ID_FOR_SRP", USERNAME, "FRIENDLY_DEVICE_NAME", "work-phone"),
challenged.get("ChallengeParameters"));
ObjectMapper mapper = new ObjectMapper();
CognitoUser restored = mapper.readValue(
mapper.writeValueAsBytes(service.adminGetUser(pool.getId(), USERNAME)), CognitoUser.class);
assertEquals("work-phone", restored.getSoftwareTokenMfaDeviceName());
String replacement = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
service.verifySoftwareToken(accessToken, null, CognitoTotp.code(replacement, clock.instant()));
assertEquals(Map.of("USER_ID_FOR_SRP", USERNAME), passwordLogin().get("ChallengeParameters"));
}
@Test
void friendlyDeviceNameAtTheLengthLimitIsKept() {
String accessToken = accessToken();
String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
String longestName = "d".repeat(CognitoAuthFlowHandler.MAX_FRIENDLY_DEVICE_NAME_LENGTH);
assertEquals("SUCCESS", service.verifySoftwareToken(accessToken, null,
CognitoTotp.code(secret, clock.instant()), longestName).get("Status"));
service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED);
assertEquals(Map.of("USER_ID_FOR_SRP", USERNAME, "FRIENDLY_DEVICE_NAME", longestName),
passwordLogin().get("ChallengeParameters"));
}
@Test
void friendlyDeviceNameLengthCountsCharactersNotUtf16Units() {
String accessToken = accessToken();
int limit = CognitoAuthFlowHandler.MAX_FRIENDLY_DEVICE_NAME_LENGTH;
for (int characters : List.of(limit / 2 + 1, limit)) {
String name = "\uD83D\uDE00".repeat(characters);
String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
assertEquals("SUCCESS", service.verifySoftwareToken(accessToken, null,
CognitoTotp.code(secret, clock.instant()), name).get("Status"));
assertEquals(name, service.adminGetUser(pool.getId(), USERNAME).getSoftwareTokenMfaDeviceName());
}
String tooLong = "\uD83D\uDE00".repeat(limit + 1);
String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
AwsException rejected = assertThrows(AwsException.class, () -> service.verifySoftwareToken(
accessToken, null, CognitoTotp.code(secret, clock.instant()), tooLong));
assertEquals("InvalidParameterException", rejected.getErrorCode());
assertEquals("1 validation error detected: Value '" + tooLong + "' at 'friendlyDeviceName' failed to "
+ "satisfy constraint: Member must have length less than or equal to 131072", rejected.getMessage());
assertEquals(secret, service.adminGetUser(pool.getId(), USERNAME).getPendingSoftwareTokenMfaSecret());
}
@Test
void friendlyDeviceNameOverTheLengthLimitChangesNothing() {
String accessToken = accessToken();
String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
service.verifySoftwareToken(accessToken, null, CognitoTotp.code(secret, clock.instant()), "work-phone");
String replacement = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
String code = CognitoTotp.code(replacement, clock.instant());
String wrongCode = code.equals("000000") ? "000001" : "000000";
String tooLong = "d".repeat(CognitoAuthFlowHandler.MAX_FRIENDLY_DEVICE_NAME_LENGTH + 1);
for (String userCode : List.of(code, wrongCode)) {
AwsException rejected = assertThrows(AwsException.class,
() -> service.verifySoftwareToken(accessToken, null, userCode, tooLong));
assertEquals("InvalidParameterException", rejected.getErrorCode());
assertEquals("1 validation error detected: Value '" + tooLong + "' at 'friendlyDeviceName' failed to "
+ "satisfy constraint: Member must have length less than or equal to 131072",
rejected.getMessage());
}
CognitoUser user = service.adminGetUser(pool.getId(), USERNAME);
assertEquals(secret, user.getSoftwareTokenMfaSecret());
assertEquals("work-phone", user.getSoftwareTokenMfaDeviceName());
assertEquals(replacement, user.getPendingSoftwareTokenMfaSecret());
assertEquals(CognitoTotp.MAX_FAILED_ATTEMPTS, user.getPendingSoftwareTokenMfaAttemptsRemaining());
assertEquals("SUCCESS", service.verifySoftwareToken(accessToken, null, code, "new-phone").get("Status"));
assertEquals("new-phone", service.adminGetUser(pool.getId(), USERNAME).getSoftwareTokenMfaDeviceName());
}
@Test
@@ -94,6 +94,7 @@ class CognitoTotpMfaTest {
Map<String, Object> later = passwordLogin();
assertEquals("SOFTWARE_TOKEN_MFA", later.get("ChallengeName"));
assertFalse(later.containsKey("AuthenticationResult"));
assertEquals(Map.of("USER_ID_FOR_SRP", USERNAME), later.get("ChallengeParameters"));
String laterSession = (String) later.get("Session");
String wrongCode = code.equals("000000") ? "000001" : "000000";
AwsException mismatch = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(