Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Mohith645c97c80368
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java
index c1585491b4..e1a4212c39 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java
@@ -4,6 +4,8 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminRespondToAuthChallengeResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
@@ -12,12 +14,16 @@ import software.amazon.awssdk.services.cognitoidentityprovider.model.InitiateAut
import software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidParameterException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.RespondToAuthChallengeResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolClientType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolMfaType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UsernameAttributeType;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
import java.time.Instant;
+import java.util.Base64;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
@@ -89,6 +95,76 @@ class CognitoOptionalTotpMfaTest {
}
}
+ @Test
+ @DisplayName("SOFTWARE_TOKEN_MFA names the sub and the device, and accepts the sub with its SECRET_HASH")
+ void sdkAnswersTheSoftwareTokenChallengeWithUserIdForSrp() throws Exception {
+ try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
+ String poolId = cognito.createUserPool(b -> b.poolName("email-totp-sdk-" + UUID.randomUUID())
+ .usernameAttributes(UsernameAttributeType.EMAIL)).userPool().id();
+ try {
+ cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId)
+ .mfaConfiguration(UserPoolMfaType.OPTIONAL)
+ .softwareTokenMfaConfiguration(m -> m.enabled(true)));
+ UserPoolClientType client = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
+ .clientName("email-totp-sdk-client").generateSecret(true)
+ .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_ADMIN_USER_PASSWORD_AUTH,
+ ExplicitAuthFlowsType.ALLOW_REFRESH_TOKEN_AUTH))
+ .userPoolClient();
+ String email = "totp-" + UUID.randomUUID() + "@example.com";
+ String sub = cognito.adminCreateUser(b -> b.userPoolId(poolId).username(email)
+ .userAttributes(a -> a.name("email").value(email),
+ a -> a.name("email_verified").value("true"))
+ .messageAction(MessageActionType.SUPPRESS)).user().username();
+ cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(email)
+ .password(PASSWORD).permanent(true));
+
+ String accessToken = adminPasswordLogin(cognito, poolId, client, email)
+ .authenticationResult().accessToken();
+ String secret = cognito.associateSoftwareToken(b -> b.accessToken(accessToken)).secretCode();
+ String setupCode = totp(secret, Instant.now());
+ cognito.verifySoftwareToken(b -> b.accessToken(accessToken).userCode(setupCode)
+ .friendlyDeviceName("sdk-device"));
+ cognito.adminSetUserMFAPreference(b -> b.userPoolId(poolId).username(email)
+ .softwareTokenMfaSettings(s -> s.enabled(true).preferredMfa(true)));
+
+ AdminInitiateAuthResponse challenged = adminPasswordLogin(cognito, poolId, client, email);
+ assertThat(challenged.challengeName()).isEqualTo(ChallengeNameType.SOFTWARE_TOKEN_MFA);
+ assertThat(challenged.challengeParameters()).containsOnly(
+ Map.entry("USER_ID_FOR_SRP", sub), Map.entry("FRIENDLY_DEVICE_NAME", "sdk-device"));
+
+ String userIdForSrp = challenged.challengeParameters().get("USER_ID_FOR_SRP");
+ String signInCode = totp(secret, Instant.now());
+ String challengeSecretHash = secretHash(client, userIdForSrp);
+ AdminRespondToAuthChallengeResponse signedIn = cognito.adminRespondToAuthChallenge(b -> b
+ .userPoolId(poolId).clientId(client.clientId())
+ .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA)
+ .session(challenged.session())
+ .challengeResponses(Map.of("USERNAME", userIdForSrp,
+ "SECRET_HASH", challengeSecretHash,
+ "SOFTWARE_TOKEN_MFA_CODE", signInCode)));
+ assertThat(signedIn.authenticationResult().accessToken()).isNotBlank();
+ } finally {
+ cognito.deleteUserPool(b -> b.userPoolId(poolId));
+ }
+ }
+ }
+
+ private static AdminInitiateAuthResponse adminPasswordLogin(CognitoIdentityProviderClient cognito,
+ String poolId, UserPoolClientType client,
+ String username) throws Exception {
+ String secretHash = secretHash(client, username);
+ return cognito.adminInitiateAuth(b -> b.userPoolId(poolId).clientId(client.clientId())
+ .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD, "SECRET_HASH", secretHash)));
+ }
+
+ private static String secretHash(UserPoolClientType client, String username) throws Exception {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(client.clientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
+ return Base64.getEncoder().encodeToString(
+ mac.doFinal((username + client.clientId()).getBytes(StandardCharsets.UTF_8)));
+ }
+
private static InitiateAuthResponse passwordLogin(CognitoIdentityProviderClient cognito, String clientId) {
return cognito.initiateAuth(b -> b.clientId(clientId)
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index 4ad06befa6..24c57e12a8 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -360,9 +360,13 @@ first factor returns `MFA_SETUP` instead of tokens for a user without a verified
Call `AssociateSoftwareToken` with that session, then `VerifySoftwareToken` with the
returned session and a six-digit TOTP code. Finish with `RespondToAuthChallenge`
(`MFA_SETUP`) to receive tokens. Later sign-ins return `SOFTWARE_TOKEN_MFA`, which
-requires a fresh code in `SOFTWARE_TOKEN_MFA_CODE`. Both token-management actions
-also accept an access token for an already authenticated user. Sessions expire with
-the app client's `AuthSessionValidity` and cannot be replayed after completion.
+requires a fresh code in `SOFTWARE_TOKEN_MFA_CODE`. Its `ChallengeParameters` carry
+`USER_ID_FOR_SRP`, the user's actual username rather than an alias (the `sub` in a pool
+with `UsernameAttributes`), to send back as `USERNAME` and to compute `SECRET_HASH` from,
+plus `FRIENDLY_DEVICE_NAME` when `VerifySoftwareToken` was given a `FriendlyDeviceName`.
+Both token-management actions also accept an access token for an already authenticated
+user. Sessions expire with the app client's `AuthSessionValidity` and cannot be replayed
+after completion.
Completing `MFA_SETUP` turns software-token MFA on for the user and, when no other factor is
preferred, makes it the preferred one, so `GetUser` and `AdminGetUser` report it.
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
index 11516a1a7f..fc213b671d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
@@ -58,6 +59,8 @@ final class CognitoAuthFlowHandler {
/** The message of a wrong password, which managed login also shows for an unknown user. */
static final String INCORRECT_CREDENTIALS = "Incorrect username or password";
static final int MAX_USER_AUTH_SESSIONS_PER_PARTITION = 4_096;
+ /** VerifySoftwareToken's {@code FriendlyDeviceName} length limit in the service model. */
+ static final int MAX_FRIENDLY_DEVICE_NAME_LENGTH = 131_072;
/** The challenges a USER_AUTH PREFERRED_CHALLENGE may name, in the order AWS lists them when refusing another. */
private static final List<String> PREFERRED_CHALLENGES =
List.of("PASSWORD", "PASSWORD_SRP", "SMS_OTP", "EMAIL_OTP", "WEB_AUTHN");
@@ -345,7 +348,16 @@ final class CognitoAuthFlowHandler {
return result;
}
- Map<String, Object> verifySoftwareToken(String accessToken, String session, String userCode) {
+ Map<String, Object> verifySoftwareToken(String accessToken, String session, String userCode,
+ String friendlyDeviceName) {
+ // Smithy's @length counts Unicode scalar values, so a supplementary character counts once.
+ int nameLength = friendlyDeviceName == null ? 0
+ : friendlyDeviceName.codePointCount(0, friendlyDeviceName.length());
+ if (nameLength > MAX_FRIENDLY_DEVICE_NAME_LENGTH) {
+ throw SmithyValidationErrors.exception("InvalidParameterException", "Value '" + friendlyDeviceName
+ + "' at 'friendlyDeviceName' failed to satisfy constraint: "
+ + "Member must have length less than or equal to " + MAX_FRIENDLY_DEVICE_NAME_LENGTH);
+ }
requireOneTotpCredential(accessToken, session);
if (userCode == null || !userCode.matches("[0-9]{6}")) {
throw new AwsException("InvalidParameterException", "UserCode must be a six-digit code", 400);
@@ -364,7 +376,7 @@ final class CognitoAuthFlowHandler {
username = token.username();
}
if (!service.activateSoftwareTokenMfa(poolId, username, state == null ? null : state.secret(),
- userCode, clock.instant())) {
+ userCode, friendlyDeviceName, clock.instant())) {
throw new AwsException("CodeMismatchException",
"Invalid verification code provided, please try again.", 400);
}
@@ -2213,9 +2225,15 @@ final class CognitoAuthFlowHandler {
phase, metadata, triggerSource, sessionExpiry(client, clock.instant()),
user.getSoftwareTokenMfaSecret()));
Map<String, String> parameters = new HashMap<>();
- parameters.put("USERNAME", user.getUsername());
if (phase == TotpPhase.SETUP) {
+ parameters.put("USERNAME", user.getUsername());
parameters.put("MFAS_CAN_SETUP", "[\"SOFTWARE_TOKEN_MFA\"]");
+ } else {
+ // As on AWS: the canonical username (never an alias) to answer with, and the authenticator's name.
+ parameters.put("USER_ID_FOR_SRP", user.getUsername());
+ if (user.getSoftwareTokenMfaDeviceName() != null) {
+ parameters.put("FRIENDLY_DEVICE_NAME", user.getSoftwareTokenMfaDeviceName());
+ }
}
result.put("ChallengeParameters", parameters);
return result;
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.java
index 455e223d77..6c7ef4784a 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
@@ -992,7 +992,7 @@ public class CognitoJsonHandler {
private Response handleVerifySoftwareToken(JsonNode request) {
Map<String, Object> result = service.verifySoftwareToken(
request.path("AccessToken").asText(null), request.path("Session").asText(null),
- request.path("UserCode").asText(null));
+ request.path("UserCode").asText(null), request.path("FriendlyDeviceName").asText(null));
return Response.ok(objectMapper.valueToTree(result)).build();
}
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 f1b3b60980..0f933ff08a 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
@@ -3679,7 +3679,12 @@ public class CognitoService implements ResourceProvider {
}
public Map<String, Object> verifySoftwareToken(String accessToken, String session, String userCode) {
- return authFlowHandler.verifySoftwareToken(accessToken, session, userCode);
+ return verifySoftwareToken(accessToken, session, userCode, null);
+ }
+
+ public Map<String, Object> verifySoftwareToken(String accessToken, String session, String userCode,
+ String friendlyDeviceName) {
+ return authFlowHandler.verifySoftwareToken(accessToken, session, userCode, friendlyDeviceName);
}
void beginSoftwareTokenMfa(String poolId, String username, String secret) {
@@ -3693,7 +3698,7 @@ public class CognitoService implements ResourceProvider {
}
boolean activateSoftwareTokenMfa(String poolId, String username, String expectedSecret,
- String code, Instant now) {
+ String code, String friendlyDeviceName, Instant now) {
synchronized (userLock(poolId, username)) {
CognitoUser user = adminGetUser(poolId, username);
String pending = user.getPendingSoftwareTokenMfaSecret();
@@ -3714,6 +3719,8 @@ public class CognitoService implements ResourceProvider {
return false;
}
user.setSoftwareTokenMfaSecret(pending);
+ user.setSoftwareTokenMfaDeviceName(friendlyDeviceName == null || friendlyDeviceName.isEmpty()
+ ? null : friendlyDeviceName);
user.setPendingSoftwareTokenMfaSecret(null);
user.setPendingSoftwareTokenMfaAttemptsRemaining(null);
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
index 7da2c2d2be..720000051e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
@@ -29,6 +29,7 @@ public class CognitoUser {
private SoftwareTokenMfaSettings softwareTokenMfaSettings;
private SmsMfaSettings smsMfaSettings;
private String softwareTokenMfaSecret;
+ private String softwareTokenMfaDeviceName;
private String pendingSoftwareTokenMfaSecret;
private Integer pendingSoftwareTokenMfaAttemptsRemaining;
private List<WebAuthnCredential> webAuthnCredentials = new ArrayList<>();
@@ -110,6 +111,10 @@ public class CognitoUser {
public String getSoftwareTokenMfaSecret() { return softwareTokenMfaSecret; }
public void setSoftwareTokenMfaSecret(String secret) { this.softwareTokenMfaSecret = secret; }
+ /** VerifySoftwareToken's {@code FriendlyDeviceName} for the active authenticator, or null when none was given. */
+ public String getSoftwareTokenMfaDeviceName() { return softwareTokenMfaDeviceName; }
+ public void setSoftwareTokenMfaDeviceName(String deviceName) { this.softwareTokenMfaDeviceName = deviceName; }
+
public String getPendingSoftwareTokenMfaSecret() { return pendingSoftwareTokenMfaSecret; }
public void setPendingSoftwareTokenMfaSecret(String secret) { this.pendingSoftwareTokenMfaSecret = secret; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java
index 3b25ada1eb..5624176b0d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java
@@ -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)));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java
index 4edc28d805..525a7e3306 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java
@@ -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
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java
index 85c641d5dd..998609772a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java
@@ -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(