diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoTotpMfaTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoTotpMfaTest.java new file mode 100644 index 0000000000..e3653385cb --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoTotpMfaTest.java @@ -0,0 +1,116 @@ +package com.floci.test; + +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AssociateSoftwareTokenResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.InitiateAuthResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.RespondToAuthChallengeResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolMfaType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.VerifySoftwareTokenResponse; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.ByteBuffer; +import java.time.Instant; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +class CognitoTotpMfaTest { + private static final String USERNAME = "totp-sdk-user"; + private static final String PASSWORD = "SdkTotp123!"; + + @Test + void sdkCompletesSetupAndLaterSoftwareTokenChallenges() throws Exception { + try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) { + CreateUserPoolResponse created = cognito.createUserPool(b -> b + .poolName("totp-sdk-" + UUID.randomUUID())); + String poolId = created.userPool().id(); + try { + cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId) + .mfaConfiguration(UserPoolMfaType.ON) + .softwareTokenMfaConfiguration(m -> m.enabled(true))); + String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId) + .clientName("totp-sdk-client") + .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH)) + .userPoolClient().clientId(); + cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME) + .messageAction(MessageActionType.SUPPRESS)); + cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME) + .password(PASSWORD).permanent(true)); + + InitiateAuthResponse first = passwordLogin(cognito, clientId); + assertThat(first.challengeName()).isEqualTo(ChallengeNameType.MFA_SETUP); + assertThat(first.authenticationResult()).isNull(); + assertThat(first.challengeParameters().get("MFAS_CAN_SETUP")) + .contains("SOFTWARE_TOKEN_MFA"); + + AssociateSoftwareTokenResponse associated = cognito.associateSoftwareToken( + b -> b.session(first.session())); + assertThat(associated.secretCode()).matches("[A-Z2-7]{32}"); + String setupCode = totp(associated.secretCode(), Instant.now()); + VerifySoftwareTokenResponse verified = cognito.verifySoftwareToken(b -> b + .session(associated.session()) + .userCode(setupCode)); + assertThat(verified.statusAsString()).isEqualTo("SUCCESS"); + + RespondToAuthChallengeResponse completed = cognito.respondToAuthChallenge(b -> b + .clientId(clientId).challengeName(ChallengeNameType.MFA_SETUP) + .session(verified.session()) + .challengeResponses(Map.of("USERNAME", USERNAME))); + assertThat(completed.authenticationResult().accessToken()).isNotBlank(); + + InitiateAuthResponse later = passwordLogin(cognito, clientId); + assertThat(later.challengeName()).isEqualTo(ChallengeNameType.SOFTWARE_TOKEN_MFA); + assertThat(later.authenticationResult()).isNull(); + String signInCode = totp(associated.secretCode(), Instant.now()); + RespondToAuthChallengeResponse signedIn = cognito.respondToAuthChallenge(b -> b + .clientId(clientId).challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA) + .session(later.session()) + .challengeResponses(Map.of("USERNAME", USERNAME, + "SOFTWARE_TOKEN_MFA_CODE", signInCode))); + assertThat(signedIn.authenticationResult().accessToken()).isNotBlank(); + } finally { + cognito.deleteUserPool(b -> b.userPoolId(poolId)); + } + } + } + + private static InitiateAuthResponse passwordLogin(CognitoIdentityProviderClient cognito, String clientId) { + return cognito.initiateAuth(b -> b.clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD))); + } + + private static String totp(String secret, Instant now) throws Exception { + byte[] key = new byte[secret.length() * 5 / 8]; + int buffer = 0; + int bits = 0; + int index = 0; + for (int i = 0; i < secret.length(); i++) { + buffer = (buffer << 5) | "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(secret.charAt(i)); + bits += 5; + if (bits >= 8) { + key[index++] = (byte) (buffer >>> (bits - 8)); + bits -= 8; + } + } + Mac mac = Mac.getInstance("HmacSHA1"); + mac.init(new SecretKeySpec(key, "HmacSHA1")); + byte[] digest = mac.doFinal(ByteBuffer.allocate(Long.BYTES) + .putLong(now.getEpochSecond() / 30).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); + } +} diff --git a/docs/services/cognito.md b/docs/services/cognito.md index f542bacbaa..9bb07891d9 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -199,7 +199,21 @@ further divergences, both deliberate: |--------|-------------| | InitiateAuth | Authenticates app-client users through supported user-password and SRP-style flows. | | AdminInitiateAuth | Starts an admin authentication flow for a user pool user. | -| RespondToAuthChallenge | Responds to supported Cognito auth challenges. | +| RespondToAuthChallenge | Responds to supported Cognito auth challenges, including TOTP setup and software-token MFA. | +| AssociateSoftwareToken | Creates a TOTP secret for a user identified by an MFA setup session or access token. | +| VerifySoftwareToken | Verifies the TOTP code and enables the user's software token. | + +With `MfaConfiguration=ON` and software-token MFA enabled, a successful password or SRP +first factor returns `MFA_SETUP` instead of tokens for a user without a verified token. +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. + +This flow currently covers software-token MFA required by a pool. Optional MFA +preferences, SMS/email MFA challenges, and managed-login MFA are not emulated. ### User Listing 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 ef7e7dc1a3..eb0538fd04 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 @@ -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 srpSessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap customAuthSessions = new ConcurrentHashMap<>(); + private final ConcurrentHashMap totpSessions = new ConcurrentHashMap<>(); private final Object userAuthSessionLock = new Object(); private final LinkedHashMap userAuthSessions = new LinkedHashMap<>(); private final LinkedHashMap simulatedUserAuthSessions = new LinkedHashMap<>(); @@ -69,6 +71,13 @@ final class CognitoAuthFlowHandler { String secretBlockBase64, Map clientMetadata, Instant expiresAt) {} + private enum TotpPhase { SETUP, ASSOCIATED, VERIFIED, CODE_REQUIRED } + + private record TotpSession(String userPoolId, String username, String clientId, + TotpPhase phase, Map 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 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 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 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 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 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 handleTotpChallenge(UserPool pool, UserPoolClient client, String challengeName, + String session, Map responses, + Map 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 metadata = clientMetadata != null && !clientMetadata.isEmpty() + ? clientMetadata : state.clientMetadata(); + return authenticationResult(pool, client, user, state.triggerSource(), metadata); + } + private Map processChallenge(UserPool pool, UserPoolClient client, String challengeName, String session, Map responses, Map 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 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 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 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 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 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 completePrimaryAuth(UserPool pool, UserPoolClient client, CognitoUser user, + String triggerSource, Map 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 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 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 authenticationResult(UserPool pool, UserPoolClient client, CognitoUser user, + String triggerSource, Map clientMetadata) { + Map result = new HashMap<>(); + result.put("AuthenticationResult", issueTokens(pool, client, user, triggerSource, clientMetadata)); + return result; + } + private Map issueTokens(UserPool pool, UserPoolClient client, CognitoUser user, String triggerSource, Map clientMetadata) { firePostAuthentication(pool, client, user, clientMetadata, false); 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 4cdf38c8cf..c178a9e264 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 @@ -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 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 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 attrs = new HashMap<>(); request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText())); 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 f53bbcbbe7..3731c157e1 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 @@ -2943,6 +2943,54 @@ public class CognitoService implements ResourceProvider { return authFlowHandler.adminRespondToAuthChallenge(userPoolId, clientId, challengeName, session, responses, clientMetadata); } + public Map associateSoftwareToken(String accessToken, String session) { + return authFlowHandler.associateSoftwareToken(accessToken, session); + } + + public Map 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 scopes = extractScopesFromToken(accessToken); if (scopes != null && !scopes.contains(requiredScope)) { throw new AwsException("NotAuthorizedException", "Access Token does not have the required scope", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java new file mode 100644 index 0000000000..54b243a7fd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java @@ -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; + } +} 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 e765d42785..554f89955f 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 @@ -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; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 5962d97796..d95acfcc97 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -100,6 +100,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.acm.CertificateGenerator - --initialize-at-run-time=io.github.hectorvent.floci.config.TlsConfigSource - --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoSrpHelper + - --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoTotp - --initialize-at-run-time=io.github.hectorvent.floci.services.route53.Route53Service - --initialize-at-run-time=io.github.hectorvent.floci.services.kms.KmsService - --initialize-at-run-time=io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreEventService diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index 8c040a90ac..f7476ffcaa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -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 login = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Temp1234!")); + assertEquals("NEW_PASSWORD_REQUIRED", login.get("ChallengeName")); + Map 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 associated = service.associateSoftwareToken(null, (String) setup.get("Session")); + String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant()); + Map verified = service.verifySoftwareToken(null, (String) associated.get("Session"), code); + Map tokens = service.respondToAuthChallenge(client.getClientId(), + "MFA_SETUP", (String) verified.get("Session"), Map.of("USERNAME", "alice")); + assertNotNull(tokens.get("AuthenticationResult")); + + ArgumentCaptor payload = ArgumentCaptor.forClass(byte[].class); + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payload.capture(), any()); + Map 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 started = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")); + assertEquals("PASSWORD_VERIFIER", started.get("ChallengeName")); + Map 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() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.java new file mode 100644 index 0000000000..7ddd0d7eb5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.java @@ -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); + } +} 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 new file mode 100644 index 0000000000..1d19adb07d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java @@ -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 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 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 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 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 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 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 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 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 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 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 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 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 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 association = service.associateSoftwareToken(accessToken, null); + assertFalse(association.containsKey("Session")); + String code = CognitoTotp.code((String) association.get("SecretCode"), clock.instant()); + Map 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 first = service.associateSoftwareToken(null, firstLogin); + Map 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 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 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 started = service.initiateAuth(client.getClientId(), "USER_SRP_AUTH", + Map.of("USERNAME", USERNAME, "SRP_A", publicA.toString(16))); + assertEquals("PASSWORD_VERIFIER", started.get("ChallengeName")); + Map params = (Map) 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 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 passwordLogin() { + return service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpTest.java new file mode 100644 index 0000000000..47cb2f7895 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpTest.java @@ -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)); + } +}