fix(cognito): verify SRP proofs in custom authentication (#6794)

* fix(cognito): verify SRP proofs in custom authentication

* fix(cognito): include password-change challenge parameters
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-28 07:07:12 -04:00
1 parent 582dba6419
commit da517acc65
6 files changed
+676 -49

No files matched your search

+9
View File
@@ -507,6 +507,15 @@ shortcut is not implemented yet.
Any other `AuthFlow` value is rejected with `InvalidParameterException` and no tokens are issued.
`CUSTOM_AUTH` can start with `CHALLENGE_NAME=SRP_A` and `SRP_A`. Floci seeds the
DefineAuthChallenge history with `SRP_A=true`, issues a real `PASSWORD_VERIFIER` challenge,
and verifies the SRP proof before returning to the trigger's custom challenges. Temporary-password
users complete `NEW_PASSWORD_REQUIRED` within the same custom sequence. Each response must match
the issued session's client, user and challenge; sessions are consumed once. Plain custom
challenges remain supported. `RESET_REQUIRED` still requires password recovery first because
Floci clears the SRP verifier when an administrator resets the password.
See [AWS's custom SRP sequence](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html#user-pool-lambda-challenge-srp-authentication).
The challenge `Session` of a `USER_SRP_AUTH`, `CUSTOM_AUTH` or `USER_AUTH` sign-in is valid for 3 minutes
from when it was issued, the AWS default for the client's `AuthSessionValidity`. Answering the challenge with
an older session fails with `NotAuthorizedException` (`Invalid session for the user, session is expired.`)
@@ -20,6 +20,7 @@ import org.jboss.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
@@ -77,6 +78,7 @@ final class CognitoAuthFlowHandler {
private final LambdaService lambdaService;
private final RegionResolver regionResolver;
private final Clock clock;
private final ConcurrentHashMap<String, PasswordChangeSession> passwordChangeSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CustomAuthToken> customAuthSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TotpSession> totpSessions = new ConcurrentHashMap<>();
@@ -94,6 +96,8 @@ final class CognitoAuthFlowHandler {
String secretBlockBase64, Map<String, String> clientMetadata,
Instant expiresAt) {}
private record PasswordChangeSession(String userPoolId, String username, String clientId, Instant expiresAt) {}
private enum TotpPhase { SETUP, ASSOCIATED, VERIFIED, CODE_REQUIRED }
private record TotpSession(String userPoolId, String username, String clientId,
@@ -127,6 +131,7 @@ final class CognitoAuthFlowHandler {
Map<String, String> privateChallengeParameters;
Map<String, String> clientMetadata = Map.of();
String currentChallengeName;
SrpSession srpSession;
CustomAuthSession(String userPoolId, String username, String clientId) {
this.userPoolId = userPoolId;
@@ -506,28 +511,62 @@ final class CognitoAuthFlowHandler {
return handleWebAuthnChallengeResponse(pool, client, session, responses, clientMetadata);
}
if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) {
String username = responses.get("USERNAME");
String newPassword = responses.get("NEW_PASSWORD");
if (username == null || newPassword == null) {
throw new AwsException("InvalidParameterException", "USERNAME and NEW_PASSWORD are required", 400);
}
service.adminSetUserPassword(pool.getId(), username, newPassword, true);
// Apply any userAttributes.<name> updates the client provided.
Map<String, String> attrUpdates = new HashMap<>();
for (Map.Entry<String, String> e : responses.entrySet()) {
if (e.getKey() != null && e.getKey().startsWith("userAttributes.")) {
attrUpdates.put(e.getKey().substring("userAttributes.".length()), e.getValue());
CustomAuthToken custom = session == null ? null : customAuthSessions.get(session);
if (custom != null) {
CustomAuthSession state = requireCustomSession(pool, client, session, challengeName);
synchronized (state) {
requireCustomSession(pool, client, session, challengeName);
validateCustomUsername(pool, client, state, responses);
changePassword(pool, responses);
consumeCustomSession(session, state);
state.history.get(state.history.size() - 1).put("challengeResult", true);
}
CognitoUser user = applyNewPasswordAttributes(pool, responses);
return continueCustomSrpAuth(pool, client, user, session, state, clientMetadata);
}
if (!attrUpdates.isEmpty()) {
service.adminUpdateUserAttributes(pool.getId(), username, attrUpdates);
PasswordChangeSession pending = session == null ? null : passwordChangeSessions.get(session);
if (pending == null || sessionExpired(pending.expiresAt())
|| !pool.getId().equals(pending.userPoolId()) || !client.getClientId().equals(pending.clientId())
|| !pending.username().equals(responses.get("USERNAME"))) {
throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400);
}
CognitoUser user = service.adminGetUser(pool.getId(), username);
validateSecretHash(client, responses, pending.username());
synchronized (pending) {
if (passwordChangeSessions.get(session) != pending || sessionExpired(pending.expiresAt())) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
changePassword(pool, responses);
passwordChangeSessions.remove(session, pending);
}
CognitoUser user = applyNewPasswordAttributes(pool, responses);
return completePrimaryAuth(pool, client, user, "TokenGeneration_NewPasswordChallenge", clientMetadata);
}
throw new AwsException("InvalidParameterException", "Unsupported challenge: " + challengeName, 400);
}
private void changePassword(UserPool pool, Map<String, String> responses) {
String username = responses.get("USERNAME");
String newPassword = responses.get("NEW_PASSWORD");
if (username == null || newPassword == null) {
throw new AwsException("InvalidParameterException", "USERNAME and NEW_PASSWORD are required", 400);
}
service.adminSetUserPassword(pool.getId(), username, newPassword, true);
}
private CognitoUser applyNewPasswordAttributes(UserPool pool, Map<String, String> responses) {
String username = responses.get("USERNAME");
Map<String, String> attrUpdates = new HashMap<>();
for (Map.Entry<String, String> entry : responses.entrySet()) {
if (entry.getKey() != null && entry.getKey().startsWith("userAttributes.")) {
attrUpdates.put(entry.getKey().substring("userAttributes.".length()), entry.getValue());
}
}
if (!attrUpdates.isEmpty()) {
service.adminUpdateUserAttributes(pool.getId(), username, attrUpdates);
}
return service.adminGetUser(pool.getId(), username);
}
// ──────────────────────────── USER_PASSWORD / REFRESH ────────────────────────────
private Map<String, Object> authenticateWithPassword(UserPool pool, UserPoolClient client,
@@ -735,9 +774,17 @@ final class CognitoAuthFlowHandler {
private Map<String, Object> buildNewPasswordRequiredChallenge(UserPool pool, UserPoolClient client, CognitoUser user) {
String session = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());
purgeExpired(passwordChangeSessions, PasswordChangeSession::expiresAt);
passwordChangeSessions.put(session, new PasswordChangeSession(pool.getId(), user.getUsername(),
client.getClientId(), sessionExpiry(client, clock.instant())));
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", "NEW_PASSWORD_REQUIRED");
result.put("Session", session);
result.put("ChallengeParameters", newPasswordChallengeParameters(user));
return result;
}
private static Map<String, String> newPasswordChallengeParameters(CognitoUser user) {
Map<String, String> params = new HashMap<>();
params.put("USER_ID_FOR_SRP", user.getUsername());
params.put("requiredAttributes", "[]");
@@ -747,8 +794,7 @@ final class CognitoAuthFlowHandler {
} catch (Exception e) {
params.put("userAttributes", "{}");
}
result.put("ChallengeParameters", params);
return result;
return params;
}
private static String buildSessionToken(String poolId, String username, String clientId) {
@@ -818,6 +864,13 @@ final class CognitoAuthFlowHandler {
throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400);
}
return buildSrpChallenge(pool, client, user, aHex, clientMetadata, null);
}
private Map<String, Object> buildSrpChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
String aHex, Map<String, String> clientMetadata,
CustomAuthSession custom) {
validateSrpPublicValue(aHex);
String[] serverB = CognitoSrpHelper.generateServerB(user.getSrpVerifier());
String bHex = serverB[0];
String bPublicHex = serverB[1];
@@ -829,10 +882,17 @@ final class CognitoAuthFlowHandler {
String secretBlockBase64 = Base64.getEncoder().encodeToString(secretBlock);
purgeExpired(srpSessions, SrpSession::expiresAt);
srpSessions.put(sessionToken, new SrpSession(
pool.getId(), user.getUsername(), client.getClientId(),
SrpSession srp = new SrpSession(pool.getId(), user.getUsername(), client.getClientId(),
aHex, bHex, bPublicHex, secretBlockBase64,
clientMetadata == null ? Map.of() : clientMetadata, sessionExpiry(client, clock.instant())));
clientMetadata == null ? Map.of() : clientMetadata, sessionExpiry(client, clock.instant()));
if (custom == null) {
srpSessions.put(sessionToken, srp);
} else {
custom.srpSession = srp;
custom.currentChallengeName = "PASSWORD_VERIFIER";
custom.history.add(new HashMap<>(Map.of("challengeName", "PASSWORD_VERIFIER")));
issueCustomAuthToken(sessionToken, custom, client);
}
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", "PASSWORD_VERIFIER");
@@ -867,6 +927,35 @@ final class CognitoAuthFlowHandler {
srpSessions.remove(session);
throw sessionExpiredException();
}
CognitoUser user = verifySrpProof(pool, client, srp, responses);
Map<String, String> effectiveMetadata = (clientMetadata != null && !clientMetadata.isEmpty())
? clientMetadata : srp.clientMetadata();
srpSessions.remove(session);
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
return buildNewPasswordRequiredChallenge(pool, client, user);
}
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata);
}
private static void validateSrpPublicValue(String aHex) {
if (aHex == null || aHex.isBlank()) {
throw new AwsException("InvalidParameterException", "SRP_A is required", 400);
}
try {
BigInteger publicA = new BigInteger(aHex, 16);
if (publicA.signum() <= 0 || publicA.mod(CognitoSrpHelper.N).signum() == 0) {
throw new NumberFormatException("Invalid SRP public value");
}
} catch (NumberFormatException invalid) {
throw new AwsException("InvalidParameterException", "Invalid SRP_A", 400);
}
}
private CognitoUser verifySrpProof(UserPool pool, UserPoolClient client, SrpSession srp,
Map<String, String> responses) {
if (!pool.getId().equals(srp.userPoolId()) || !client.getClientId().equals(srp.clientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
@@ -893,17 +982,10 @@ final class CognitoAuthFlowHandler {
byte[] secretBlock = Base64.getDecoder().decode(srp.secretBlockBase64());
boolean valid = CognitoSrpHelper.verifySignature(sessionKey, pool.getId(), user.getUsername(),
secretBlock, timestamp, claimSignature);
if (!valid) throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400);
Map<String, String> effectiveMetadata = (clientMetadata != null && !clientMetadata.isEmpty())
? clientMetadata : srp.clientMetadata();
srpSessions.remove(session);
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
return buildNewPasswordRequiredChallenge(pool, client, user);
if (!valid || !srp.secretBlockBase64().equals(responses.get("PASSWORD_CLAIM_SECRET_BLOCK"))) {
throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400);
}
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata);
return user;
}
// ──────────────────────────── USER_AUTH (choice-based) ────────────────────────────
@@ -1399,6 +1481,16 @@ final class CognitoAuthFlowHandler {
CustomAuthSession state =
new CustomAuthSession(pool.getId(), user.getUsername(), client.getClientId());
state.clientMetadata = clientMetadata == null ? Map.of() : clientMetadata;
boolean srpAuth = "SRP_A".equals(authParameters.get("CHALLENGE_NAME"));
if (srpAuth) {
validateSecretHash(client, authParameters, username);
validateSrpPublicValue(authParameters.get("SRP_A"));
requireSignInEligible(user);
if (user.getSrpVerifier() == null) {
throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400);
}
state.history.add(new HashMap<>(Map.of("challengeName", "SRP_A", "challengeResult", true)));
}
Map<String, Object> defineResp = defineAuthChallenge(pool, client, user, state);
if (Boolean.TRUE.equals(defineResp.get("failAuthentication"))) {
@@ -1413,6 +1505,9 @@ final class CognitoAuthFlowHandler {
String challengeName = (String) defineResp.getOrDefault("challengeName", "CUSTOM_CHALLENGE");
state.currentChallengeName = challengeName;
if (srpAuth && "PASSWORD_VERIFIER".equals(challengeName)) {
return buildSrpChallenge(pool, client, user, authParameters.get("SRP_A"), state.clientMetadata, state);
}
Map<String, String> publicParams = new HashMap<>();
publicParams.put("USERNAME", user.getUsername());
@@ -1437,22 +1532,7 @@ final class CognitoAuthFlowHandler {
private Map<String, Object> handleCustomChallenge(UserPool pool, UserPoolClient client,
String session, Map<String, String> responses,
Map<String, String> clientMetadata) {
if (session == null) throw new AwsException("InvalidParameterException", "Session is required", 400);
CustomAuthToken token = customAuthSessions.get(session);
if (token == null) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
if (sessionExpired(token.expiresAt())) {
customAuthSessions.remove(session);
throw sessionExpiredException();
}
CustomAuthSession state = token.state();
if (!state.userPoolId.equals(pool.getId()) || !state.clientId.equals(client.getClientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
if (clientMetadata != null && !clientMetadata.isEmpty()) {
state.clientMetadata = clientMetadata;
}
CustomAuthSession state = requireCustomSession(pool, client, session, "CUSTOM_CHALLENGE");
String answer = responses.get("ANSWER");
if (answer == null) answer = responses.get("custom:ANSWER");
@@ -1468,10 +1548,17 @@ final class CognitoAuthFlowHandler {
throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400);
}
consumeCustomSession(session, state);
if (clientMetadata != null && !clientMetadata.isEmpty()) {
state.clientMetadata = clientMetadata;
}
boolean answerCorrect = verifyAuthChallenge(pool, client, user, state, answer);
if (!state.history.isEmpty()) {
state.history.get(state.history.size() - 1).put("challengeResult", answerCorrect);
}
if (state.srpSession != null) {
return continueCustomSrpAuth(pool, client, user, session, state, clientMetadata);
}
Map<String, Object> defineResp = defineAuthChallenge(pool, client, user, state);
if (Boolean.TRUE.equals(defineResp.get("failAuthentication"))) {
@@ -1509,12 +1596,16 @@ final class CognitoAuthFlowHandler {
CustomAuthSession state,
Map<String, String> responses,
Map<String, String> clientMetadata) {
requireCustomSession(pool, client, session, "PASSWORD_VERIFIER");
if (state.srpSession != null) {
CognitoUser user = verifySrpProof(pool, client, state.srpSession, responses);
consumeCustomSession(session, state);
state.history.get(state.history.size() - 1).put("challengeResult", true);
return continueCustomSrpAuth(pool, client, user, session, state, clientMetadata);
}
if (!state.userPoolId.equals(pool.getId()) || !state.clientId.equals(client.getClientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
if (clientMetadata != null && !clientMetadata.isEmpty()) {
state.clientMetadata = clientMetadata;
}
String password = responses.get("ANSWER");
if (password == null) password = responses.get("PASSWORD_CLAIM_SIGNATURE");
@@ -1525,6 +1616,10 @@ final class CognitoAuthFlowHandler {
CognitoUser user = service.adminGetUser(pool.getId(), state.username);
boolean passwordOK = user.getPasswordHash() != null
&& user.getPasswordHash().equals(service.hashPassword(password));
consumeCustomSession(session, state);
if (clientMetadata != null && !clientMetadata.isEmpty()) {
state.clientMetadata = clientMetadata;
}
if (!state.history.isEmpty()) {
state.history.get(state.history.size() - 1).put("challengeResult", passwordOK);
}
@@ -1561,6 +1656,71 @@ final class CognitoAuthFlowHandler {
return result;
}
private CustomAuthSession requireCustomSession(UserPool pool, UserPoolClient client,
String session, String challengeName) {
CustomAuthToken token = session == null ? null : customAuthSessions.get(session);
if (token == null) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
if (sessionExpired(token.expiresAt())) {
customAuthSessions.remove(session, token);
throw sessionExpiredException();
}
CustomAuthSession state = token.state();
if (!state.userPoolId.equals(pool.getId()) || !state.clientId.equals(client.getClientId())
|| !challengeName.equals(state.currentChallengeName)) {
throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400);
}
return state;
}
private void consumeCustomSession(String session, CustomAuthSession state) {
CustomAuthToken token = customAuthSessions.get(session);
if (token == null || token.state() != state || !customAuthSessions.remove(session, token)) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
}
private void validateCustomUsername(UserPool pool, UserPoolClient client, CustomAuthSession state,
Map<String, String> responses) {
String supplied = responses.get("USERNAME");
if (!state.username.equals(resolveToCanonicalUsername(pool, supplied))) {
throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400);
}
validateSecretHash(client, responses, supplied);
}
private Map<String, Object> continueCustomSrpAuth(UserPool pool, UserPoolClient client, CognitoUser user,
String session, CustomAuthSession state,
Map<String, String> clientMetadata) {
if (clientMetadata != null && !clientMetadata.isEmpty()) {
state.clientMetadata = clientMetadata;
}
Map<String, Object> decision = defineAuthChallenge(pool, client, user, state);
customAuthSessions.remove(session);
if (Boolean.TRUE.equals(decision.get("failAuthentication"))) {
throw new AwsException("NotAuthorizedException", "Custom auth failed", 400);
}
boolean passwordChange = user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus());
if (!passwordChange && Boolean.TRUE.equals(decision.get("issueTokens"))) {
return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", state.clientMetadata);
}
String challengeName = passwordChange ? "NEW_PASSWORD_REQUIRED"
: (String) decision.getOrDefault("challengeName", "CUSTOM_CHALLENGE");
if (!"CUSTOM_CHALLENGE".equals(challengeName) && !"NEW_PASSWORD_REQUIRED".equals(challengeName)) {
throw new AwsException("InvalidLambdaResponseException", "Unexpected custom SRP challenge", 400);
}
state.currentChallengeName = challengeName;
Map<String, String> params = "NEW_PASSWORD_REQUIRED".equals(challengeName)
? newPasswordChallengeParameters(user) : new HashMap<>();
params.put("USERNAME", state.username);
applyCreateResponse(state, challengeName, "CUSTOM_CHALLENGE".equals(challengeName)
? createAuthChallenge(pool, client, user, state, challengeName) : Map.of(), params);
String next = buildSessionToken(pool.getId(), state.username, client.getClientId());
issueCustomAuthToken(next, state, client);
return Map.of("ChallengeName", challengeName, "Session", next, "ChallengeParameters", params);
}
// ──────────────────────────── CUSTOM_AUTH triggers + helpers ────────────────────────────
private Map<String, Object> defineAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
@@ -123,4 +123,60 @@ class CognitoCustomAuthIntegrationTest {
.then().statusCode(200);
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void customSrpProofContinuesToTheCustomChallengeOverTheWire(boolean admin) throws Exception {
String id = UUID.randomUUID().toString();
String define = "arn:aws:lambda:us-east-1:000000000000:function:define-srp-" + id;
String verify = "arn:aws:lambda:us-east-1:000000000000:function:verify-srp-" + id;
String poolId = cognitoJson("CreateUserPool", MAPPER.writeValueAsString(Map.of(
"PoolName", "custom-srp-" + id,
"LambdaConfig", Map.of("DefineAuthChallenge", define, "VerifyAuthChallengeResponse", verify))))
.path("UserPool").path("Id").asText();
try {
String clientId = cognitoJson("CreateUserPoolClient", MAPPER.writeValueAsString(Map.of(
"UserPoolId", poolId, "ClientName", "app", "ExplicitAuthFlows", List.of("ALLOW_CUSTOM_AUTH"))))
.path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", MAPPER.writeValueAsString(Map.of(
"UserPoolId", poolId, "Username", "alice", "MessageAction", "SUPPRESS"))).then().statusCode(200);
cognitoAction("AdminSetUserPassword", MAPPER.writeValueAsString(Map.of("UserPoolId", poolId,
"Username", "alice", "Password", "Perm1234!", "Permanent", true))).then().statusCode(200);
when(lambdaService.invoke(anyString(), eq(define), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(
"response", Map.of("challengeName", "PASSWORD_VERIFIER"))), null, "request"))
.thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(
"response", Map.of("challengeName", "CUSTOM_CHALLENGE"))), null, "request"))
.thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(
"response", Map.of("issueTokens", true))), null, "request"));
when(lambdaService.invoke(anyString(), eq(verify), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(
"response", Map.of("answerCorrect", true))), null, "request"));
Map<String, Object> request = new HashMap<>(Map.of("ClientId", clientId, "AuthFlow", "CUSTOM_AUTH",
"AuthParameters", Map.of("USERNAME", "alice", "CHALLENGE_NAME", "SRP_A",
"SRP_A", CognitoSrpTestClient.publicA())));
if (admin) {
request.put("UserPoolId", poolId);
}
JsonNode started = cognitoJson(admin ? "AdminInitiateAuth" : "InitiateAuth", MAPPER.writeValueAsString(request));
assertEquals("PASSWORD_VERIFIER", started.path("ChallengeName").asText());
Map<?, ?> params = MAPPER.convertValue(started.path("ChallengeParameters"), Map.class);
request.remove("AuthFlow");
request.remove("AuthParameters");
request.put("Session", started.path("Session").asText());
request.put("ChallengeName", "PASSWORD_VERIFIER");
request.put("ChallengeResponses", CognitoSrpTestClient.proof(poolId, "alice", "Perm1234!", params));
String action = admin ? "AdminRespondToAuthChallenge" : "RespondToAuthChallenge";
JsonNode next = cognitoJson(action, MAPPER.writeValueAsString(request));
assertEquals("CUSTOM_CHALLENGE", next.path("ChallengeName").asText());
assertFalse(next.has("AuthenticationResult"));
request.put("Session", next.path("Session").asText());
request.put("ChallengeName", "CUSTOM_CHALLENGE");
request.put("ChallengeResponses", Map.of("USERNAME", "alice", "ANSWER", "blue"));
JsonNode completed = cognitoJson(action, MAPPER.writeValueAsString(request));
assertFalse(completed.path("AuthenticationResult").path("AccessToken").asText().isBlank());
} finally {
cognitoAction("DeleteUserPool", MAPPER.writeValueAsString(Map.of("UserPoolId", poolId))).then().statusCode(200);
}
}
}
@@ -0,0 +1,354 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
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.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class CognitoCustomSrpAuthTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String USERNAME = "alice";
private static final String PASSWORD = "Perm1234!";
private static final String DEFINE = "arn:aws:lambda:us-east-1:000000000000:function:define";
private static final String CREATE = "arn:aws:lambda:us-east-1:000000000000:function:create";
private static final String VERIFY = "arn:aws:lambda:us-east-1:000000000000:function:verify";
private CognitoService service;
private LambdaService lambda;
private MutableClock clock;
private UserPool pool;
private UserPoolClient client;
private final List<JsonNode> histories = new ArrayList<>();
private boolean temporaryPassword;
@BeforeEach
void setUp() throws Exception {
lambda = mock(LambdaService.class);
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"),
lambda, mock(AcmService.class), null, null, null, clock);
pool = service.createUserPool(Map.of("PoolName", "CustomSrp",
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 8)), "LambdaConfig", Map.of(
"DefineAuthChallenge", DEFINE, "CreateAuthChallenge", CREATE,
"VerifyAuthChallengeResponse", VERIFY)), "us-east-1");
service.adminCreateUser(pool.getId(), USERNAME, Map.of(), null);
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, true);
client = service.createUserPoolClient(pool.getId(), "app", false, false, List.of(), List.of());
client.setExplicitAuthFlows(List.of("ALLOW_CUSTOM_AUTH"));
when(lambda.invoke(anyString(), eq(DEFINE), any(byte[].class), any())).thenAnswer(call -> {
JsonNode history = MAPPER.readTree((byte[]) call.getArgument(2)).path("request").path("session");
histories.add(history);
String last = history.isEmpty() ? "" : history.get(history.size() - 1).path("challengeName").asText();
if ("SRP_A".equals(last)) {
return ok(Map.of("challengeName", "PASSWORD_VERIFIER"));
}
if ("PASSWORD_VERIFIER".equals(last) && temporaryPassword) {
return ok(Map.of("challengeName", "NEW_PASSWORD_REQUIRED"));
}
if ("CUSTOM_CHALLENGE".equals(last)) {
return ok(Map.of("issueTokens", true));
}
return ok(Map.of("challengeName", "CUSTOM_CHALLENGE"));
});
when(lambda.invoke(anyString(), eq(CREATE), any(byte[].class), any())).thenReturn(ok(Map.of(
"publicChallengeParameters", Map.of("question", "colour"),
"privateChallengeParameters", Map.of("answer", "blue"))));
when(lambda.invoke(anyString(), eq(VERIFY), any(byte[].class), any())).thenReturn(ok(Map.of("answerCorrect", true)));
}
@ParameterizedTest
@CsvSource({"false,false", "true,false", "false,true", "true,true"})
void srpProofPrecedesCustomChallengesAndTokens(boolean admin, boolean temporary) throws Exception {
temporaryPassword = temporary;
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, !temporary);
Map<String, Object> started = start(admin);
verify(lambda, never()).invoke(anyString(), eq(CREATE), any(byte[].class), any());
Map<String, String> proof = proof(started);
Map<String, Object> next = respond(admin, client.getClientId(), "PASSWORD_VERIFIER", started, proof);
assertFalse(next.containsKey("AuthenticationResult"));
assertNotEquals(started.get("Session"), next.get("Session"));
assertDenied(() -> respond(admin, client.getClientId(), "PASSWORD_VERIFIER", started, proof));
if (temporary) {
assertEquals("NEW_PASSWORD_REQUIRED", next.get("ChallengeName"));
Map<?, ?> params = (Map<?, ?>) next.get("ChallengeParameters");
assertEquals(USERNAME, params.get("USER_ID_FOR_SRP"));
assertTrue(MAPPER.readTree((String) params.get("requiredAttributes")).isArray());
assertTrue(MAPPER.readTree((String) params.get("userAttributes")).isObject());
Map<String, Object> passwordChallenge = next;
next = respond(admin, client.getClientId(), "NEW_PASSWORD_REQUIRED", next,
Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "NewPerm1234!"));
assertFalse(next.containsKey("AuthenticationResult"));
assertDenied(() -> respond(admin, client.getClientId(), "NEW_PASSWORD_REQUIRED", passwordChallenge,
Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "Another1234!")));
}
assertEquals("CUSTOM_CHALLENGE", next.get("ChallengeName"));
Map<String, Object> completed = respond(admin, client.getClientId(), "CUSTOM_CHALLENGE", next,
Map.of("USERNAME", USERNAME, "ANSWER", "blue"));
assertNotNull(((Map<?, ?>) completed.get("AuthenticationResult")).get("AccessToken"));
JsonNode history = histories.get(histories.size() - 1);
List<String> expected = temporary
? List.of("SRP_A", "PASSWORD_VERIFIER", "NEW_PASSWORD_REQUIRED", "CUSTOM_CHALLENGE")
: List.of("SRP_A", "PASSWORD_VERIFIER", "CUSTOM_CHALLENGE");
assertEquals(expected.size(), history.size());
for (int i = 0; i < expected.size(); i++) {
assertEquals(expected.get(i), history.get(i).path("challengeName").asText());
assertTrue(history.get(i).path("challengeResult").asBoolean());
}
verify(lambda, times(1)).invoke(anyString(), eq(CREATE), any(byte[].class), any());
}
@ParameterizedTest
@ValueSource(strings = {"signature", "username", "client", "phase", "expired", "plaintext", "block", "missing-block"})
void invalidOrMisboundProofCannotAdvanceTheFlow(String failure) throws Exception {
Map<String, Object> started = start(false);
Map<String, String> proof = new HashMap<>(proof(started));
String respondingClient = client.getClientId();
String challenge = "PASSWORD_VERIFIER";
switch (failure) {
case "signature" -> proof.put("PASSWORD_CLAIM_SIGNATURE", Base64.getEncoder().encodeToString(new byte[32]));
case "username" -> proof.put("USERNAME", "someone-else");
case "client" -> respondingClient = service.createUserPoolClient(pool.getId(), "other", false, false,
List.of(), List.of()).getClientId();
case "phase" -> { challenge = "CUSTOM_CHALLENGE"; proof.put("ANSWER", "blue"); }
case "expired" -> clock.advance(Duration.ofMinutes(4));
case "plaintext" -> proof.put("PASSWORD_CLAIM_SIGNATURE", PASSWORD);
case "block" -> proof.put("PASSWORD_CLAIM_SECRET_BLOCK", "substituted");
case "missing-block" -> proof.remove("PASSWORD_CLAIM_SECRET_BLOCK");
default -> fail("Unknown case");
}
String targetClient = respondingClient;
String targetChallenge = challenge;
assertDenied(() -> respond(false, targetClient, targetChallenge, started, proof));
assertEquals(1, histories.size());
verify(lambda, never()).invoke(anyString(), eq(VERIFY), any(byte[].class), any());
}
@Test
void srpSessionCannotBeAnsweredWithAPlainPassword() {
Map<String, Object> started = start(false);
AwsException error = assertThrows(AwsException.class, () -> respond(false, client.getClientId(),
"PASSWORD_VERIFIER", started, Map.of("USERNAME", USERNAME, "ANSWER", PASSWORD)));
assertEquals("InvalidParameterException", error.getErrorCode());
assertEquals(1, histories.size());
}
@ParameterizedTest
@ValueSource(strings = {"0", "N", "not-hex", "-1"})
void invalidPublicValueIsRejectedBeforeStartingTheCustomSequence(String value) {
String publicValue = "N".equals(value) ? CognitoSrpHelper.N.toString(16) : value;
AwsException error = assertThrows(AwsException.class, () -> service.initiateAuth(client.getClientId(),
"CUSTOM_AUTH", Map.of("USERNAME", USERNAME, "CHALLENGE_NAME", "SRP_A", "SRP_A", publicValue)));
assertEquals("InvalidParameterException", error.getErrorCode());
assertTrue(histories.isEmpty());
}
@ParameterizedTest
@ValueSource(strings = {"phase", "expired", "consumed", "unknown"})
void passwordChangeCannotBypassTheCustomSequence(String failure) throws Exception {
Map<String, Object> started = start(false);
if ("expired".equals(failure)) {
clock.advance(Duration.ofMinutes(4));
} else if ("consumed".equals(failure)) {
respond(false, client.getClientId(), "PASSWORD_VERIFIER", started, proof(started));
} else if ("unknown".equals(failure)) {
started = Map.of("Session", "unknown-session");
}
Map<String, Object> previous = started;
assertDenied(() -> respond(false, client.getClientId(), "NEW_PASSWORD_REQUIRED", previous,
Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "Bypass1234!")));
}
@ParameterizedTest
@ValueSource(strings = {"username", "client", "expired"})
void passwordChangeIsBoundToTheVerifiedCustomUserAndClient(String failure) throws Exception {
temporaryPassword = true;
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, false);
Map<String, Object> started = start(false);
Map<String, Object> passwordChallenge = respond(false, client.getClientId(), "PASSWORD_VERIFIER", started, proof(started));
String originalHash = service.adminGetUser(pool.getId(), USERNAME).getPasswordHash();
String target = "client".equals(failure) ? service.createUserPoolClient(pool.getId(), "other", false, false,
List.of(), List.of()).getClientId() : client.getClientId();
if ("expired".equals(failure)) {
clock.advance(Duration.ofMinutes(4));
}
Map<String, String> response = Map.of("USERNAME", "username".equals(failure) ? "someone-else" : USERNAME,
"NEW_PASSWORD", "Bypass1234!");
assertDenied(() -> respond(false, target, "NEW_PASSWORD_REQUIRED", passwordChallenge, response));
assertEquals(originalHash, service.adminGetUser(pool.getId(), USERNAME).getPasswordHash());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void explicitlyRequestedSrpRequiresThePublicValue(boolean admin) {
Map<String, String> params = Map.of("USERNAME", USERNAME, "CHALLENGE_NAME", "SRP_A");
AwsException error = assertThrows(AwsException.class, () -> {
if (admin) {
service.adminInitiateAuth(pool.getId(), client.getClientId(), "CUSTOM_AUTH", params, Map.of());
} else {
service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", params);
}
});
assertEquals("InvalidParameterException", error.getErrorCode());
assertTrue(histories.isEmpty());
}
@ParameterizedTest
@CsvSource({"false,missing", "false,weak", "true,missing", "true,weak"})
void rejectedNewPasswordCanBeCorrectedOnTheSameSession(boolean custom, String invalid) throws Exception {
temporaryPassword = true;
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, false);
Map<String, Object> challenge;
if (custom) {
Map<String, Object> started = start(false);
challenge = respond(false, client.getClientId(), "PASSWORD_VERIFIER", started, proof(started));
} else {
client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH"));
challenge = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD));
}
Map<String, String> bad = new HashMap<>(Map.of("USERNAME", USERNAME));
if ("weak".equals(invalid)) {
bad.put("NEW_PASSWORD", "x");
}
assertThrows(AwsException.class, () -> respond(false, client.getClientId(), "NEW_PASSWORD_REQUIRED", challenge, bad));
Map<String, Object> next = respond(false, client.getClientId(), "NEW_PASSWORD_REQUIRED", challenge,
Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "Corrected1234!"));
if (custom) {
assertEquals("CUSTOM_CHALLENGE", next.get("ChallengeName"));
assertFalse(next.containsKey("AuthenticationResult"));
} else {
assertNotNull(next.get("AuthenticationResult"));
}
}
@Test
void rejectedCustomResponseDoesNotReplaceClientMetadata() throws Exception {
Map<String, Object> started = start(false);
Map<String, Object> next = service.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER",
(String) started.get("Session"), proof(started), Map.of("trace", "original"));
assertDenied(() -> service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE",
(String) next.get("Session"), Map.of("USERNAME", "someone-else", "ANSWER", "blue"),
Map.of("trace", "rejected")));
respond(false, client.getClientId(), "CUSTOM_CHALLENGE", next, Map.of("USERNAME", USERNAME, "ANSWER", "blue"));
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(lambda).invoke(anyString(), eq(VERIFY), payload.capture(), any());
assertEquals("original", MAPPER.readTree(payload.getValue()).path("request").path("clientMetadata").path("trace").asText());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void attributeFailureAfterPasswordChangeDoesNotLeaveTheSessionReusable(boolean custom) throws Exception {
temporaryPassword = true;
pool.setUsernameAttributes(List.of("email"));
service.adminCreateUser(pool.getId(), "occupied@example.com", Map.of("email", "occupied@example.com"), null);
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, false);
Map<String, Object> challenge;
if (custom) {
Map<String, Object> started = start(false);
challenge = respond(false, client.getClientId(), "PASSWORD_VERIFIER", started, proof(started));
} else {
client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH"));
challenge = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD));
}
String before = service.adminGetUser(pool.getId(), USERNAME).getPasswordHash();
AwsException failure = assertThrows(AwsException.class, () -> respond(false, client.getClientId(),
"NEW_PASSWORD_REQUIRED", challenge, Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "Changed1234!",
"userAttributes.email", "occupied@example.com")));
assertEquals("AliasExistsException", failure.getErrorCode());
assertNotEquals(before, service.adminGetUser(pool.getId(), USERNAME).getPasswordHash());
assertDenied(() -> respond(false, client.getClientId(), "NEW_PASSWORD_REQUIRED", challenge,
Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "Reused1234!")));
}
@Test
void simultaneousProofResponsesAdvanceOnlyOnce() throws Exception {
Map<String, Object> started = start(false);
Map<String, String> proof = proof(started);
CountDownLatch defining = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(1);
when(lambda.invoke(anyString(), eq(DEFINE), any(byte[].class), any())).thenAnswer(call -> {
defining.countDown();
assertTrue(finish.await(5, TimeUnit.SECONDS));
return ok(Map.of("challengeName", "CUSTOM_CHALLENGE"));
});
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Map<String, Object>> first = executor.submit(() -> respond(false, client.getClientId(),
"PASSWORD_VERIFIER", started, proof));
try {
assertTrue(defining.await(5, TimeUnit.SECONDS));
assertDenied(() -> respond(false, client.getClientId(), "PASSWORD_VERIFIER", started, proof));
} finally {
finish.countDown();
}
assertEquals("CUSTOM_CHALLENGE", first.get(5, TimeUnit.SECONDS).get("ChallengeName"));
}
verify(lambda, times(2)).invoke(anyString(), eq(DEFINE), any(byte[].class), any());
}
private Map<String, Object> start(boolean admin) {
Map<String, String> params = Map.of("USERNAME", USERNAME, "CHALLENGE_NAME", "SRP_A",
"SRP_A", CognitoSrpTestClient.publicA());
Map<String, Object> started = admin
? service.adminInitiateAuth(pool.getId(), client.getClientId(), "CUSTOM_AUTH", params, Map.of())
: service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", params);
assertEquals("PASSWORD_VERIFIER", started.get("ChallengeName"));
assertFalse(started.containsKey("AuthenticationResult"));
Map<?, ?> challenge = (Map<?, ?>) started.get("ChallengeParameters");
for (String member : List.of("USER_ID_FOR_SRP", "USERNAME", "SALT", "SRP_B", "SECRET_BLOCK")) {
assertNotNull(challenge.get(member));
}
return started;
}
private Map<String, Object> respond(boolean admin, String clientId, String challenge,
Map<String, Object> previous, Map<String, String> responses) {
String session = (String) previous.get("Session");
return admin ? service.adminRespondToAuthChallenge(pool.getId(), clientId, challenge, session, responses, Map.of())
: service.respondToAuthChallenge(clientId, challenge, session, responses);
}
private static void assertDenied(Runnable operation) {
assertEquals("NotAuthorizedException", assertThrows(AwsException.class, operation::run).getErrorCode());
}
private static InvokeResult ok(Map<String, Object> response) throws Exception {
return new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of("response", response)), null, "request");
}
private Map<String, String> proof(Map<String, Object> started) throws Exception {
return CognitoSrpTestClient.proof(pool.getId(), USERNAME, PASSWORD, (Map<?, ?>) started.get("ChallengeParameters"));
}
}
@@ -5373,7 +5373,7 @@ class CognitoServiceTest {
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
Map.of("USERNAME", "alice", "CHALLENGE_NAME", "SRP_A")));
Map.of("USERNAME", "alice", "CHALLENGE_NAME", "SRP_A", "SRP_A", "ABCDEF1234567890")));
assertEquals("InvalidUserPoolConfigurationException", ex.getErrorCode());
}
@@ -0,0 +1,48 @@
package io.github.hectorvent.floci.services.cognito;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
/** A client-side password proof; it uses only the challenge's public values. */
final class CognitoSrpTestClient {
private static final BigInteger PRIVATE_A = new BigInteger("123456789abcdef123456789abcdef", 16);
private static final BigInteger PUBLIC_A = CognitoSrpHelper.G.modPow(PRIVATE_A, CognitoSrpHelper.N);
private CognitoSrpTestClient() {}
static String publicA() {
return PUBLIC_A.toString(16);
}
static Map<String, String> proof(String poolId, String username, String password, Map<?, ?> params) throws Exception {
String salt = (String) params.get("SALT");
BigInteger publicB = new BigInteger((String) params.get("SRP_B"), 16);
MessageDigest hash = MessageDigest.getInstance("SHA-256");
byte[] inner = hash.digest((CognitoSrpHelper.extractPoolName(poolId) + username + ":" + password)
.getBytes(StandardCharsets.UTF_8));
hash.update(new BigInteger(salt, 16).toByteArray());
BigInteger x = new BigInteger(1, hash.digest(inner));
hash.update(PUBLIC_A.toByteArray());
BigInteger u = new BigInteger(1, hash.digest(publicB.toByteArray()));
BigInteger shared = publicB.subtract(CognitoSrpHelper.K.multiply(CognitoSrpHelper.G.modPow(x, CognitoSrpHelper.N)))
.mod(CognitoSrpHelper.N).modPow(PRIVATE_A.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);
byte[] key = Arrays.copyOf(mac.doFinal(), 16);
String timestamp = "Wed Apr 8 12:00:00 UTC 2026";
return Map.of("USERNAME", username, "TIMESTAMP", timestamp,
"PASSWORD_CLAIM_SECRET_BLOCK", (String) params.get("SECRET_BLOCK"),
"PASSWORD_CLAIM_SIGNATURE", Base64.getEncoder().encodeToString(CognitoSrpHelper.computeSignature(key,
poolId, username, Base64.getDecoder().decode((String) params.get("SECRET_BLOCK")), timestamp)));
}
}