feat(cognito): support software-token MFA setup and challenges (#4620)

* feat(cognito): require TOTP MFA after primary authentication

* test(cognito): verify TOTP MFA with Java SDK

* fix(cognito): reject disabled users completing TOTP challenges

* fix(cognito): preserve new-password trigger through TOTP

* fix(cognito): gate custom password auth with required MFA

* fix(cognito): limit failed TOTP verification attempts

* fix(cognito): report code mismatch for invalid TOTP setup
This commit is contained in:
XuJian authored and GitHub committed 2026-09-29 19:43:09 -05:00
1 parent e6894119f4
commit 433893d298
12 files changed
+1031 -24

No files matched your search

@@ -28,14 +28,14 @@ import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -491,6 +491,37 @@ class CognitoLambdaTriggersTest {
// PreTokenGeneration
// =========================================================================
@Test
void newPasswordMfaSetupPreservesPreTokenGenerationSource() throws Exception {
MutableClock clock = new MutableClock();
service = serviceWithClock(clock);
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "Temp1234!");
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
.thenReturn(ok(Map.of()));
Map<String, Object> login = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Temp1234!"));
assertEquals("NEW_PASSWORD_REQUIRED", login.get("ChallengeName"));
Map<String, Object> setup = service.respondToAuthChallenge(client.getClientId(),
"NEW_PASSWORD_REQUIRED", (String) login.get("Session"),
Map.of("USERNAME", "alice", "NEW_PASSWORD", "Perm1234!"));
assertEquals("MFA_SETUP", setup.get("ChallengeName"));
Map<String, Object> associated = service.associateSoftwareToken(null, (String) setup.get("Session"));
String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant());
Map<String, Object> verified = service.verifySoftwareToken(null, (String) associated.get("Session"), code);
Map<String, Object> tokens = service.respondToAuthChallenge(client.getClientId(),
"MFA_SETUP", (String) verified.get("Session"), Map.of("USERNAME", "alice"));
assertNotNull(tokens.get("AuthenticationResult"));
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payload.capture(), any());
Map<String, Object> event = MAPPER.readValue(payload.getValue(), new TypeReference<>() {});
assertEquals("TokenGeneration_NewPasswordChallenge", event.get("triggerSource"));
}
@Test
@SuppressWarnings("unchecked")
void preTokenGenerationAddsAndOverridesClaims() {
@@ -984,6 +1015,30 @@ class CognitoLambdaTriggersTest {
// CUSTOM_AUTH triggers (already covered indirectly; check triggerSource wiring)
// =========================================================================
@Test
void customPasswordChallengeRequiresTotpBeforeIssuingTokens() {
UserPool pool = createPoolWithLambdaConfig(Map.of(
"DefineAuthChallenge", "arn:aws:lambda:::define",
"CreateAuthChallenge", "arn:aws:lambda:::create"));
seedUser(pool, "alice", "Perm1234!");
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))
.thenReturn(ok(Map.of("challengeName", "PASSWORD_VERIFIER")))
.thenReturn(ok(Map.of("issueTokens", true)));
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))
.thenReturn(ok(Map.of()));
Map<String, Object> started = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
Map.of("USERNAME", "alice"));
assertEquals("PASSWORD_VERIFIER", started.get("ChallengeName"));
Map<String, Object> completed = service.respondToAuthChallenge(client.getClientId(),
"PASSWORD_VERIFIER", (String) started.get("Session"),
Map.of("USERNAME", "alice", "ANSWER", "Perm1234!"));
assertEquals("MFA_SETUP", completed.get("ChallengeName"));
assertFalse(completed.containsKey("AuthenticationResult"));
}
@Test
@SuppressWarnings("unchecked")
void customAuthInvokesDefineAndCreateChallengeTriggers() {
@@ -0,0 +1,95 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CognitoTotpMfaIntegrationTest {
@Inject
Clock clock;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void jsonProtocolRequiresTotpBeforeIssuingTokens() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"TotpProtocolPool"}
""").path("UserPool").path("Id").asText();
cognitoJson("SetUserPoolMfaConfig", """
{"UserPoolId":"%s","MfaConfiguration":"ON",
"SoftwareTokenMfaConfiguration":{"Enabled":true}}
""".formatted(poolId));
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"totp-protocol-client",
"ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_SRP_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
cognitoJson("AdminCreateUser", """
{"UserPoolId":"%s","Username":"totp-user","MessageAction":"SUPPRESS"}
""".formatted(poolId));
cognitoJson("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"totp-user",
"Password":"Perm1234!","Permanent":true}
""".formatted(poolId));
String loginRequest = """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"totp-user","PASSWORD":"Perm1234!"}}
""".formatted(clientId);
JsonNode login = cognitoJson("InitiateAuth", loginRequest);
assertEquals("MFA_SETUP", login.path("ChallengeName").asText());
assertTrue(login.path("AuthenticationResult").isMissingNode());
String firstSession = login.path("Session").asText();
JsonNode associated = cognitoJson("AssociateSoftwareToken", """
{"Session":"%s"}
""".formatted(firstSession));
assertTrue(associated.path("SecretCode").asText().matches("[A-Z2-7]{32}"));
String code = CognitoTotp.code(associated.path("SecretCode").asText(), clock.instant());
String wrongCode = code.equals("000000") ? "000001" : "000000";
cognitoAction("VerifySoftwareToken", """
{"Session":"%s","UserCode":"%s"}
""".formatted(associated.path("Session").asText(), wrongCode))
.then().statusCode(400).body("__type", equalTo("CodeMismatchException"));
JsonNode verified = cognitoJson("VerifySoftwareToken", """
{"Session":"%s","UserCode":"%s"}
""".formatted(associated.path("Session").asText(), code));
assertEquals("SUCCESS", verified.path("Status").asText());
JsonNode completed = cognitoJson("RespondToAuthChallenge", """
{"ClientId":"%s","ChallengeName":"MFA_SETUP","Session":"%s",
"ChallengeResponses":{"USERNAME":"totp-user"}}
""".formatted(clientId, verified.path("Session").asText()));
assertFalse(completed.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
JsonNode later = cognitoJson("InitiateAuth", loginRequest);
assertEquals("SOFTWARE_TOKEN_MFA", later.path("ChallengeName").asText());
assertTrue(later.path("AuthenticationResult").isMissingNode());
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", """
{"ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s",
"ChallengeResponses":{"USERNAME":"totp-user","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
""".formatted(clientId, later.path("Session").asText(), code));
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
String replay = """
{"ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s",
"ChallengeResponses":{"USERNAME":"totp-user","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
""".formatted(clientId, later.path("Session").asText(), code);
cognitoAction("RespondToAuthChallenge", replay).then().statusCode(400);
}
}
@@ -0,0 +1,361 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.AcmService;
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;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class CognitoTotpMfaTest {
private static final String USERNAME = "alice";
private static final String PASSWORD = "Perm1234!";
private CognitoService service;
private MutableClock clock;
private UserPool pool;
private UserPoolClient client;
@BeforeEach
void setUp() {
clock = new MutableClock();
service = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
"http://localhost:4566", "cloudfront.net",
new RegionResolver("us-east-1", "000000000000"), null, mock(AcmService.class),
null, null, null, clock);
pool = service.createUserPool(Map.of("PoolName", "TotpTestPool"), "us-east-1");
service.adminCreateUser(pool.getId(), USERNAME, Map.of("email", "alice@example.com"), null);
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, true);
client = service.createUserPoolClient(pool.getId(), "totp-client", false, false, List.of(), List.of());
client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_SRP_AUTH"));
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
}
@Test
void setupAndLaterSignInRequireSeparateTotpChallenges() {
Map<String, Object> login = passwordLogin();
assertEquals("MFA_SETUP", login.get("ChallengeName"));
assertFalse(login.containsKey("AuthenticationResult"));
assertTrue(String.valueOf(login.get("ChallengeParameters")).contains("SOFTWARE_TOKEN_MFA"));
String loginSession = (String) login.get("Session");
Map<String, Object> association = service.associateSoftwareToken(null, loginSession);
String secret = (String) association.get("SecretCode");
String associationSession = (String) association.get("Session");
assertNotNull(secret);
assertFalse(loginSession.equals(associationSession));
AwsException wrong = assertThrows(AwsException.class, () -> service.verifySoftwareToken(
null, associationSession, "not-a-code"));
assertEquals("InvalidParameterException", wrong.getErrorCode());
String code = CognitoTotp.code(secret, clock.instant());
Map<String, Object> verified = service.verifySoftwareToken(null, associationSession, code);
assertEquals("SUCCESS", verified.get("Status"));
String verifiedSession = (String) verified.get("Session");
assertFalse(associationSession.equals(verifiedSession));
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", loginSession,
Map.of("USERNAME", USERNAME))).getErrorCode());
Map<String, Object> authenticated = service.respondToAuthChallenge(client.getClientId(),
"MFA_SETUP", verifiedSession, Map.of("USERNAME", USERNAME));
assertNotNull(((Map<?, ?>) authenticated.get("AuthenticationResult")).get("AccessToken"));
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
Map.of("USERNAME", USERNAME))).getErrorCode());
Map<String, Object> later = passwordLogin();
assertEquals("SOFTWARE_TOKEN_MFA", later.get("ChallengeName"));
assertFalse(later.containsKey("AuthenticationResult"));
String laterSession = (String) later.get("Session");
String wrongCode = code.equals("000000") ? "000001" : "000000";
AwsException mismatch = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
client.getClientId(), "SOFTWARE_TOKEN_MFA", laterSession,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", wrongCode)));
assertEquals("CodeMismatchException", mismatch.getErrorCode());
Map<String, Object> completed = service.respondToAuthChallenge(client.getClientId(),
"SOFTWARE_TOKEN_MFA", laterSession,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code));
assertNotNull(((Map<?, ?>) completed.get("AuthenticationResult")).get("AccessToken"));
}
@Test
void disabledUserCannotCompleteMfaSetupChallenge() {
String loginSession = (String) passwordLogin().get("Session");
Map<String, Object> association = service.associateSoftwareToken(null, loginSession);
String code = CognitoTotp.code((String) association.get("SecretCode"), clock.instant());
String verifiedSession = (String) service.verifySoftwareToken(null,
(String) association.get("Session"), code).get("Session");
service.adminDisableUser(pool.getId(), USERNAME);
AwsException disabled = assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
Map.of("USERNAME", USERNAME)));
assertEquals("UserNotConfirmedException", disabled.getErrorCode());
}
@Test
void disabledUserCannotCompleteSoftwareTokenChallenge() {
String loginSession = (String) passwordLogin().get("Session");
Map<String, Object> association = service.associateSoftwareToken(null, loginSession);
String code = CognitoTotp.code((String) association.get("SecretCode"), clock.instant());
String verifiedSession = (String) service.verifySoftwareToken(null,
(String) association.get("Session"), code).get("Session");
service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
Map.of("USERNAME", USERNAME));
String challengeSession = (String) passwordLogin().get("Session");
service.adminDisableUser(pool.getId(), USERNAME);
AwsException disabled = assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA", challengeSession,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code)));
assertEquals("UserNotConfirmedException", disabled.getErrorCode());
}
@Test
void setupSessionExpiresAndCannotBeUsedByAnotherClient() {
String session = (String) passwordLogin().get("Session");
UserPoolClient other = service.createUserPoolClient(pool.getId(), "other", false, false, List.of(), List.of());
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(other.getClientId(), "MFA_SETUP", session,
Map.of("USERNAME", USERNAME))).getErrorCode());
clock.advance(Duration.ofMinutes(client.getAuthSessionValidity()).plusSeconds(1));
AwsException expired = assertThrows(AwsException.class,
() -> service.associateSoftwareToken(null, session));
assertEquals("NotAuthorizedException", expired.getErrorCode());
assertTrue(expired.getMessage().contains("expired"));
}
@Test
void associationRejectsPoolsWithoutSoftwareTokenMfa() {
service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false);
String accessToken = (String) ((Map<?, ?>) passwordLogin().get("AuthenticationResult")).get("AccessToken");
AwsException unsupported = assertThrows(AwsException.class,
() -> service.associateSoftwareToken(accessToken, null));
assertEquals("SoftwareTokenMFANotFoundException", unsupported.getErrorCode());
}
@Test
void invalidSetupCodeUsesCodeMismatchError() {
String loginSession = (String) passwordLogin().get("Session");
Map<String, Object> associated = service.associateSoftwareToken(null, loginSession);
String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant());
String wrongCode = code.equals("000000") ? "000001" : "000000";
AwsException mismatch = assertThrows(AwsException.class,
() -> service.verifySoftwareToken(null, (String) associated.get("Session"), wrongCode));
assertEquals("CodeMismatchException", mismatch.getErrorCode());
}
@Test
void repeatedWrongSetupCodesInvalidatePendingSoftwareToken() throws Exception {
String loginSession = (String) passwordLogin().get("Session");
Map<String, Object> associated = service.associateSoftwareToken(null, loginSession);
String session = (String) associated.get("Session");
String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant());
String wrongCode = code.equals("000000") ? "000001" : "000000";
for (int attempt = 0; attempt < CognitoTotp.MAX_FAILED_ATTEMPTS; attempt++) {
AwsException mismatch = assertThrows(AwsException.class,
() -> service.verifySoftwareToken(null, session, wrongCode));
assertEquals("CodeMismatchException", mismatch.getErrorCode());
}
CognitoUser pending = service.adminGetUser(pool.getId(), USERNAME);
ObjectMapper mapper = new ObjectMapper();
CognitoUser reloaded = mapper.readValue(mapper.writeValueAsBytes(pending), CognitoUser.class);
assertEquals(0, reloaded.getPendingSoftwareTokenMfaAttemptsRemaining());
assertEquals("CodeMismatchException", assertThrows(AwsException.class,
() -> service.verifySoftwareToken(null, session, code)).getErrorCode());
Map<String, Object> replacement = service.associateSoftwareToken(null,
(String) passwordLogin().get("Session"));
String replacementCode = CognitoTotp.code((String) replacement.get("SecretCode"), clock.instant());
assertEquals("SUCCESS", service.verifySoftwareToken(null,
(String) replacement.get("Session"), replacementCode).get("Status"));
}
@Test
void accessTokenCannotRetryExhaustedSoftwareTokenAssociation() {
service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false);
String accessToken = (String) ((Map<?, ?>) passwordLogin().get("AuthenticationResult")).get("AccessToken");
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
Map<String, Object> associated = service.associateSoftwareToken(accessToken, null);
String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant());
String wrongCode = code.equals("000000") ? "000001" : "000000";
for (int attempt = 0; attempt < CognitoTotp.MAX_FAILED_ATTEMPTS; attempt++) {
assertEquals("CodeMismatchException", assertThrows(AwsException.class,
() -> service.verifySoftwareToken(accessToken, null, wrongCode)).getErrorCode());
}
assertEquals("CodeMismatchException", assertThrows(AwsException.class,
() -> service.verifySoftwareToken(accessToken, null, code)).getErrorCode());
}
@Test
void repeatedWrongSignInCodesInvalidateChallengeSession() {
Map<String, Object> associated = service.associateSoftwareToken(null,
(String) passwordLogin().get("Session"));
String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant());
String verifiedSession = (String) service.verifySoftwareToken(null,
(String) associated.get("Session"), code).get("Session");
service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
Map.of("USERNAME", USERNAME));
String session = (String) passwordLogin().get("Session");
String wrongCode = code.equals("000000") ? "000001" : "000000";
for (int attempt = 0; attempt < CognitoTotp.MAX_FAILED_ATTEMPTS; attempt++) {
assertEquals("CodeMismatchException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA", session,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", wrongCode)))
.getErrorCode());
}
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA", session,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code))).getErrorCode());
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA",
(String) passwordLogin().get("Session"),
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code)).get("AuthenticationResult"));
}
@Test
void accessTokenCanAssociateSoftwareTokenWithoutAnAuthSession() {
service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false);
String accessToken = (String) ((Map<?, ?>) passwordLogin().get("AuthenticationResult")).get("AccessToken");
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
Map<String, Object> association = service.associateSoftwareToken(accessToken, null);
assertFalse(association.containsKey("Session"));
String code = CognitoTotp.code((String) association.get("SecretCode"), clock.instant());
Map<String, Object> verified = service.verifySoftwareToken(accessToken, null, code);
assertEquals("SUCCESS", verified.get("Status"));
assertFalse(verified.containsKey("Session"));
assertEquals("SOFTWARE_TOKEN_MFA", passwordLogin().get("ChallengeName"));
}
@Test
void laterAssociationInvalidatesEarlierSecretAndSession() {
String firstLogin = (String) passwordLogin().get("Session");
String secondLogin = (String) passwordLogin().get("Session");
Map<String, Object> first = service.associateSoftwareToken(null, firstLogin);
Map<String, Object> second = service.associateSoftwareToken(null, secondLogin);
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.associateSoftwareToken(null, firstLogin)).getErrorCode());
String firstCode = CognitoTotp.code((String) first.get("SecretCode"), clock.instant());
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.verifySoftwareToken(null, (String) first.get("Session"), firstCode)).getErrorCode());
String secondCode = CognitoTotp.code((String) second.get("SecretCode"), clock.instant());
Map<String, Object> verified = service.verifySoftwareToken(null, (String) second.get("Session"), secondCode);
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP",
(String) verified.get("Session"), Map.of("USERNAME", USERNAME)).get("AuthenticationResult"));
}
@Test
void registeredSecretSurvivesUserSerialization() throws Exception {
String loginSession = (String) passwordLogin().get("Session");
Map<String, Object> associated = service.associateSoftwareToken(null, loginSession);
String secret = (String) associated.get("SecretCode");
String code = CognitoTotp.code(secret, clock.instant());
service.verifySoftwareToken(null, (String) associated.get("Session"), code);
CognitoUser persisted = service.adminGetUser(pool.getId(), USERNAME);
ObjectMapper mapper = new ObjectMapper();
CognitoUser restored = mapper.readValue(mapper.writeValueAsBytes(persisted), CognitoUser.class);
assertEquals(secret, restored.getSoftwareTokenMfaSecret());
assertNull(restored.getPendingSoftwareTokenMfaSecret());
assertTrue(CognitoTotp.validCode(restored.getSoftwareTokenMfaSecret(), code, clock.instant()));
}
@Test
@SuppressWarnings("unchecked")
void successfulSrpProofContinuesToMfaSetupWithoutTokens() throws Exception {
BigInteger privateA = new BigInteger("123456789abcdef123456789abcdef", 16);
BigInteger publicA = CognitoSrpHelper.G.modPow(privateA, CognitoSrpHelper.N);
Map<String, Object> started = service.initiateAuth(client.getClientId(), "USER_SRP_AUTH",
Map.of("USERNAME", USERNAME, "SRP_A", publicA.toString(16)));
assertEquals("PASSWORD_VERIFIER", started.get("ChallengeName"));
Map<String, String> params = (Map<String, String>) started.get("ChallengeParameters");
String timestamp = "Wed Apr 8 12:00:00 UTC 2026";
byte[] sessionKey = clientSrpSessionKey(privateA, publicA,
new BigInteger(params.get("SRP_B"), 16), params.get("SALT"));
byte[] secretBlock = Base64.getDecoder().decode(params.get("SECRET_BLOCK"));
String signature = Base64.getEncoder().encodeToString(CognitoSrpHelper.computeSignature(
sessionKey, pool.getId(), USERNAME, secretBlock, timestamp));
UserPoolClient other = service.createUserPoolClient(pool.getId(), "other-srp-client", false, false,
List.of(), List.of());
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(other.getClientId(), "PASSWORD_VERIFIER",
(String) started.get("Session"), Map.of(
"USERNAME", USERNAME,
"PASSWORD_CLAIM_SECRET_BLOCK", params.get("SECRET_BLOCK"),
"PASSWORD_CLAIM_SIGNATURE", signature,
"TIMESTAMP", timestamp))).getErrorCode());
Map<String, Object> verified = service.respondToAuthChallenge(client.getClientId(),
"PASSWORD_VERIFIER", (String) started.get("Session"), Map.of(
"USERNAME", USERNAME,
"PASSWORD_CLAIM_SECRET_BLOCK", params.get("SECRET_BLOCK"),
"PASSWORD_CLAIM_SIGNATURE", signature,
"TIMESTAMP", timestamp));
assertEquals("MFA_SETUP", verified.get("ChallengeName"));
assertFalse(verified.containsKey("AuthenticationResult"));
}
private byte[] clientSrpSessionKey(BigInteger privateA, BigInteger publicA,
BigInteger publicB, String saltHex) throws Exception {
MessageDigest hash = MessageDigest.getInstance("SHA-256");
hash.update((CognitoSrpHelper.extractPoolName(pool.getId()) + USERNAME + ":" + PASSWORD)
.getBytes(StandardCharsets.UTF_8));
byte[] inner = hash.digest();
hash.update(new BigInteger(saltHex, 16).toByteArray());
BigInteger x = new BigInteger(1, hash.digest(inner));
hash.update(publicA.toByteArray());
BigInteger u = new BigInteger(1, hash.digest(publicB.toByteArray()));
BigInteger base = publicB.subtract(CognitoSrpHelper.K.multiply(
CognitoSrpHelper.G.modPow(x, CognitoSrpHelper.N))).mod(CognitoSrpHelper.N);
BigInteger shared = base.modPow(privateA.add(u.multiply(x)), CognitoSrpHelper.N);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(u.toByteArray(), "HmacSHA256"));
byte[] prk = mac.doFinal(shared.toByteArray());
mac.init(new SecretKeySpec(prk, "HmacSHA256"));
mac.update("Caldera Derived Key".getBytes(StandardCharsets.UTF_8));
mac.update((byte) 1);
return Arrays.copyOf(mac.doFinal(), 16);
}
private Map<String, Object> passwordLogin() {
return service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD));
}
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.cognito;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CognitoTotpTest {
@Test
void usesRfc6238Sha1CounterAndSixDigits() {
String secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
assertEquals("287082", CognitoTotp.code(secret, Instant.ofEpochSecond(59)));
assertTrue(CognitoTotp.validCode(secret, "287082", Instant.ofEpochSecond(59)));
assertTrue(CognitoTotp.validCode(secret, "287082", Instant.ofEpochSecond(89)));
assertFalse(CognitoTotp.validCode(secret, "287082", Instant.ofEpochSecond(90)));
assertFalse(CognitoTotp.validCode(secret, "28782", Instant.ofEpochSecond(59)));
}
@Test
void newSecretIsBase32Encoded() {
String first = CognitoTotp.newSecret();
String second = CognitoTotp.newSecret();
assertTrue(first.matches("[A-Z2-7]{32}"));
assertFalse(first.equals(second));
assertTrue(CognitoTotp.validCode(first, CognitoTotp.code(first, Instant.EPOCH), Instant.EPOCH));
}
}