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

@@ -30,6 +30,7 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
/**
@@ -60,6 +61,7 @@ final class CognitoAuthFlowHandler {
private final Clock clock;
private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CustomAuthToken> customAuthSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TotpSession> totpSessions = new ConcurrentHashMap<>();
private final Object userAuthSessionLock = new Object();
private final LinkedHashMap<String, UserAuthSession> userAuthSessions = new LinkedHashMap<>();
private final LinkedHashMap<String, UserAuthSession> simulatedUserAuthSessions = new LinkedHashMap<>();
@@ -69,6 +71,13 @@ final class CognitoAuthFlowHandler {
String secretBlockBase64, Map<String, String> clientMetadata,
Instant expiresAt) {}
private enum TotpPhase { SETUP, ASSOCIATED, VERIFIED, CODE_REQUIRED }
private record TotpSession(String userPoolId, String username, String clientId,
TotpPhase phase, Map<String, String> clientMetadata,
String triggerSource, Instant expiresAt, String secret,
AtomicInteger failedAttempts) {}
/**
* Correlates a USER_AUTH challenge response back to the InitiateAuth/RespondToAuthChallenge
* call that issued it, the same way {@link SrpSession} and {@link CustomAuthSession} do for
@@ -279,12 +288,148 @@ final class CognitoAuthFlowHandler {
return processChallenge(pool, client, challengeName, session, responses, clientMetadata);
}
Map<String, Object> associateSoftwareToken(String accessToken, String session) {
requireOneTotpCredential(accessToken, session);
String poolId;
String username;
TotpSession state = null;
if (session != null) {
state = requireTotpSession(session, TotpPhase.SETUP);
poolId = state.userPoolId();
username = state.username();
} else {
CognitoService.VerifiedAccessToken token = service.verifyAccessToken(accessToken);
service.requireScope(accessToken, "aws.cognito.signin.user.admin");
poolId = token.poolId();
username = token.username();
}
UserPool pool = service.describeUserPool(poolId);
if (!Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled())) {
throw new AwsException("SoftwareTokenMFANotFoundException",
"Software token MFA is not enabled for this user pool", 400);
}
String secret = CognitoTotp.newSecret();
if (state != null && !totpSessions.remove(session, state)) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
service.beginSoftwareTokenMfa(poolId, username, secret);
Map<String, Object> result = new HashMap<>();
result.put("SecretCode", secret);
if (state != null) {
result.put("Session", issueTotpSession(state.userPoolId(), state.username(), state.clientId(),
TotpPhase.ASSOCIATED, state.clientMetadata(), state.triggerSource(), state.expiresAt(), secret));
}
return result;
}
Map<String, Object> verifySoftwareToken(String accessToken, String session, String userCode) {
requireOneTotpCredential(accessToken, session);
if (userCode == null || !userCode.matches("[0-9]{6}")) {
throw new AwsException("InvalidParameterException", "UserCode must be a six-digit code", 400);
}
String poolId;
String username;
TotpSession state = null;
if (session != null) {
state = requireTotpSession(session, TotpPhase.ASSOCIATED);
poolId = state.userPoolId();
username = state.username();
} else {
CognitoService.VerifiedAccessToken token = service.verifyAccessToken(accessToken);
service.requireScope(accessToken, "aws.cognito.signin.user.admin");
poolId = token.poolId();
username = token.username();
}
if (!service.activateSoftwareTokenMfa(poolId, username, state == null ? null : state.secret(),
userCode, clock.instant())) {
throw new AwsException("CodeMismatchException",
"Invalid verification code provided, please try again.", 400);
}
Map<String, Object> result = new HashMap<>();
result.put("Status", "SUCCESS");
if (state != null) {
totpSessions.remove(session, state);
result.put("Session", issueTotpSession(state.userPoolId(), state.username(), state.clientId(),
TotpPhase.VERIFIED, state.clientMetadata(), state.triggerSource(), state.expiresAt(),
state.secret()));
}
return result;
}
private static void requireOneTotpCredential(String accessToken, String session) {
if ((accessToken == null) == (session == null)) {
throw new AwsException("InvalidParameterException", "Provide either AccessToken or Session", 400);
}
}
private String issueTotpSession(String poolId, String username, String clientId, TotpPhase phase,
Map<String, String> metadata, String triggerSource, Instant expiresAt,
String secret) {
purgeExpired(totpSessions, TotpSession::expiresAt);
String token = buildSessionToken(poolId, username, clientId);
totpSessions.put(token, new TotpSession(poolId, username, clientId, phase, metadata, triggerSource,
expiresAt, secret, new AtomicInteger()));
return token;
}
private TotpSession requireTotpSession(String session, TotpPhase phase) {
TotpSession state = session == null ? null : totpSessions.get(session);
if (state == null || state.phase() != phase) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
if (sessionExpired(state.expiresAt())) {
totpSessions.remove(session, state);
throw sessionExpiredException();
}
return state;
}
private Map<String, Object> handleTotpChallenge(UserPool pool, UserPoolClient client, String challengeName,
String session, Map<String, String> responses,
Map<String, String> clientMetadata) {
TotpPhase phase = "MFA_SETUP".equals(challengeName) ? TotpPhase.VERIFIED : TotpPhase.CODE_REQUIRED;
TotpSession state = requireTotpSession(session, phase);
if (!pool.getId().equals(state.userPoolId()) || !client.getClientId().equals(state.clientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
String username = responses.get("USERNAME");
if (username == null || !username.equals(state.username())) {
throw new AwsException("NotAuthorizedException", "Session does not match user", 400);
}
validateSecretHash(client, responses, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
requireSignInEligible(user);
synchronized (state) {
if (phase == TotpPhase.VERIFIED) {
if (!state.secret().equals(user.getSoftwareTokenMfaSecret())) {
throw new AwsException("NotAuthorizedException", "Software token is not verified", 400);
}
} else if (!state.secret().equals(user.getSoftwareTokenMfaSecret())
|| !CognitoTotp.validCode(state.secret(),
responses.get("SOFTWARE_TOKEN_MFA_CODE"), clock.instant())) {
if (state.failedAttempts().incrementAndGet() >= CognitoTotp.MAX_FAILED_ATTEMPTS) {
totpSessions.remove(session, state);
}
throw new AwsException("CodeMismatchException", "Invalid verification code provided, please try again.", 400);
}
if (!totpSessions.remove(session, state)) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
}
Map<String, String> metadata = clientMetadata != null && !clientMetadata.isEmpty()
? clientMetadata : state.clientMetadata();
return authenticationResult(pool, client, user, state.triggerSource(), metadata);
}
private Map<String, Object> processChallenge(UserPool pool, UserPoolClient client, String challengeName,
String session, Map<String, String> responses,
Map<String, String> clientMetadata) {
if ("PASSWORD_VERIFIER".equals(challengeName)) {
return handlePasswordVerifierChallenge(pool, client, session, responses, clientMetadata);
}
if ("MFA_SETUP".equals(challengeName) || "SOFTWARE_TOKEN_MFA".equals(challengeName)) {
return handleTotpChallenge(pool, client, challengeName, session, responses, clientMetadata);
}
if ("CUSTOM_CHALLENGE".equals(challengeName)) {
return handleCustomChallenge(pool, client, session, responses, clientMetadata);
}
@@ -321,10 +466,7 @@ final class CognitoAuthFlowHandler {
service.adminUpdateUserAttributes(pool.getId(), username, attrUpdates);
}
CognitoUser user = service.adminGetUser(pool.getId(), username);
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult",
issueTokens(pool, client, user, "TokenGeneration_NewPasswordChallenge", clientMetadata));
return result;
return completePrimaryAuth(pool, client, user, "TokenGeneration_NewPasswordChallenge", clientMetadata);
}
throw new AwsException("InvalidParameterException", "Unsupported challenge: " + challengeName, 400);
}
@@ -345,10 +487,7 @@ final class CognitoAuthFlowHandler {
return buildNewPasswordRequiredChallenge(pool, client, user);
}
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult",
issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata));
return result;
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", clientMetadata);
}
/**
@@ -584,6 +723,9 @@ final class CognitoAuthFlowHandler {
srpSessions.remove(session);
throw sessionExpiredException();
}
if (!pool.getId().equals(srp.userPoolId()) || !client.getClientId().equals(srp.clientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
String username = responses.get("USERNAME");
String claimSignature = responses.get("PASSWORD_CLAIM_SIGNATURE");
@@ -592,6 +734,9 @@ final class CognitoAuthFlowHandler {
throw new AwsException("InvalidParameterException",
"USERNAME, PASSWORD_CLAIM_SIGNATURE and TIMESTAMP are required", 400);
}
if (!username.equals(srp.username())) {
throw new AwsException("NotAuthorizedException", "Session does not match user", 400);
}
validateSecretHash(client, responses, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
@@ -620,10 +765,7 @@ final class CognitoAuthFlowHandler {
return buildNewPasswordRequiredChallenge(pool, client, user);
}
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult",
issueTokens(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata));
return result;
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata);
}
// ──────────────────────────── USER_AUTH (choice-based) ────────────────────────────
@@ -760,10 +902,7 @@ final class CognitoAuthFlowHandler {
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
return buildNewPasswordRequiredChallenge(pool, client, user);
}
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult",
issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata));
return result;
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", clientMetadata);
}
/**
@@ -1064,10 +1203,7 @@ final class CognitoAuthFlowHandler {
}
if (Boolean.TRUE.equals(defineResp.get("issueTokens"))) {
customAuthSessions.remove(session);
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult",
issueTokens(pool, client, user, "TokenGeneration_Authentication", state.clientMetadata));
return result;
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", state.clientMetadata);
}
String nextChallenge = (String) defineResp.getOrDefault("challengeName", "CUSTOM_CHALLENGE");
@@ -1534,6 +1670,36 @@ final class CognitoAuthFlowHandler {
}
}
private Map<String, Object> completePrimaryAuth(UserPool pool, UserPoolClient client, CognitoUser user,
String triggerSource, Map<String, String> clientMetadata) {
if (!"ON".equals(pool.getMfaConfiguration())
|| !Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled())) {
return authenticationResult(pool, client, user, triggerSource, clientMetadata);
}
TotpPhase phase = user.getSoftwareTokenMfaSecret() == null
? TotpPhase.SETUP : TotpPhase.CODE_REQUIRED;
String challengeName = phase == TotpPhase.SETUP ? "MFA_SETUP" : "SOFTWARE_TOKEN_MFA";
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", challengeName);
result.put("Session", issueTotpSession(pool.getId(), user.getUsername(), client.getClientId(),
phase, clientMetadata == null ? Map.of() : Map.copyOf(clientMetadata), triggerSource,
sessionExpiry(client, clock.instant()), user.getSoftwareTokenMfaSecret()));
Map<String, String> parameters = new HashMap<>();
parameters.put("USERNAME", user.getUsername());
if (phase == TotpPhase.SETUP) {
parameters.put("MFAS_CAN_SETUP", "[\"SOFTWARE_TOKEN_MFA\"]");
}
result.put("ChallengeParameters", parameters);
return result;
}
private Map<String, Object> authenticationResult(UserPool pool, UserPoolClient client, CognitoUser user,
String triggerSource, Map<String, String> clientMetadata) {
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult", issueTokens(pool, client, user, triggerSource, clientMetadata));
return result;
}
private Map<String, Object> issueTokens(UserPool pool, UserPoolClient client, CognitoUser user,
String triggerSource, Map<String, String> clientMetadata) {
firePostAuthentication(pool, client, user, clientMetadata, false);
@@ -95,6 +95,8 @@ public class CognitoJsonHandler {
case "AdminInitiateAuth" -> handleAdminInitiateAuth(request);
case "RespondToAuthChallenge" -> handleRespondToAuthChallenge(request);
case "AdminRespondToAuthChallenge" -> handleAdminRespondToAuthChallenge(request);
case "AssociateSoftwareToken" -> handleAssociateSoftwareToken(request);
case "VerifySoftwareToken" -> handleVerifySoftwareToken(request);
case "SignUp" -> handleSignUp(request);
case "ConfirmSignUp" -> handleConfirmSignUp(request);
case "ResendConfirmationCode" -> handleResendConfirmationCode(request);
@@ -916,6 +918,19 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.valueToTree(result)).build();
}
private Response handleAssociateSoftwareToken(JsonNode request) {
Map<String, Object> result = service.associateSoftwareToken(
request.path("AccessToken").asText(null), request.path("Session").asText(null));
return Response.ok(objectMapper.valueToTree(result)).build();
}
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));
return Response.ok(objectMapper.valueToTree(result)).build();
}
private Response handleSignUp(JsonNode request) {
Map<String, String> attrs = new HashMap<>();
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
@@ -2943,6 +2943,54 @@ public class CognitoService implements ResourceProvider {
return authFlowHandler.adminRespondToAuthChallenge(userPoolId, clientId, challengeName, session, responses, clientMetadata);
}
public Map<String, Object> associateSoftwareToken(String accessToken, String session) {
return authFlowHandler.associateSoftwareToken(accessToken, session);
}
public Map<String, Object> verifySoftwareToken(String accessToken, String session, String userCode) {
return authFlowHandler.verifySoftwareToken(accessToken, session, userCode);
}
void beginSoftwareTokenMfa(String poolId, String username, String secret) {
synchronized (userLock(poolId, username)) {
CognitoUser user = adminGetUser(poolId, username);
user.setPendingSoftwareTokenMfaSecret(secret);
user.setPendingSoftwareTokenMfaAttemptsRemaining(CognitoTotp.MAX_FAILED_ATTEMPTS);
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(poolId, user.getUsername()), user);
}
}
boolean activateSoftwareTokenMfa(String poolId, String username, String expectedSecret,
String code, Instant now) {
synchronized (userLock(poolId, username)) {
CognitoUser user = adminGetUser(poolId, username);
String pending = user.getPendingSoftwareTokenMfaSecret();
if (pending == null) {
throw new AwsException("InvalidParameterException", "No software token is awaiting verification", 400);
}
if (expectedSecret != null && !expectedSecret.equals(pending)) {
throw new AwsException("NotAuthorizedException", "Software token association has changed", 400);
}
Integer storedAttempts = user.getPendingSoftwareTokenMfaAttemptsRemaining();
int attemptsRemaining = storedAttempts == null ? CognitoTotp.MAX_FAILED_ATTEMPTS : storedAttempts;
if (attemptsRemaining <= 0) {
return false;
}
if (!CognitoTotp.validCode(pending, code, now)) {
user.setPendingSoftwareTokenMfaAttemptsRemaining(attemptsRemaining - 1);
userStore.put(userKey(poolId, user.getUsername()), user);
return false;
}
user.setSoftwareTokenMfaSecret(pending);
user.setPendingSoftwareTokenMfaSecret(null);
user.setPendingSoftwareTokenMfaAttemptsRemaining(null);
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(poolId, user.getUsername()), user);
return true;
}
}
public void changePassword(String accessToken, String previousPassword, String proposedPassword) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
String username = token.username();
@@ -4534,7 +4582,7 @@ public class CognitoService implements ResourceProvider {
* {@link #verifyAccessToken}, which already confirms the token is a valid, unexpired access
* token; this only adds the scope check on top.
*/
private void requireScope(String accessToken, String requiredScope) {
void requireScope(String accessToken, String requiredScope) {
Set<String> scopes = extractScopesFromToken(accessToken);
if (scopes != null && !scopes.contains(requiredScope)) {
throw new AwsException("NotAuthorizedException", "Access Token does not have the required scope", 400);
@@ -0,0 +1,92 @@
package io.github.hectorvent.floci.services.cognito;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
final class CognitoTotp {
// Match verification-code emulation; AWS does not publish an exact attempt threshold.
static final int MAX_FAILED_ATTEMPTS = 5;
private static final char[] BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".toCharArray();
private static final SecureRandom RANDOM = new SecureRandom();
private CognitoTotp() {}
static String newSecret() {
byte[] bytes = new byte[20];
RANDOM.nextBytes(bytes);
StringBuilder encoded = new StringBuilder(32);
int buffer = 0;
int bits = 0;
for (byte value : bytes) {
buffer = (buffer << 8) | (value & 0xff);
bits += 8;
while (bits >= 5) {
encoded.append(BASE32[(buffer >>> (bits - 5)) & 31]);
bits -= 5;
}
}
return encoded.toString();
}
static boolean validCode(String secret, String code, Instant now) {
if (secret == null || code == null || !code.matches("[0-9]{6}")) {
return false;
}
byte[] key = decode(secret);
long step = Math.floorDiv(now.getEpochSecond(), 30);
for (long candidate = step - 1; candidate <= step + 1; candidate++) {
byte[] expected = codeAt(key, candidate).getBytes(StandardCharsets.US_ASCII);
if (MessageDigest.isEqual(expected, code.getBytes(StandardCharsets.US_ASCII))) {
return true;
}
}
return false;
}
static String code(String secret, Instant now) {
return codeAt(decode(secret), Math.floorDiv(now.getEpochSecond(), 30));
}
private static String codeAt(byte[] key, long counter) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(key, "HmacSHA1"));
byte[] digest = mac.doFinal(ByteBuffer.allocate(Long.BYTES).putLong(counter).array());
int offset = digest[digest.length - 1] & 15;
int binary = ((digest[offset] & 127) << 24)
| ((digest[offset + 1] & 255) << 16)
| ((digest[offset + 2] & 255) << 8)
| (digest[offset + 3] & 255);
return String.format(Locale.ROOT, "%06d", binary % 1_000_000);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("TOTP HMAC is unavailable", e);
}
}
private static byte[] decode(String secret) {
byte[] decoded = new byte[secret.length() * 5 / 8];
int buffer = 0;
int bits = 0;
int index = 0;
for (int i = 0; i < secret.length(); i++) {
int value = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(secret.charAt(i));
if (value < 0) {
throw new IllegalArgumentException("Invalid TOTP secret");
}
buffer = (buffer << 5) | value;
bits += 5;
if (bits >= 8) {
decoded[index++] = (byte) (buffer >>> (bits - 8));
bits -= 8;
}
}
return decoded;
}
}
@@ -26,6 +26,9 @@ public class CognitoUser {
private String srpSalt;
private String srpVerifier;
private EmailMfaSettings emailMfaSettings;
private String softwareTokenMfaSecret;
private String pendingSoftwareTokenMfaSecret;
private Integer pendingSoftwareTokenMfaAttemptsRemaining;
private String federatedProviderName;
private String federatedSubject;
@@ -92,6 +95,17 @@ public class CognitoUser {
this.emailMfaSettings = emailMfaSettings;
}
public String getSoftwareTokenMfaSecret() { return softwareTokenMfaSecret; }
public void setSoftwareTokenMfaSecret(String secret) { this.softwareTokenMfaSecret = secret; }
public String getPendingSoftwareTokenMfaSecret() { return pendingSoftwareTokenMfaSecret; }
public void setPendingSoftwareTokenMfaSecret(String secret) { this.pendingSoftwareTokenMfaSecret = secret; }
public Integer getPendingSoftwareTokenMfaAttemptsRemaining() { return pendingSoftwareTokenMfaAttemptsRemaining; }
public void setPendingSoftwareTokenMfaAttemptsRemaining(Integer attempts) {
this.pendingSoftwareTokenMfaAttemptsRemaining = attempts;
}
public String getFederatedProviderName() {
return federatedProviderName;
}