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 new file mode 100644 index 0000000000..715434e8b5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -0,0 +1,928 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.core.type.TypeReference; +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.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.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Owns Cognito authentication-flow protocol logic: USER_PASSWORD_AUTH, + * USER_SRP_AUTH, REFRESH_TOKEN_AUTH, CUSTOM_AUTH, and challenge responses + * (PASSWORD_VERIFIER, CUSTOM_CHALLENGE, NEW_PASSWORD_REQUIRED). + * + * For CUSTOM_AUTH, dispatches Cognito Lambda triggers + * (DefineAuthChallenge, CreateAuthChallenge, VerifyAuthChallengeResponse). + * When a trigger is not configured (or invocation fails), falls back to a + * deterministic stub: single CUSTOM_CHALLENGE round, accept any non-empty + * answer (or match {@code custom:expectedAuthAnswer} attribute if set). + * + * Calls back into {@link CognitoService} for user/pool lookup and token + * generation. + */ +final class CognitoAuthFlowHandler { + + private static final Logger LOG = Logger.getLogger(CognitoAuthFlowHandler.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final CognitoService service; + private final LambdaService lambdaService; + private final RegionResolver regionResolver; + private final ConcurrentHashMap srpSessions = new ConcurrentHashMap<>(); + private final ConcurrentHashMap customAuthSessions = new ConcurrentHashMap<>(); + + private record SrpSession(String userPoolId, String username, String clientId, + String aHex, String bHex, String bPublicHex, + String secretBlockBase64, Map clientMetadata) {} + + static final class CustomAuthSession { + final String userPoolId; + final String username; + final String clientId; + final List> history = new ArrayList<>(); + Map privateChallengeParameters; + Map clientMetadata = Map.of(); + String currentChallengeName; + + CustomAuthSession(String userPoolId, String username, String clientId) { + this.userPoolId = userPoolId; + this.username = username; + this.clientId = clientId; + } + } + + CognitoAuthFlowHandler(CognitoService service, LambdaService lambdaService, RegionResolver regionResolver) { + this.service = service; + this.lambdaService = lambdaService; + this.regionResolver = regionResolver; + } + + // ──────────────────────────── Public entry points ──────────────────────────── + + Map initiateAuth(String clientId, String authFlow, Map authParameters, + Map clientMetadata) { + UserPoolClient client = service.findClientById(clientId); + UserPool pool = service.describeUserPool(client.getUserPoolId()); + + return switch (authFlow) { + case "USER_PASSWORD_AUTH" -> authenticateWithPassword(pool, client, authParameters, clientMetadata); + case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, client, authParameters, clientMetadata); + case "USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters, clientMetadata); + case "CUSTOM_AUTH" -> handleCustomAuth(pool, client, authParameters, clientMetadata); + default -> { + String username = authParameters.get("USERNAME"); + if (username == null) { + throw new AwsException("InvalidParameterException", "USERNAME is required", 400); + } + CognitoUser user = service.adminGetUser(pool.getId(), username); + Map result = new HashMap<>(); + result.put("AuthenticationResult", + issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata)); + yield result; + } + }; + } + + Map adminInitiateAuth(String userPoolId, String clientId, String authFlow, + Map authParameters, Map clientMetadata) { + UserPoolClient client = service.describeUserPoolClient(userPoolId, clientId); + UserPool pool = service.describeUserPool(userPoolId); + + String username = authParameters.get("USERNAME"); + if (username != null) { + try { + CognitoUser user = service.adminGetUser(userPoolId, username); + if ("RESET_REQUIRED".equals(user.getUserStatus())) { + throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); + } + } catch (AwsException ae) { + if (!"UserNotFoundException".equals(ae.getErrorCode())) throw ae; + // Allow flow to proceed; UserMigration may handle it inside the flow handler. + } + } + + return switch (authFlow) { + case "ADMIN_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH" -> + authenticateWithPassword(pool, client, authParameters, clientMetadata); + case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, client, authParameters, clientMetadata); + case "ADMIN_USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters, clientMetadata); + case "CUSTOM_AUTH" -> handleCustomAuth(pool, client, authParameters, clientMetadata); + default -> { + CognitoUser user = service.adminGetUser(userPoolId, username); + Map result = new HashMap<>(); + result.put("AuthenticationResult", + issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata)); + yield result; + } + }; + } + + Map respondToAuthChallenge(String clientId, String challengeName, String session, + Map responses, Map clientMetadata) { + UserPoolClient client = service.findClientById(clientId); + UserPool pool = service.describeUserPool(client.getUserPoolId()); + + if ("PASSWORD_VERIFIER".equals(challengeName)) { + return handlePasswordVerifierChallenge(pool, client, session, responses, clientMetadata); + } + if ("CUSTOM_CHALLENGE".equals(challengeName)) { + return handleCustomChallenge(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. updates the client provided. + Map attrUpdates = new HashMap<>(); + for (Map.Entry e : responses.entrySet()) { + if (e.getKey() != null && e.getKey().startsWith("userAttributes.")) { + attrUpdates.put(e.getKey().substring("userAttributes.".length()), e.getValue()); + } + } + if (!attrUpdates.isEmpty()) { + 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; + } + throw new AwsException("InvalidParameterException", "Unsupported challenge: " + challengeName, 400); + } + + // ──────────────────────────── USER_PASSWORD / REFRESH ──────────────────────────── + + private Map authenticateWithPassword(UserPool pool, UserPoolClient client, + Map params, Map clientMetadata) { + String username = params.get("USERNAME"); + String password = params.get("PASSWORD"); + if (username == null) throw new AwsException("InvalidParameterException", "USERNAME is required", 400); + if (password == null) throw new AwsException("InvalidParameterException", "PASSWORD is required", 400); + validateSecretHash(client, params, username); + + CognitoUser user; + try { + user = service.adminGetUser(pool.getId(), username); + } catch (AwsException ae) { + if (!"UserNotFoundException".equals(ae.getErrorCode())) throw ae; + user = tryUserMigration(pool, client, username, password, null, clientMetadata, + "UserMigration_Authentication"); + if (user == null) throw ae; + } + + firePreAuthentication(pool, client, user, null, clientMetadata, false); + + if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400); + if ("RESET_REQUIRED".equals(user.getUserStatus())) { + throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); + } + if ("UNCONFIRMED".equals(user.getUserStatus())) { + throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400); + } + if (user.getPasswordHash() == null || !user.getPasswordHash().equals(service.hashPassword(password))) { + throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400); + } + + 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; + } + + private Map handleRefreshToken(UserPool pool, UserPoolClient client, + Map params, Map clientMetadata) { + String refreshToken = params.get("REFRESH_TOKEN"); + if (refreshToken == null) throw new AwsException("InvalidParameterException", "REFRESH_TOKEN is required", 400); + String[] parts = service.parseRefreshToken(refreshToken); + if (parts != null) { + String username = parts[1]; + String tokenClientId = parts[2]; + try { + CognitoUser user = service.adminGetUser(pool.getId(), username); + CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, + clientMetadata, "TokenGeneration_RefreshTokens"); + Map auth = new HashMap<>(); + auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", tokenClientId, override)); + auth.put("IdToken", service.generateSignedJwt(user, pool, "id", tokenClientId, override)); + auth.put("ExpiresIn", 3600); + auth.put("TokenType", "Bearer"); + Map result = new HashMap<>(); + result.put("AuthenticationResult", auth); + return result; + } catch (AwsException ignored) { } + } + Map auth = new HashMap<>(); + auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client.getClientId())); + auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client.getClientId())); + auth.put("ExpiresIn", 3600); + auth.put("TokenType", "Bearer"); + Map result = new HashMap<>(); + result.put("AuthenticationResult", auth); + return result; + } + + private Map buildNewPasswordRequiredChallenge(UserPool pool, UserPoolClient client, CognitoUser user) { + String session = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId()); + Map result = new HashMap<>(); + result.put("ChallengeName", "NEW_PASSWORD_REQUIRED"); + result.put("Session", session); + Map params = new HashMap<>(); + params.put("USER_ID_FOR_SRP", user.getUsername()); + params.put("requiredAttributes", "[]"); + try { + params.put("userAttributes", + new ObjectMapper().writeValueAsString(user.getAttributes() == null ? Map.of() : user.getAttributes())); + } catch (Exception e) { + params.put("userAttributes", "{}"); + } + result.put("ChallengeParameters", params); + return result; + } + + private static String buildSessionToken(String poolId, String username, String clientId) { + String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID(); + return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + } + + private void validateSecretHash(UserPoolClient client, Map params, String username) { + String secret = client.getClientSecret(); + if (secret == null || secret.isBlank()) return; + String provided = params.get("SECRET_HASH"); + if (provided == null || provided.isBlank()) { + throw new AwsException("InvalidParameterException", + "Client " + client.getClientId() + " has a secret; SECRET_HASH is required", 400); + } + String expected; + try { + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(java.nio.charset.StandardCharsets.UTF_8), "HmacSHA256")); + byte[] sig = mac.doFinal((username + client.getClientId()).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + expected = Base64.getEncoder().encodeToString(sig); + } catch (Exception e) { + throw new AwsException("InternalErrorException", "SECRET_HASH computation failed", 500); + } + if (!expected.equals(provided)) { + throw new AwsException("NotAuthorizedException", "SECRET_HASH does not match", 400); + } + } + + // ──────────────────────────── SRP ──────────────────────────── + + private Map handleUserSrpAuth(UserPool pool, UserPoolClient client, + Map authParameters, + Map clientMetadata) { + String username = authParameters.get("USERNAME"); + String aHex = authParameters.get("SRP_A"); + if (username == null || aHex == null) { + throw new AwsException("InvalidParameterException", "USERNAME and SRP_A are required", 400); + } + validateSecretHash(client, authParameters, username); + + CognitoUser user = service.adminGetUser(pool.getId(), username); + firePreAuthentication(pool, client, user, null, clientMetadata, false); + + if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400); + if ("RESET_REQUIRED".equals(user.getUserStatus())) { + throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); + } + if (user.getSrpVerifier() == null) { + throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); + } + + String[] serverB = CognitoSrpHelper.generateServerB(user.getSrpVerifier()); + String bHex = serverB[0]; + String bPublicHex = serverB[1]; + + String sessionToken = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId()); + + byte[] secretBlock = new byte[16]; + new java.security.SecureRandom().nextBytes(secretBlock); + String secretBlockBase64 = Base64.getEncoder().encodeToString(secretBlock); + + srpSessions.put(sessionToken, new SrpSession( + pool.getId(), user.getUsername(), client.getClientId(), + aHex, bHex, bPublicHex, secretBlockBase64, + clientMetadata == null ? Map.of() : clientMetadata)); + + Map result = new HashMap<>(); + result.put("ChallengeName", "PASSWORD_VERIFIER"); + result.put("Session", sessionToken); + result.put("ChallengeParameters", Map.of( + "SALT", user.getSrpSalt(), + "SRP_B", bPublicHex, + "SECRET_BLOCK", secretBlockBase64, + "USER_ID_FOR_SRP", user.getUsername() + )); + return result; + } + + private Map handlePasswordVerifierChallenge(UserPool pool, UserPoolClient client, + String session, Map responses, + Map clientMetadata) { + CustomAuthSession customState = + session == null ? null : customAuthSessions.get(session); + if (customState != null) { + return verifyPasswordWithinCustomAuth(pool, client, session, customState, responses, clientMetadata); + } + + SrpSession srp = srpSessions.get(session); + if (srp == null) throw new AwsException("NotAuthorizedException", "Session not found", 400); + + String username = responses.get("USERNAME"); + String claimSignature = responses.get("PASSWORD_CLAIM_SIGNATURE"); + String timestamp = responses.get("TIMESTAMP"); + if (username == null || claimSignature == null || timestamp == null) { + throw new AwsException("InvalidParameterException", + "USERNAME, PASSWORD_CLAIM_SIGNATURE and TIMESTAMP are required", 400); + } + validateSecretHash(client, responses, username); + + CognitoUser user = service.adminGetUser(pool.getId(), username); + if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400); + if ("RESET_REQUIRED".equals(user.getUserStatus())) { + throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); + } + if (user.getSrpVerifier() == null) { + throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); + } + + byte[] sessionKey = CognitoSrpHelper.computeSessionKey(srp.aHex(), srp.bHex(), srp.bPublicHex(), user.getSrpVerifier()); + 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 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); + } + + Map result = new HashMap<>(); + result.put("AuthenticationResult", + issueTokens(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata)); + return result; + } + + // ──────────────────────────── CUSTOM_AUTH ──────────────────────────── + + private Map handleCustomAuth(UserPool pool, UserPoolClient client, + Map authParameters, + Map clientMetadata) { + String username = authParameters.get("USERNAME"); + if (username == null) throw new AwsException("InvalidParameterException", "USERNAME is required", 400); + + CognitoUser user = service.adminGetUser(pool.getId(), username); + firePreAuthentication(pool, client, user, null, clientMetadata, false); + if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400); + if ("RESET_REQUIRED".equals(user.getUserStatus())) { + throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); + } + + CustomAuthSession state = + new CustomAuthSession(pool.getId(), username, client.getClientId()); + state.clientMetadata = clientMetadata == null ? Map.of() : clientMetadata; + + Map defineResp = defineAuthChallenge(pool, client, user, state); + if (Boolean.TRUE.equals(defineResp.get("failAuthentication"))) { + throw new AwsException("NotAuthorizedException", "Custom auth failed", 400); + } + if (Boolean.TRUE.equals(defineResp.get("issueTokens"))) { + Map result = new HashMap<>(); + result.put("AuthenticationResult", + issueTokens(pool, client, user, "TokenGeneration_Authentication", state.clientMetadata)); + return result; + } + + String challengeName = (String) defineResp.getOrDefault("challengeName", "CUSTOM_CHALLENGE"); + state.currentChallengeName = challengeName; + + Map publicParams = new HashMap<>(); + publicParams.put("USERNAME", username); + for (Map.Entry e : authParameters.entrySet()) { + if (!"USERNAME".equals(e.getKey()) && !"SRP_A".equals(e.getKey())) { + publicParams.putIfAbsent(e.getKey(), e.getValue()); + } + } + applyCreateResponse(state, challengeName, + createAuthChallenge(pool, client, user, state, challengeName), publicParams); + + String sessionToken = buildSessionToken(pool.getId(), username, client.getClientId()); + customAuthSessions.put(sessionToken, state); + + Map result = new HashMap<>(); + result.put("ChallengeName", challengeName); + result.put("Session", sessionToken); + result.put("ChallengeParameters", publicParams); + return result; + } + + private Map handleCustomChallenge(UserPool pool, UserPoolClient client, + String session, Map responses, + Map clientMetadata) { + if (session == null) throw new AwsException("InvalidParameterException", "Session is required", 400); + CustomAuthSession state = customAuthSessions.get(session); + if (state == null) throw new AwsException("NotAuthorizedException", "Session not found", 400); + 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 answer = responses.get("ANSWER"); + if (answer == null) answer = responses.get("custom:ANSWER"); + if (answer == null || answer.isBlank()) { + throw new AwsException("InvalidParameterException", "ANSWER is required", 400); + } + validateSecretHash(client, responses, state.username); + + CognitoUser user = service.adminGetUser(pool.getId(), state.username); + + Boolean answerCorrect = verifyAuthChallenge(pool, client, user, state, answer); + if (answerCorrect == null) { + String expected = user.getAttributes() == null ? null : user.getAttributes().get("custom:expectedAuthAnswer"); + answerCorrect = (expected == null) || expected.equals(answer); + } + if (!state.history.isEmpty()) { + state.history.get(state.history.size() - 1).put("challengeResult", answerCorrect); + } + + Map defineResp = defineAuthChallenge(pool, client, user, state); + if (Boolean.TRUE.equals(defineResp.get("failAuthentication"))) { + customAuthSessions.remove(session); + throw new AwsException("NotAuthorizedException", "Incorrect challenge answer", 400); + } + 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; + } + + String nextChallenge = (String) defineResp.getOrDefault("challengeName", "CUSTOM_CHALLENGE"); + state.currentChallengeName = nextChallenge; + Map publicParams = new HashMap<>(); + publicParams.put("USERNAME", state.username); + applyCreateResponse(state, nextChallenge, + createAuthChallenge(pool, client, user, state, nextChallenge), publicParams); + + String newSession = buildSessionToken(pool.getId(), state.username, client.getClientId()); + customAuthSessions.remove(session); + customAuthSessions.put(newSession, state); + + Map result = new HashMap<>(); + result.put("ChallengeName", nextChallenge); + result.put("Session", newSession); + result.put("ChallengeParameters", publicParams); + return result; + } + + private Map verifyPasswordWithinCustomAuth(UserPool pool, UserPoolClient client, + String session, + CustomAuthSession state, + Map responses, + Map 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"); + if (password == null || password.isBlank()) { + throw new AwsException("InvalidParameterException", "ANSWER (password) is required", 400); + } + + CognitoUser user = service.adminGetUser(pool.getId(), state.username); + boolean passwordOK = user.getPasswordHash() != null + && user.getPasswordHash().equals(service.hashPassword(password)); + if (!state.history.isEmpty()) { + state.history.get(state.history.size() - 1).put("challengeResult", passwordOK); + } + if (!passwordOK) { + customAuthSessions.remove(session); + throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400); + } + + Map defineResp = defineAuthChallenge(pool, client, user, state); + if (Boolean.TRUE.equals(defineResp.get("failAuthentication"))) { + customAuthSessions.remove(session); + throw new AwsException("NotAuthorizedException", "Custom auth failed", 400); + } + 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; + } + + String nextChallenge = (String) defineResp.getOrDefault("challengeName", "CUSTOM_CHALLENGE"); + state.currentChallengeName = nextChallenge; + Map publicParams = new HashMap<>(); + publicParams.put("USERNAME", state.username); + applyCreateResponse(state, nextChallenge, + createAuthChallenge(pool, client, user, state, nextChallenge), publicParams); + + String newSession = buildSessionToken(pool.getId(), state.username, client.getClientId()); + customAuthSessions.remove(session); + customAuthSessions.put(newSession, state); + + Map result = new HashMap<>(); + result.put("ChallengeName", nextChallenge); + result.put("Session", newSession); + result.put("ChallengeParameters", publicParams); + return result; + } + + // ──────────────────────────── CUSTOM_AUTH triggers + helpers ──────────────────────────── + + private Map defineAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user, + CustomAuthSession state) { + Map req = new HashMap<>(); + req.put("session", new ArrayList<>(state.history)); + req.put("userNotFound", false); + req.put("clientMetadata", state.clientMetadata == null ? Map.of() : state.clientMetadata); + Map resp = invokeTrigger(pool, client, user, "DefineAuthChallenge", + "DefineAuthChallenge_Authentication", req).response(); + if (resp != null) return resp; + + Map fallback = new HashMap<>(); + boolean anyCorrect = state.history.stream().anyMatch(h -> Boolean.TRUE.equals(h.get("challengeResult"))); + boolean anyWrong = state.history.stream().anyMatch(h -> Boolean.FALSE.equals(h.get("challengeResult"))); + if (anyCorrect) { + fallback.put("issueTokens", true); + } else if (anyWrong && state.history.size() >= 3) { + fallback.put("failAuthentication", true); + } else { + fallback.put("challengeName", "CUSTOM_CHALLENGE"); + } + return fallback; + } + + private Map createAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user, + CustomAuthSession state, String challengeName) { + Map req = new HashMap<>(); + req.put("challengeName", challengeName); + req.put("session", new ArrayList<>(state.history)); + req.put("clientMetadata", state.clientMetadata == null ? Map.of() : state.clientMetadata); + return invokeTrigger(pool, client, user, "CreateAuthChallenge", + "CreateAuthChallenge_Authentication", req).response(); + } + + private Boolean verifyAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user, + CustomAuthSession state, String answer) { + Map req = new HashMap<>(); + req.put("challengeAnswer", answer); + req.put("privateChallengeParameters", + state.privateChallengeParameters == null ? Map.of() : state.privateChallengeParameters); + req.put("clientMetadata", state.clientMetadata == null ? Map.of() : state.clientMetadata); + Map resp = invokeTrigger(pool, client, user, "VerifyAuthChallengeResponse", + "VerifyAuthChallengeResponse_Authentication", req).response(); + if (resp == null) return null; + Object v = resp.get("answerCorrect"); + return v instanceof Boolean b ? b : null; + } + + private Map applyCreateResponse(CustomAuthSession state, String challengeName, + Map createResp, + Map publicParamsOut) { + if (createResp != null) { + Object pub = createResp.get("publicChallengeParameters"); + Object priv = createResp.get("privateChallengeParameters"); + if (pub instanceof Map pubMap) { + pubMap.forEach((k, v) -> publicParamsOut.put(String.valueOf(k), v == null ? null : String.valueOf(v))); + } + if (priv instanceof Map privMap) { + Map typed = new HashMap<>(); + privMap.forEach((k, v) -> typed.put(String.valueOf(k), v == null ? null : String.valueOf(v))); + state.privateChallengeParameters = typed; + } + } + Map entry = new HashMap<>(); + entry.put("challengeName", challengeName); + if (createResp != null) entry.put("challengeMetadata", createResp.get("challengeMetadata")); + state.history.add(entry); + return entry; + } + + private record TriggerResult(Map response, String errorMessage, boolean configured) { + static TriggerResult notConfigured() { return new TriggerResult(null, null, false); } + static TriggerResult success(Map response) { return new TriggerResult(response, null, true); } + static TriggerResult error(String msg) { return new TriggerResult(null, msg, true); } + boolean errored() { return configured && errorMessage != null; } + } + + @SuppressWarnings("unchecked") + private TriggerResult invokeTrigger(UserPool pool, UserPoolClient client, CognitoUser user, + String triggerKey, String triggerSource, + Map request) { + if (lambdaService == null) return TriggerResult.notConfigured(); + String functionRef = resolveTriggerArn(pool, triggerKey); + if (functionRef == null) return TriggerResult.notConfigured(); + + String region = regionForPool(pool); + + Map event = new HashMap<>(); + event.put("version", "1"); + event.put("region", region); + event.put("userPoolId", pool.getId()); + event.put("userName", user == null ? null : user.getUsername()); + event.put("callerContext", Map.of( + "awsSdkVersion", "floci", + "clientId", client.getClientId())); + event.put("triggerSource", triggerSource); + Map req = new HashMap<>(request); + if (user != null) { + req.put("userAttributes", user.getAttributes() == null ? Map.of() : user.getAttributes()); + } + event.put("request", req); + event.put("response", new HashMap<>()); + + try { + byte[] payload = MAPPER.writeValueAsBytes(event); + InvokeResult result = lambdaService.invoke(region, functionRef, payload, InvocationType.RequestResponse); + if (result.getFunctionError() != null) { + String msg = String.format("trigger %s (%s) returned error: %s", + triggerKey, functionRef, result.getFunctionError()); + LOG.warnv("Cognito {0}", msg); + return TriggerResult.error(msg); + } + if (result.getPayload() == null || result.getPayload().length == 0) { + return TriggerResult.success(Map.of()); + } + Map parsed = MAPPER.readValue(result.getPayload(), new TypeReference<>() {}); + Object response = parsed.get("response"); + Map respMap = response instanceof Map m ? (Map) m : Map.of(); + return TriggerResult.success(respMap); + } catch (AwsException ae) { + LOG.warnv("Cognito trigger {0} not invokable: {1}", triggerKey, ae.getMessage()); + return TriggerResult.error(ae.getMessage()); + } catch (Exception e) { + LOG.warnv(e, "Cognito trigger {0} invocation failed", triggerKey); + return TriggerResult.error(e.getMessage()); + } + } + + // ──────────────────────────── Pre/Post/PreToken/UserMigration ──────────────────────────── + + private void firePreAuthentication(UserPool pool, UserPoolClient client, CognitoUser user, + Map validationData, Map clientMetadata, + boolean userNotFound) { + Map req = new HashMap<>(); + req.put("validationData", validationData == null ? Map.of() : validationData); + req.put("userNotFound", userNotFound); + req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata); + TriggerResult result = invokeTrigger(pool, client, user, + "PreAuthentication", "PreAuthentication_Authentication", req); + if (result.errored()) { + throw new AwsException("NotAuthorizedException", + "PreAuthentication trigger denied authentication: " + result.errorMessage(), 400); + } + } + + private void firePostAuthentication(UserPool pool, UserPoolClient client, CognitoUser user, + Map clientMetadata, boolean newDeviceUsed) { + Map req = new HashMap<>(); + req.put("newDeviceUsed", newDeviceUsed); + req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata); + invokeTrigger(pool, client, user, "PostAuthentication", "PostAuthentication_Authentication", req); + } + + @SuppressWarnings("unchecked") + private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user, + Map clientMetadata, String triggerSource) { + Map req = new HashMap<>(); + req.put("groupConfiguration", buildGroupConfiguration(user)); + req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata); + // V2 lambdas (CognitoEventUserPoolsPreTokenGenV2) require `scopes` to deserialize. + // V1 lambdas tolerate the extra field. + req.put("scopes", List.of()); + TriggerResult result = invokeTrigger(pool, client, user, "PreTokenGeneration", triggerSource, req); + if (!result.configured() || result.errored()) return null; + + Map response = result.response(); + if (response == null) return null; + + // V2 response: claimsAndScopeOverrideDetails { idTokenGeneration, accessTokenGeneration, groupOverrideDetails } + if (response.get("claimsAndScopeOverrideDetails") instanceof Map v2) { + return parseV2Override(v2); + } + // V1 response: claimsOverrideDetails { claimsToAddOrOverride, claimsToSuppress, groupOverrideDetails } + if (response.get("claimsOverrideDetails") instanceof Map v1) { + return parseV1Override(v1); + } + return null; + } + + @SuppressWarnings("unchecked") + private static CognitoService.ClaimsOverride parseV1Override(Map details) { + Map claimsToAddOrOverride = asStringObjectMap(details.get("claimsToAddOrOverride")); + List claimsToSuppress = asStringList(details.get("claimsToSuppress")); + + List groupsToOverride = null; + List iamRolesToOverride = null; + String preferredRole = null; + if (details.get("groupOverrideDetails") instanceof Map g) { + groupsToOverride = asStringList(g.get("groupsToOverride")); + iamRolesToOverride = asStringList(g.get("iamRolesToOverride")); + if (g.get("preferredRole") instanceof String pr) preferredRole = pr; + } + + if (claimsToAddOrOverride == null && claimsToSuppress == null + && groupsToOverride == null && iamRolesToOverride == null && preferredRole == null) { + return null; + } + // V1 applies the same claims map to both id and access tokens. + return new CognitoService.ClaimsOverride( + claimsToAddOrOverride, claimsToSuppress, + claimsToAddOrOverride, claimsToSuppress, + null, null, + groupsToOverride, iamRolesToOverride, preferredRole); + } + + @SuppressWarnings("unchecked") + private static CognitoService.ClaimsOverride parseV2Override(Map details) { + Map idAdd = null; + List idSuppress = null; + Map accessAdd = null; + List accessSuppress = null; + List scopesToAdd = null; + List scopesToSuppress = null; + + if (details.get("idTokenGeneration") instanceof Map id) { + idAdd = asStringObjectMap(id.get("claimsToAddOrOverride")); + idSuppress = asStringList(id.get("claimsToSuppress")); + } + if (details.get("accessTokenGeneration") instanceof Map at) { + accessAdd = asStringObjectMap(at.get("claimsToAddOrOverride")); + accessSuppress = asStringList(at.get("claimsToSuppress")); + scopesToAdd = asStringList(at.get("scopesToAdd")); + scopesToSuppress = asStringList(at.get("scopesToSuppress")); + } + + List groupsToOverride = null; + List iamRolesToOverride = null; + String preferredRole = null; + if (details.get("groupOverrideDetails") instanceof Map g) { + groupsToOverride = asStringList(g.get("groupsToOverride")); + iamRolesToOverride = asStringList(g.get("iamRolesToOverride")); + if (g.get("preferredRole") instanceof String pr) preferredRole = pr; + } + + if (idAdd == null && idSuppress == null && accessAdd == null && accessSuppress == null + && scopesToAdd == null && scopesToSuppress == null + && groupsToOverride == null && iamRolesToOverride == null && preferredRole == null) { + return null; + } + return new CognitoService.ClaimsOverride( + idAdd, idSuppress, accessAdd, accessSuppress, + scopesToAdd, scopesToSuppress, + groupsToOverride, iamRolesToOverride, preferredRole); + } + + private static Map asStringObjectMap(Object o) { + if (!(o instanceof Map m) || m.isEmpty()) return null; + Map out = new LinkedHashMap<>(); + for (Map.Entry e : m.entrySet()) out.put(String.valueOf(e.getKey()), e.getValue()); + return out; + } + + private static List asStringList(Object o) { + if (!(o instanceof List l) || l.isEmpty()) return null; + List out = new ArrayList<>(); + for (Object v : l) out.add(String.valueOf(v)); + return out; + } + + private static Map buildGroupConfiguration(CognitoUser user) { + Map cfg = new HashMap<>(); + cfg.put("groupsToOverride", user.getGroupNames() == null ? List.of() : new ArrayList<>(user.getGroupNames())); + cfg.put("iamRolesToOverride", List.of()); + cfg.put("preferredRole", null); + return cfg; + } + + @SuppressWarnings("unchecked") + private CognitoUser tryUserMigration(UserPool pool, UserPoolClient client, String username, String password, + Map validationData, Map clientMetadata, + String triggerSource) { + if (resolveTriggerArn(pool, "UserMigration") == null) return null; + + Map req = new HashMap<>(); + if (password != null) req.put("password", password); + req.put("validationData", validationData == null ? Map.of() : validationData); + req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata); + req.put("userNotFound", true); + // No user object yet — pass username through the event manually. + Map event = new HashMap<>(); + event.put("version", "1"); + event.put("region", regionForPool(pool)); + event.put("userPoolId", pool.getId()); + event.put("userName", username); + event.put("callerContext", Map.of( + "awsSdkVersion", "floci", + "clientId", client.getClientId())); + event.put("triggerSource", triggerSource); + event.put("request", req); + event.put("response", new HashMap<>()); + + try { + byte[] payload = MAPPER.writeValueAsBytes(event); + InvokeResult result = lambdaService.invoke(regionForPool(pool), + resolveTriggerArn(pool, "UserMigration"), payload, InvocationType.RequestResponse); + if (result.getFunctionError() != null) { + LOG.warnv("UserMigration trigger errored: {0}", result.getFunctionError()); + return null; + } + if (result.getPayload() == null || result.getPayload().length == 0) return null; + + Map parsed = MAPPER.readValue(result.getPayload(), new TypeReference<>() {}); + Object responseObj = parsed.get("response"); + if (!(responseObj instanceof Map response)) return null; + Object attrsObj = response.get("userAttributes"); + if (!(attrsObj instanceof Map attrs) || attrs.isEmpty()) return null; + + Map typedAttrs = new HashMap<>(); + attrs.forEach((k, v) -> { + if (v != null) typedAttrs.put(String.valueOf(k), String.valueOf(v)); + }); + String finalStatus = response.get("finalUserStatus") instanceof String s ? s : "CONFIRMED"; + + service.adminCreateMigratedUser(pool.getId(), username, password, typedAttrs, finalStatus); + return service.adminGetUser(pool.getId(), username); + } catch (Exception e) { + LOG.warnv(e, "UserMigration trigger invocation failed"); + return null; + } + } + + private Map issueTokens(UserPool pool, UserPoolClient client, CognitoUser user, + String triggerSource, Map clientMetadata) { + firePostAuthentication(pool, client, user, clientMetadata, false); + CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource); + return service.generateAuthResult(user, pool, client.getClientId(), override); + } + + CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user) { + return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens"); + } + + private static String resolveTriggerArn(UserPool pool, String triggerKey) { + Map cfg = pool.getLambdaConfig(); + if (cfg == null) return null; + Object v = cfg.get(triggerKey); + if (v instanceof String s && !s.isBlank()) return s; + // V2 form: PreTokenGeneration is configured under "PreTokenGenerationConfig" + // as { LambdaArn, LambdaVersion } (UpdateUserPool / UpdateUserPoolClient + // API). Fall through so callers using the V1 key still work, and pick up + // the V2 ARN when only the V2 key is set. + if ("PreTokenGeneration".equals(triggerKey)) { + Object v2 = cfg.get("PreTokenGenerationConfig"); + if (v2 instanceof Map m) { + Object arn = m.get("LambdaArn"); + if (arn instanceof String s && !s.isBlank()) return s; + } + } + return null; + } + + private String regionForPool(UserPool pool) { + String arn = pool.getArn(); + if (arn != null) { + String[] parts = arn.split(":", 6); + if (parts.length >= 4 && !parts[3].isBlank()) return parts[3]; + } + return regionResolver.getDefaultRegion(); + } +} 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 48dcea2a65..095b3dc097 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 @@ -363,11 +363,14 @@ public class CognitoJsonHandler { private Response handleInitiateAuth(JsonNode request) { Map params = new HashMap<>(); request.path("AuthParameters").fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().asText())); + Map clientMetadata = new HashMap<>(); + request.path("ClientMetadata").fields().forEachRemaining(e -> clientMetadata.put(e.getKey(), e.getValue().asText())); Map result = service.initiateAuth( request.path("ClientId").asText(), request.path("AuthFlow").asText(), - params + params, + clientMetadata ); return Response.ok(objectMapper.valueToTree(result)).build(); } @@ -375,12 +378,15 @@ public class CognitoJsonHandler { private Response handleAdminInitiateAuth(JsonNode request) { Map params = new HashMap<>(); request.path("AuthParameters").fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().asText())); + Map clientMetadata = new HashMap<>(); + request.path("ClientMetadata").fields().forEachRemaining(e -> clientMetadata.put(e.getKey(), e.getValue().asText())); Map result = service.adminInitiateAuth( request.path("UserPoolId").asText(), request.path("ClientId").asText(), request.path("AuthFlow").asText(), - params + params, + clientMetadata ); return Response.ok(objectMapper.valueToTree(result)).build(); } @@ -388,12 +394,15 @@ public class CognitoJsonHandler { private Response handleRespondToAuthChallenge(JsonNode request) { Map responses = new HashMap<>(); request.path("ChallengeResponses").fields().forEachRemaining(e -> responses.put(e.getKey(), e.getValue().asText())); + Map clientMetadata = new HashMap<>(); + request.path("ClientMetadata").fields().forEachRemaining(e -> clientMetadata.put(e.getKey(), e.getValue().asText())); Map result = service.respondToAuthChallenge( request.path("ClientId").asText(), request.path("ChallengeName").asText(), request.path("Session").asText(null), - responses + responses, + clientMetadata ); return Response.ok(objectMapper.valueToTree(result)).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 24e6dc5cbd..c62baed680 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 @@ -1,6 +1,8 @@ package io.github.hectorvent.floci.services.cognito; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -8,6 +10,7 @@ import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.cognito.model.*; +import io.github.hectorvent.floci.services.lambda.LambdaService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -18,14 +21,30 @@ import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; -import java.util.stream.Collectors; @ApplicationScoped public class CognitoService { private static final Logger LOG = Logger.getLogger(CognitoService.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** + * Claim overrides returned by a PreTokenGeneration Lambda trigger. + * + * Supports both V1 (single claims map applied to both id and access tokens) + * and V2 (per-token-type claim overrides + scope changes for the access + * token). For V1 lambdas the parser populates the id/access slots with the + * same map. + */ + public record ClaimsOverride(Map idClaimsToAddOrOverride, + List idClaimsToSuppress, + Map accessClaimsToAddOrOverride, + List accessClaimsToSuppress, + List scopesToAdd, + List scopesToSuppress, + List groupsToOverride, + List iamRolesToOverride, + String preferredRole) {} private final StorageBackend poolStore; private final StorageBackend clientStore; @@ -34,16 +53,13 @@ public class CognitoService { private final StorageBackend groupStore; private final String baseUrl; private final RegionResolver regionResolver; + private final LambdaService lambdaService; // Keyed by session token; contains SRP ephemeral state (bPrivate, B, A, secretBlock) - private final ConcurrentHashMap srpSessions = new ConcurrentHashMap<>(); - - private record SrpSession(String userPoolId, String username, String clientId, - String aHex, String bHex, String bPublicHex, - String secretBlockBase64) {} + private final CognitoAuthFlowHandler authFlowHandler; @Inject - public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig, RegionResolver regionResolver) { + public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig, RegionResolver regionResolver, LambdaService lambdaService) { this.poolStore = storageFactory.create("cognito", "cognito-pools.json", new TypeReference>() {}); this.clientStore = storageFactory.create("cognito", "cognito-clients.json", @@ -56,6 +72,8 @@ public class CognitoService { new TypeReference>() {}); this.baseUrl = trimTrailingSlash(emulatorConfig.baseUrl()); this.regionResolver = regionResolver; + this.lambdaService = lambdaService; + this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver); } CognitoService(StorageBackend poolStore, @@ -64,7 +82,8 @@ public class CognitoService { StorageBackend userStore, StorageBackend groupStore, String baseUrl, - RegionResolver regionResolver) { + RegionResolver regionResolver, + LambdaService lambdaService) { this.poolStore = poolStore; this.clientStore = clientStore; this.resourceServerStore = resourceServerStore; @@ -72,6 +91,8 @@ public class CognitoService { this.groupStore = groupStore; this.baseUrl = baseUrl; this.regionResolver = regionResolver; + this.lambdaService = lambdaService; + this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver); } // ──────────────────────────── User Pools ──────────────────────────── @@ -127,9 +148,7 @@ public class CognitoService { if (request.containsKey("DeviceConfiguration")) pool.setDeviceConfiguration((Map) request.get("DeviceConfiguration")); if (request.containsKey("EmailConfiguration")) pool.setEmailConfiguration((Map) request.get("EmailConfiguration")); if (request.containsKey("SmsConfiguration")) pool.setSmsConfiguration((Map) request.get("SmsConfiguration")); - if (request.containsKey("UserPoolTags")) { - pool.setUserPoolTags(ReservedTags.stripReservedTags((Map) request.get("UserPoolTags"))); - } + if (request.containsKey("UserPoolTags")) pool.setUserPoolTags(ReservedTags.stripReservedTags((Map) request.get("UserPoolTags"))); if (request.containsKey("AdminCreateUserConfig")) pool.setAdminCreateUserConfig((Map) request.get("AdminCreateUserConfig")); if (request.containsKey("UserPoolAddOns")) pool.setUserPoolAddOns((Map) request.get("UserPoolAddOns")); if (request.containsKey("UsernameConfiguration")) pool.setUsernameConfiguration((Map) request.get("UsernameConfiguration")); @@ -447,6 +466,32 @@ public class CognitoService { return user; } + void adminCreateMigratedUser(String userPoolId, String username, String password, + Map attributes, String finalUserStatus) { + describeUserPool(userPoolId); + String key = userKey(userPoolId, username); + + CognitoUser user = userStore.get(key).orElseGet(CognitoUser::new); + user.setUsername(username); + user.setUserPoolId(userPoolId); + if (attributes != null) { + user.getAttributes().putAll(attributes); + } + if (!user.getAttributes().containsKey("sub")) { + user.getAttributes().put("sub", UUID.randomUUID().toString()); + } + if (password != null && !password.isEmpty()) { + updateUserPassword(user, password); + user.setTemporaryPassword(false); + } + user.setUserStatus(finalUserStatus == null ? "CONFIRMED" : finalUserStatus); + user.setEnabled(true); + user.setLastModifiedDate(System.currentTimeMillis() / 1000L); + + userStore.put(key, user); + LOG.infov("Migrated user {0} into pool {1} (status={2})", username, userPoolId, user.getUserStatus()); + } + public void adminUserGlobalSignOut(String userPoolId, String username) { adminGetUser(userPoolId, username); LOG.infov("AdminUserGlobalSignOut stub: user {0} in pool {1} signed out globally", username, userPoolId); @@ -695,188 +740,34 @@ public class CognitoService { // ──────────────────────────── Auth ──────────────────────────── public Map initiateAuth(String clientId, String authFlow, Map authParameters) { - UserPoolClient client = clientStore.get(clientId) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404)); - UserPool pool = describeUserPool(client.getUserPoolId()); + return authFlowHandler.initiateAuth(clientId, authFlow, authParameters, Map.of()); + } - return switch (authFlow) { - case "USER_PASSWORD_AUTH" -> authenticateWithPassword(pool, authParameters, clientId); - case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, authParameters, clientId); - case "USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters); - default -> { - // For other flows, if user exists return tokens - String username = authParameters.get("USERNAME"); - if (username == null) { - throw new AwsException("InvalidParameterException", "USERNAME is required", 400); - } - CognitoUser user = adminGetUser(pool.getId(), username); - Map result = new HashMap<>(); - result.put("AuthenticationResult", generateAuthResult(user, pool, clientId)); - yield result; - } - }; + public Map initiateAuth(String clientId, String authFlow, Map authParameters, + Map clientMetadata) { + return authFlowHandler.initiateAuth(clientId, authFlow, authParameters, clientMetadata); } public Map adminInitiateAuth(String userPoolId, String clientId, String authFlow, Map authParameters) { - UserPoolClient client = describeUserPoolClient(userPoolId, clientId); - UserPool pool = describeUserPool(userPoolId); - - String username = authParameters.get("USERNAME"); - if (username != null) { - CognitoUser user = adminGetUser(userPoolId, username); - if ("RESET_REQUIRED".equals(user.getUserStatus())) { - throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); - } - } - - return switch (authFlow) { - case "ADMIN_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH" -> - authenticateWithPassword(pool, authParameters, clientId); - case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, authParameters, clientId); - case "ADMIN_USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters); - default -> { - CognitoUser user = adminGetUser(userPoolId, username); - Map result = new HashMap<>(); - result.put("AuthenticationResult", generateAuthResult(user, pool, clientId)); - yield result; - } - }; + return authFlowHandler.adminInitiateAuth(userPoolId, clientId, authFlow, authParameters, Map.of()); } - private Map handleUserSrpAuth(UserPool pool, UserPoolClient client, Map authParameters) { - String username = authParameters.get("USERNAME"); - String aHex = authParameters.get("SRP_A"); - - if (username == null || aHex == null) { - throw new AwsException("InvalidParameterException", "USERNAME and SRP_A are required", 400); - } - - CognitoUser user = adminGetUser(pool.getId(), username); - if (!user.isEnabled()) { - throw new AwsException("UserNotConfirmedException", "User is disabled", 400); - } - if ("RESET_REQUIRED".equals(user.getUserStatus())) { - throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); - } - - if (user.getSrpVerifier() == null) { - throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); - } - - String[] serverB = CognitoSrpHelper.generateServerB(user.getSrpVerifier()); - String bHex = serverB[0]; - String bPublicHex = serverB[1]; - - String sessionToken = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId()); - - byte[] secretBlock = new byte[16]; - new java.security.SecureRandom().nextBytes(secretBlock); - String secretBlockBase64 = Base64.getEncoder().encodeToString(secretBlock); - - srpSessions.put(sessionToken, new SrpSession( - pool.getId(), - user.getUsername(), - client.getClientId(), - aHex, - bHex, - bPublicHex, - secretBlockBase64 - )); - - Map result = new HashMap<>(); - result.put("ChallengeName", "PASSWORD_VERIFIER"); - result.put("Session", sessionToken); - result.put("ChallengeParameters", Map.of( - "SALT", user.getSrpSalt(), - "SRP_B", bPublicHex, - "SECRET_BLOCK", secretBlockBase64, - "USER_ID_FOR_SRP", user.getUsername() - )); - return result; - } - - private Map handlePasswordVerifierChallenge(UserPool pool, UserPoolClient client, - String session, Map responses) { - SrpSession srp = srpSessions.get(session); - if (srp == null) { - throw new AwsException("NotAuthorizedException", "Session not found", 400); - } - - String username = responses.get("USERNAME"); - String claimSignature = responses.get("PASSWORD_CLAIM_SIGNATURE"); - String timestamp = responses.get("TIMESTAMP"); - - if (username == null || claimSignature == null || timestamp == null) { - throw new AwsException("InvalidParameterException", "USERNAME, PASSWORD_CLAIM_SIGNATURE and TIMESTAMP are required", 400); - } - - CognitoUser user = adminGetUser(pool.getId(), username); - if (!user.isEnabled()) { - throw new AwsException("UserNotConfirmedException", "User is disabled", 400); - } - if ("RESET_REQUIRED".equals(user.getUserStatus())) { - throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); - } - - if (user.getSrpVerifier() == null) { - throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); - } - - byte[] sessionKey = CognitoSrpHelper.computeSessionKey(srp.aHex(), srp.bHex(), srp.bPublicHex(), user.getSrpVerifier()); - 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); - } - - // Session consumed - srpSessions.remove(session); - - if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { - String newSession = buildSessionToken(pool.getId(), username, client.getClientId()); - Map result = new HashMap<>(); - result.put("ChallengeName", "NEW_PASSWORD_REQUIRED"); - result.put("Session", newSession); - result.put("ChallengeParameters", Map.of( - "USER_ID_FOR_SRP", username, - "requiredAttributes", "[]", - "userAttributes", "{}" - )); - return result; - } - - Map result = new HashMap<>(); - result.put("AuthenticationResult", generateAuthResult(user, pool, client.getClientId())); - return result; + public Map adminInitiateAuth(String userPoolId, String clientId, String authFlow, + Map authParameters, + Map clientMetadata) { + return authFlowHandler.adminInitiateAuth(userPoolId, clientId, authFlow, authParameters, clientMetadata); } public Map respondToAuthChallenge(String clientId, String challengeName, String session, Map responses) { - UserPoolClient client = clientStore.get(clientId) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404)); - UserPool pool = describeUserPool(client.getUserPoolId()); + return authFlowHandler.respondToAuthChallenge(clientId, challengeName, session, responses, Map.of()); + } - if ("PASSWORD_VERIFIER".equals(challengeName)) { - return handlePasswordVerifierChallenge(pool, client, session, responses); - } - - 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); - } - adminSetUserPassword(pool.getId(), username, newPassword, true); - CognitoUser user = adminGetUser(pool.getId(), username); - Map result = new HashMap<>(); - result.put("AuthenticationResult", generateAuthResult(user, pool, clientId)); - return result; - } - - throw new AwsException("InvalidParameterException", "Unsupported challenge: " + challengeName, 400); + public Map respondToAuthChallenge(String clientId, String challengeName, + String session, Map responses, + Map clientMetadata) { + return authFlowHandler.respondToAuthChallenge(clientId, challengeName, session, responses, clientMetadata); } public void changePassword(String accessToken, String previousPassword, String proposedPassword) { @@ -992,83 +883,9 @@ public class CognitoService { // ──────────────────────────── Private helpers ──────────────────────────── - private Map authenticateWithPassword(UserPool pool, Map params, String clientId) { - String username = params.get("USERNAME"); - String password = params.get("PASSWORD"); - if (username == null) { - throw new AwsException("InvalidParameterException", "USERNAME is required", 400); - } - if (password == null) { - throw new AwsException("InvalidParameterException", "PASSWORD is required", 400); - } - - CognitoUser user = adminGetUser(pool.getId(), username); - - if (!user.isEnabled()) { - throw new AwsException("UserNotConfirmedException", "User is disabled", 400); - } - - if ("RESET_REQUIRED".equals(user.getUserStatus())) { - throw new AwsException("PasswordResetRequiredException", "Password reset required", 400); - } - - if ("UNCONFIRMED".equals(user.getUserStatus())) { - throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400); - } - - if (user.getPasswordHash() == null || !user.getPasswordHash().equals(hashPassword(password))) { - throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400); - } - - if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { - // Return a challenge instead of auth tokens - String session = buildSessionToken(pool.getId(), username, clientId); - Map result = new HashMap<>(); - result.put("ChallengeName", "NEW_PASSWORD_REQUIRED"); - result.put("Session", session); - result.put("ChallengeParameters", Map.of( - "USER_ID_FOR_SRP", username, - "requiredAttributes", "[]", - "userAttributes", "{}" - )); - return result; - } - - Map result = new HashMap<>(); - result.put("AuthenticationResult", generateAuthResult(user, pool, clientId)); - return result; - } - - private Map handleRefreshToken(UserPool pool, Map params, String clientId) { - String refreshToken = params.get("REFRESH_TOKEN"); - if (refreshToken == null) { - throw new AwsException("InvalidParameterException", "REFRESH_TOKEN is required", 400); - } - String[] parts = parseRefreshToken(refreshToken); - if (parts != null) { - String username = parts[1]; - String tokenClientId = parts[2]; - try { - CognitoUser user = adminGetUser(pool.getId(), username); - Map auth = new HashMap<>(); - auth.put("AccessToken", generateSignedJwt(user, pool, "access", tokenClientId)); - auth.put("IdToken", generateSignedJwt(user, pool, "id", tokenClientId)); - auth.put("ExpiresIn", 3600); - auth.put("TokenType", "Bearer"); - Map result = new HashMap<>(); - result.put("AuthenticationResult", auth); - return result; - } catch (AwsException ignored) { } - } - // Fallback for legacy tokens: emit minimal tokens using clientId from request - Map auth = new HashMap<>(); - auth.put("AccessToken", generateTokenString("access", "unknown", pool, clientId)); - auth.put("IdToken", generateTokenString("id", "unknown", pool, clientId)); - auth.put("ExpiresIn", 3600); - auth.put("TokenType", "Bearer"); - Map result = new HashMap<>(); - result.put("AuthenticationResult", auth); - return result; + UserPoolClient findClientById(String clientId) { + return clientStore.get(clientId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404)); } public Map getTokensFromRefreshToken(String clientId, String refreshToken) { @@ -1088,9 +905,10 @@ public class CognitoService { } UserPool pool = describeUserPool(poolId); CognitoUser user = adminGetUser(poolId, username); + ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user); Map auth = new HashMap<>(); - auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId)); - auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId)); + auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId, override)); + auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId, override)); auth.put("ExpiresIn", 3600); auth.put("TokenType", "Bearer"); Map result = new HashMap<>(); @@ -1098,53 +916,95 @@ public class CognitoService { return result; } - private Map generateAuthResult(CognitoUser user, UserPool pool, String clientId) { + Map generateAuthResult(CognitoUser user, UserPool pool, String clientId, ClaimsOverride override) { Map auth = new HashMap<>(); - auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId)); - auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId)); + auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId, override)); + auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId, override)); auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), clientId)); auth.put("ExpiresIn", 3600); auth.put("TokenType", "Bearer"); return auth; } - private String generateSignedJwt(CognitoUser user, UserPool pool, String type, String clientId) { + String generateSignedJwt(CognitoUser user, UserPool pool, String type, String clientId, ClaimsOverride override) { + String header = encodeJwtHeader(pool); + long now = System.currentTimeMillis() / 1000L; + + Map claims = new LinkedHashMap<>(); + String sub = user.getAttributes().getOrDefault("sub", user.getUsername()); + String email = user.getAttributes().getOrDefault("email", user.getUsername()); + claims.put("sub", sub); + claims.put("event_id", UUID.randomUUID().toString()); + claims.put("token_use", type); + claims.put("auth_time", now); + claims.put("iss", getIssuer(pool.getId())); + claims.put("exp", now + 3600); + claims.put("iat", now); + claims.put("username", user.getUsername()); + claims.put("email", email); + claims.put("cognito:username", user.getUsername()); + if (clientId != null && !clientId.isBlank()) { + if ("access".equals(type)) claims.put("client_id", clientId); + if ("id".equals(type)) claims.put("aud", clientId); + } + if (!user.getGroupNames().isEmpty()) { + claims.put("cognito:groups", new ArrayList<>(user.getGroupNames())); + } + + applyClaimsOverride(claims, override, type); + + return signJwt(header, encodeJsonBase64Url(claims), getSigningPrivateKey(pool)); + } + + private static void applyClaimsOverride(Map claims, ClaimsOverride override, String tokenType) { + if (override == null) return; + boolean isAccess = "access".equals(tokenType); + List suppress = isAccess ? override.accessClaimsToSuppress() : override.idClaimsToSuppress(); + Map addOrOverride = isAccess ? override.accessClaimsToAddOrOverride() : override.idClaimsToAddOrOverride(); + if (suppress != null) suppress.forEach(claims::remove); + if (addOrOverride != null) claims.putAll(addOrOverride); + if (override.groupsToOverride() != null) { + claims.put("cognito:groups", override.groupsToOverride()); + } + if (override.iamRolesToOverride() != null) { + claims.put("cognito:roles", override.iamRolesToOverride()); + } + if (override.preferredRole() != null) { + claims.put("cognito:preferred_role", override.preferredRole()); + } + // V2 access-token scope mutations. + if (isAccess && (override.scopesToAdd() != null || override.scopesToSuppress() != null)) { + Object existing = claims.get("scope"); + List current = new ArrayList<>(); + if (existing instanceof String s && !s.isBlank()) { + for (String t : s.split(" ")) if (!t.isBlank()) current.add(t); + } + if (override.scopesToSuppress() != null) current.removeAll(override.scopesToSuppress()); + if (override.scopesToAdd() != null) { + for (String s : override.scopesToAdd()) if (!current.contains(s)) current.add(s); + } + if (!current.isEmpty()) claims.put("scope", String.join(" ", current)); + } + } + + private String encodeJwtHeader(UserPool pool) { String headerJson = String.format( "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", escapeJson(getSigningKeyId(pool))); - String header = Base64.getUrlEncoder().withoutPadding() + return Base64.getUrlEncoder().withoutPadding() .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8)); - - long now = System.currentTimeMillis() / 1000L; - String email = user.getAttributes().getOrDefault("email", user.getUsername()); - String groupsFragment = ""; - if (!user.getGroupNames().isEmpty()) { - String groupsJson = user.getGroupNames().stream() - .map(g -> "\"" + escapeJsonString(g) + "\"") - .collect(Collectors.joining(",", "[", "]")); - groupsFragment = ",\"cognito:groups\":" + groupsJson; - } - String sub = user.getAttributes().getOrDefault("sub", user.getUsername()); - String clientIdFragment = (clientId != null && !clientId.isBlank() && "access".equals(type)) - ? ",\"client_id\":\"" + escapeJson(clientId) + "\"" - : ""; - String audFragment = (clientId != null && !clientId.isBlank() && "id".equals(type)) - ? ",\"aud\":\"" + escapeJson(clientId) + "\"" - : ""; - String payloadJson = String.format( - "{\"sub\":\"%s\",\"event_id\":\"%s\",\"token_use\":\"%s\",\"auth_time\":%d," + - "\"iss\":\"%s\",\"exp\":%d,\"iat\":%d," + - "\"username\":\"%s\",\"email\":\"%s\",\"cognito:username\":\"%s\"%s%s%s}", - escapeJson(sub), UUID.randomUUID(), type, now, - escapeJson(getIssuer(pool.getId())), now + 3600, now, - user.getUsername(), email, user.getUsername(), clientIdFragment, audFragment, groupsFragment - ); - String payload = Base64.getUrlEncoder().withoutPadding() - .encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8)); - return signJwt(header, payload, getSigningPrivateKey(pool)); } - private String generateTokenString(String type, String username, UserPool pool, String clientId) { + private static String encodeJsonBase64Url(Map claims) { + try { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(MAPPER.writeValueAsBytes(claims)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Failed to serialize JWT claims", e); + } + } + + String generateTokenString(String type, String username, UserPool pool, String clientId) { long now = System.currentTimeMillis() / 1000L; String headerJson = String.format( "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", @@ -1430,17 +1290,12 @@ public class CognitoService { user.setSrpVerifier(verifierHex); } - private String buildSessionToken(String poolId, String username, String clientId) { - String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID(); - return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); - } - - private String buildRefreshToken(String poolId, String username, String clientId) { + String buildRefreshToken(String poolId, String username, String clientId) { String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID(); return Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); } - private String[] parseRefreshToken(String refreshToken) { + String[] parseRefreshToken(String refreshToken) { try { byte[] decoded = Base64.getDecoder().decode(refreshToken); String raw = new String(decoded, StandardCharsets.UTF_8); @@ -1484,28 +1339,6 @@ public class CognitoService { } } - private String escapeJsonString(String s) { - StringBuilder sb = new StringBuilder(); - for (char c : s.toCharArray()) { - switch (c) { - case '"' -> sb.append("\\\""); - case '\\' -> sb.append("\\\\"); - case '\b' -> sb.append("\\b"); - case '\f' -> sb.append("\\f"); - case '\n' -> sb.append("\\n"); - case '\r' -> sb.append("\\r"); - case '\t' -> sb.append("\\t"); - default -> { - if (c < 0x20) { - sb.append(String.format("\\u%04x", (int) c)); - } else { - sb.append(c); - } - } - } - } - return sb.toString(); - } private String extractJsonField(String json, String field) { String search = "\"" + field + "\":\""; diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java index 4f5c517c76..35a1ec2f66 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java @@ -37,7 +37,8 @@ class CognitoJsonHandlerTest { new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", - regionResolver + regionResolver, + null ); handler = new CognitoJsonHandler(service, mapper); } 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 new file mode 100644 index 0000000000..59df4d969d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -0,0 +1,494 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.core.type.TypeReference; +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.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.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Verifies that Cognito user-pool Lambda triggers fire on the right events with the right + * triggerSource, and that their responses are correctly applied to the auth flow. + */ +class CognitoLambdaTriggersTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private LambdaService lambdaService; + private CognitoService service; + + @BeforeEach + void setUp() { + lambdaService = mock(LambdaService.class); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + service = new CognitoService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + "http://localhost:4566", regionResolver, lambdaService); + } + + private UserPool createPoolWithLambdaConfig(Map lambdaConfig) { + Map req = new HashMap<>(); + req.put("PoolName", "trigger-pool"); + req.put("LambdaConfig", lambdaConfig); + return service.createUserPool(req, "us-east-1"); + } + + private UserPoolClient createClient(UserPool pool) { + return service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of()); + } + + private void seedUser(UserPool pool, String username, String password) { + service.adminCreateUser(pool.getId(), username, + Map.of("email", username + "@example.com"), null); + service.adminSetUserPassword(pool.getId(), username, password, true); + } + + /** Builds a Lambda-style response payload with the given {@code response} block. */ + private static byte[] lambdaPayload(Map response) { + try { + return MAPPER.writeValueAsBytes(Map.of("response", response)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static InvokeResult ok(Map response) { + return new InvokeResult(200, null, lambdaPayload(response), null, "req-id"); + } + + private static InvokeResult lambdaError(String error) { + return new InvokeResult(200, error, new byte[0], null, "req-id"); + } + + private static String decodeJwtPayload(String jwt) { + return new String(Base64.getUrlDecoder().decode(jwt.split("\\.")[1]), StandardCharsets.UTF_8); + } + + // ========================================================================= + // PreAuthentication + // ========================================================================= + + @Test + void preAuthenticationFiresOnUserPasswordAuth() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(ok(Map.of())); + + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + + verify(lambdaService, atLeastOnce()) + .invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void preAuthenticationLambdaErrorBlocksAuthentication() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any())) + .thenReturn(lambdaError("Unhandled")); + + AwsException ex = assertThrows(AwsException.class, () -> + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"))); + assertEquals("NotAuthorizedException", ex.getErrorCode()); + } + + // ========================================================================= + // PostAuthentication + // ========================================================================= + + @Test + void postAuthenticationFiresAfterSuccessfulAuth() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PostAuthentication", "arn:aws:lambda:::post")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any())) + .thenReturn(ok(Map.of())); + + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + + verify(lambdaService, atLeastOnce()) + .invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any()); + } + + @Test + @SuppressWarnings("unchecked") + void postAuthenticationLambdaErrorDoesNotBlockAuth() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PostAuthentication", "arn:aws:lambda:::post")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any())) + .thenReturn(lambdaError("Unhandled")); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + + Map auth = (Map) result.get("AuthenticationResult"); + assertNotNull(auth, "Auth should still succeed when PostAuthentication errors"); + assertNotNull(auth.get("AccessToken")); + } + + // ========================================================================= + // PreTokenGeneration + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationAddsAndOverridesClaims() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + Map claimsOverride = Map.of( + "claimsToAddOrOverride", Map.of( + "tier", "gold", + "email", "override@example.com"), + "claimsToSuppress", List.of("auth_time"), + "groupOverrideDetails", Map.of( + "groupsToOverride", List.of("admins", "managers"))); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsOverrideDetails", claimsOverride))); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String accessToken = (String) ((Map) result.get("AuthenticationResult")).get("AccessToken"); + + Map claims; + try { + claims = MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertEquals("gold", claims.get("tier"), "claimsToAddOrOverride should add 'tier'"); + assertEquals("override@example.com", claims.get("email"), "claimsToAddOrOverride should override 'email'"); + assertNull(claims.get("auth_time"), "claimsToSuppress should drop 'auth_time'"); + assertEquals(List.of("admins", "managers"), claims.get("cognito:groups"), + "groupOverrideDetails.groupsToOverride should replace cognito:groups"); + } + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationFiresOnRefreshTokenFlow() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsOverrideDetails", + Map.of("claimsToAddOrOverride", Map.of("source", "refresh"))))); + + Map initial = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String refreshToken = (String) ((Map) initial.get("AuthenticationResult")).get("RefreshToken"); + + Map refreshResult = service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH", + Map.of("REFRESH_TOKEN", refreshToken)); + String accessToken = (String) ((Map) refreshResult.get("AuthenticationResult")).get("AccessToken"); + + Map claims; + try { + claims = MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertEquals("refresh", claims.get("source")); + } + + // ========================================================================= + // PreTokenGeneration V2 + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationV2AppliesPerTokenClaimsSeparately() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + Map v2 = Map.of( + "claimsAndScopeOverrideDetails", Map.of( + "idTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of("id_only", "yes", "tier", "id-gold"), + "claimsToSuppress", List.of("auth_time")), + "accessTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of("access_only", "yes", "tier", "access-gold")))); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(v2)); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + Map auth = (Map) result.get("AuthenticationResult"); + + Map idClaims; + Map accessClaims; + try { + idClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("IdToken")), new TypeReference<>() {}); + accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + + assertEquals("yes", idClaims.get("id_only")); + assertEquals("id-gold", idClaims.get("tier")); + assertNull(idClaims.get("access_only"), "access-only override must not leak into id token"); + assertNull(idClaims.get("auth_time"), "id-side claimsToSuppress should drop auth_time"); + + assertEquals("yes", accessClaims.get("access_only")); + assertEquals("access-gold", accessClaims.get("tier")); + assertNull(accessClaims.get("id_only"), "id-only override must not leak into access token"); + assertNotNull(accessClaims.get("auth_time"), "access-side did not suppress auth_time"); + } + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationV2AppliesScopeAddAndSuppressToAccessToken() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + Map v2 = Map.of( + "claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of("scope", "openid email phone"), + "scopesToSuppress", List.of("phone"), + "scopesToAdd", List.of("profile", "openid")))); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(v2)); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String accessToken = (String) ((Map) result.get("AuthenticationResult")).get("AccessToken"); + + Map claims; + try { + claims = MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + + String scope = (String) claims.get("scope"); + assertNotNull(scope); + List tokens = List.of(scope.split(" ")); + assertTrue(tokens.contains("openid"), "openid retained (already present; scopesToAdd dedups)"); + assertTrue(tokens.contains("email"), "email retained (not suppressed)"); + assertTrue(tokens.contains("profile"), "profile added by scopesToAdd"); + assertTrue(!tokens.contains("phone"), "phone dropped by scopesToSuppress"); + } + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationV2ResolvesArnFromPreTokenGenerationConfigKey() { + UserPool pool = createPoolWithLambdaConfig(Map.of( + "PreTokenGenerationConfig", Map.of( + "LambdaArn", "arn:aws:lambda:::pre-token-v2", + "LambdaVersion", "V2_0"))); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token-v2"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of("from_v2_config", "ok")))))); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String accessToken = (String) ((Map) result.get("AuthenticationResult")).get("AccessToken"); + + Map claims; + try { + claims = MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertEquals("ok", claims.get("from_v2_config"), + "V2 config object form (PreTokenGenerationConfig.LambdaArn) should resolve trigger ARN"); + verify(lambdaService, atLeastOnce()) + .invoke(anyString(), eq("arn:aws:lambda:::pre-token-v2"), any(byte[].class), any()); + } + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationV2RequestIncludesScopesField() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + org.mockito.ArgumentCaptor payloadCap = org.mockito.ArgumentCaptor.forClass(byte[].class); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any())) + .thenReturn(ok(Map.of())); + + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + + Map event; + try { + event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + Map req = (Map) event.get("request"); + assertNotNull(req.get("scopes"), + "V2 lambdas (CognitoEventUserPoolsPreTokenGenV2) require `scopes` to deserialize"); + assertTrue(req.get("scopes") instanceof List); + assertNotNull(req.get("groupConfiguration")); + assertNotNull(req.get("userAttributes")); + } + + // ========================================================================= + // UserMigration + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void userMigrationCreatesAndAuthenticatesMissingUser() { + UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate")); + UserPoolClient client = createClient(pool); + + Map migrationResp = Map.of( + "userAttributes", Map.of( + "email", "newcomer@example.com", + "email_verified", "true"), + "finalUserStatus", "CONFIRMED", + "messageAction", "SUPPRESS"); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::migrate"), any(byte[].class), any())) + .thenReturn(ok(migrationResp)); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "newcomer", "PASSWORD", "MyPassword1!")); + + Map auth = (Map) result.get("AuthenticationResult"); + assertNotNull(auth, "Migrated user should authenticate successfully"); + assertNotNull(auth.get("AccessToken")); + + CognitoUser user = service.adminGetUser(pool.getId(), "newcomer"); + assertEquals("newcomer@example.com", user.getAttributes().get("email")); + assertEquals("CONFIRMED", user.getUserStatus()); + assertTrue(user.isEnabled()); + } + + @Test + void userMigrationLambdaErrorPropagatesUserNotFound() { + UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate")); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::migrate"), any(byte[].class), any())) + .thenReturn(lambdaError("Unhandled")); + + AwsException ex = assertThrows(AwsException.class, () -> + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "ghost", "PASSWORD", "x"))); + assertEquals("UserNotFoundException", ex.getErrorCode()); + } + + @Test + void userMigrationNotInvokedWhenUserAlreadyExists() { + UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + + verify(lambdaService, never()) + .invoke(anyString(), eq("arn:aws:lambda:::migrate"), any(byte[].class), any()); + } + + // ========================================================================= + // CUSTOM_AUTH triggers (already covered indirectly; check triggerSource wiring) + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void customAuthInvokesDefineAndCreateChallengeTriggers() { + UserPool pool = createPoolWithLambdaConfig(Map.of( + "DefineAuthChallenge", "arn:aws:lambda:::define", + "CreateAuthChallenge", "arn:aws:lambda:::create")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any())) + .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE"))); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any())) + .thenReturn(ok(Map.of( + "publicChallengeParameters", Map.of("question", "favourite-colour"), + "privateChallengeParameters", Map.of("answer", "blue"), + "challengeMetadata", "QA-V1"))); + + Map result = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")); + + assertEquals("CUSTOM_CHALLENGE", result.get("ChallengeName")); + Map params = (Map) result.get("ChallengeParameters"); + assertEquals("favourite-colour", params.get("question"), + "publicChallengeParameters from CreateAuthChallenge should appear in ChallengeParameters"); + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()); + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()); + } + + @Test + @SuppressWarnings("unchecked") + void verifyAuthChallengeLambdaDecidesCorrectness() { + UserPool pool = createPoolWithLambdaConfig(Map.of( + "DefineAuthChallenge", "arn:aws:lambda:::define", + "VerifyAuthChallengeResponse", "arn:aws:lambda:::verify")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + + // First Define call (initiation): present a challenge + // Second Define call (after verify): issue tokens + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any())) + .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE"))) + .thenReturn(ok(Map.of("issueTokens", true))); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any())) + .thenReturn(ok(Map.of("answerCorrect", true))); + + Map initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")); + String session = (String) initResult.get("Session"); + + Map tokens = service.respondToAuthChallenge(client.getClientId(), + "CUSTOM_CHALLENGE", session, + Map.of("USERNAME", "alice", "ANSWER", "anything")); + + assertNotNull(((Map) tokens.get("AuthenticationResult")).get("AccessToken")); + verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index e31259cc3b..1a2c433fb1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -37,7 +37,8 @@ class CognitoServiceTest { new InMemoryStorage<>(), groupStore, "http://localhost:4566", - regionResolver + regionResolver, + null ); } @@ -987,4 +988,212 @@ class CognitoServiceTest { assertThrows(AwsException.class, () -> service.adminEnableUser(pool.getId(), "ghost")); } + + // ========================================================================= + // CUSTOM_AUTH flow (no Lambda triggers — falls back to deterministic stub) + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void customAuthInitiateReturnsCustomChallenge() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + Map result = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice", "CHALLENGE_NAME", "SRP_A")); + + assertEquals("CUSTOM_CHALLENGE", result.get("ChallengeName")); + assertNotNull(result.get("Session")); + Map params = (Map) result.get("ChallengeParameters"); + assertEquals("alice", params.get("USERNAME")); + assertEquals("SRP_A", params.get("CHALLENGE_NAME"), + "InitiateAuth-supplied metadata should pass through to ChallengeParameters"); + } + + @Test + @SuppressWarnings("unchecked") + void customAuthAcceptsAnyAnswerWhenNoExpectedAttribute() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + Map initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")); + String session = (String) initResult.get("Session"); + + Map tokenResult = service.respondToAuthChallenge( + client.getClientId(), "CUSTOM_CHALLENGE", session, + Map.of("USERNAME", "alice", "ANSWER", "any-non-empty-answer")); + + Map auth = (Map) tokenResult.get("AuthenticationResult"); + assertNotNull(auth, "AuthenticationResult should be present after correct answer"); + assertNotNull(auth.get("AccessToken")); + assertNotNull(auth.get("RefreshToken")); + } + + @Test + void customAuthRejectsWhenAnswerDoesNotMatchExpectedAttribute() { + UserPool pool = createPoolAndUser(); + // Stamp an expected answer attribute on the user + service.adminUpdateUserAttributes(pool.getId(), "alice", + Map.of("custom:expectedAuthAnswer", "secret-otp")); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + Map initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")); + String session = (String) initResult.get("Session"); + + // First wrong attempt — flow should request another challenge, not fail outright + Map retryResult = service.respondToAuthChallenge( + client.getClientId(), "CUSTOM_CHALLENGE", session, + Map.of("USERNAME", "alice", "ANSWER", "wrong")); + assertEquals("CUSTOM_CHALLENGE", retryResult.get("ChallengeName")); + String session2 = (String) retryResult.get("Session"); + + // Eventually correct answer issues tokens + @SuppressWarnings("unchecked") + Map tokenResult = service.respondToAuthChallenge( + client.getClientId(), "CUSTOM_CHALLENGE", session2, + Map.of("USERNAME", "alice", "ANSWER", "secret-otp")); + @SuppressWarnings("unchecked") + Map auth = (Map) tokenResult.get("AuthenticationResult"); + assertNotNull(auth); + assertNotNull(auth.get("AccessToken")); + } + + @Test + void customAuthRequiresNonEmptyAnswer() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + Map initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")); + String session = (String) initResult.get("Session"); + + AwsException ex = assertThrows(AwsException.class, () -> + service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session, + Map.of("USERNAME", "alice", "ANSWER", ""))); + assertEquals("InvalidParameterException", ex.getErrorCode()); + } + + @Test + void customChallengeWithUnknownSessionThrows() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", + "not-a-real-session", Map.of("USERNAME", "alice", "ANSWER", "x"))); + assertEquals("NotAuthorizedException", ex.getErrorCode()); + } + + // ========================================================================= + // NEW_PASSWORD_REQUIRED — challenge response shape + userAttributes updates + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void newPasswordRequiredChallengeReturnsUserAttributesJson() { + UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1"); + service.adminCreateUser(pool.getId(), "carol", + Map.of("email", "carol@example.com", "given_name", "Carol"), "TempPass1!"); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "carol", "PASSWORD", "TempPass1!")); + + assertEquals("NEW_PASSWORD_REQUIRED", result.get("ChallengeName")); + Map params = (Map) result.get("ChallengeParameters"); + String userAttrsJson = params.get("userAttributes"); + assertNotNull(userAttrsJson); + assertTrue(userAttrsJson.contains("\"email\":\"carol@example.com\""), + "userAttributes JSON should include user's email; was: " + userAttrsJson); + assertTrue(userAttrsJson.contains("\"given_name\":\"Carol\""), + "userAttributes JSON should include given_name; was: " + userAttrsJson); + } + + @Test + @SuppressWarnings("unchecked") + void newPasswordRequiredAppliesUserAttributeUpdates() { + UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1"); + service.adminCreateUser(pool.getId(), "carol", Map.of("email", "carol@example.com"), "TempPass1!"); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + + Map challengeResp = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "carol", "PASSWORD", "TempPass1!")); + String session = (String) challengeResp.get("Session"); + + Map responses = new HashMap<>(); + responses.put("USERNAME", "carol"); + responses.put("NEW_PASSWORD", "Permanent99!"); + responses.put("userAttributes.given_name", "Carolyn"); + responses.put("userAttributes.family_name", "Smith"); + + Map tokens = service.respondToAuthChallenge( + client.getClientId(), "NEW_PASSWORD_REQUIRED", session, responses); + assertNotNull(((Map) tokens.get("AuthenticationResult")).get("AccessToken")); + + CognitoUser user = service.adminGetUser(pool.getId(), "carol"); + assertEquals("Carolyn", user.getAttributes().get("given_name")); + assertEquals("Smith", user.getAttributes().get("family_name")); + assertEquals("CONFIRMED", user.getUserStatus()); + } + + // ========================================================================= + // SECRET_HASH validation + // ========================================================================= + + @Test + void initiateAuthRejectsMissingSecretHashWhenClientHasSecret() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", true, false, List.of(), List.of()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"))); + assertEquals("InvalidParameterException", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("SECRET_HASH")); + } + + @Test + void initiateAuthRejectsWrongSecretHash() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", true, false, List.of(), List.of()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", + "PASSWORD", "Perm1234!", + "SECRET_HASH", "wrong-hash"))); + assertEquals("NotAuthorizedException", ex.getErrorCode()); + } + + @Test + @SuppressWarnings("unchecked") + void initiateAuthAcceptsCorrectSecretHash() throws Exception { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", true, false, List.of(), List.of()); + + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec( + client.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String secretHash = Base64.getEncoder().encodeToString( + mac.doFinal(("alice" + client.getClientId()).getBytes(StandardCharsets.UTF_8))); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", + "PASSWORD", "Perm1234!", + "SECRET_HASH", secretHash)); + Map auth = (Map) result.get("AuthenticationResult"); + assertNotNull(auth); + assertNotNull(auth.get("AccessToken")); + } }