From 537e04248258934b68ccb504108252d5086eea6c Mon Sep 17 00:00:00 2001 From: Mohith Date: Tue, 3 Nov 2026 20:04:39 +0530 Subject: [PATCH] feat(cognito): support AdminListUserAuthEvents (#7404) Record SignIn events for USER_PASSWORD_AUTH, ADMIN_USER_PASSWORD_AUTH, ADMIN_NO_SRP_AUTH and USER_SRP_AUTH on pools with the Plus feature plan and threat protection in AUDIT or ENFORCED mode, and list them newest first with MaxResults and NextToken paging. Other pools get UserPoolAddOnNotEnabledException. A wrong password is Fail, a sign-in interrupted by a challenge stays InProgress until it ends in tokens, and no EventRisk is reported since Floci performs no risk evaluation. Events are matched to their pool and user by the stored owner, not the key prefix alone, and a sign-in that ends after its user is deleted records nothing. Closes #6137 --- .../CognitoAdminListUserAuthEventsTest.java | 171 +++++++ docs/services/cognito.md | 1 + docs/services/index.md | 2 +- .../cognito/CognitoAuthFlowHandler.java | 144 ++++-- .../services/cognito/CognitoJsonHandler.java | 9 + .../services/cognito/CognitoService.java | 214 +++++++++ .../cognito/model/CognitoAuthEvent.java | 76 +++ ...dminListUserAuthEventsIntegrationTest.java | 447 ++++++++++++++++++ .../cognito/CognitoAuthEventsServiceTest.java | 251 ++++++++++ 9 files changed, 1263 insertions(+), 52 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoAdminListUserAuthEventsTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthEvent.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAdminListUserAuthEventsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthEventsServiceTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoAdminListUserAuthEventsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoAdminListUserAuthEventsTest.java new file mode 100644 index 0000000000..08a9361a71 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoAdminListUserAuthEventsTest.java @@ -0,0 +1,171 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminListUserAuthEventsResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AdvancedSecurityModeType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthEventType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeName; +import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeResponse; +import software.amazon.awssdk.services.cognitoidentityprovider.model.EventResponseType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.EventType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.NotAuthorizedException; +import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolAddOnNotEnabledException; +import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolTierType; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * AdminListUserAuthEvents must deserialize through the typed SDK model: strict SDKs reject a + * wrong timestamp or enum shape, which the AWS CLI would coerce silently. + */ +@DisplayName("Cognito IDP: AdminListUserAuthEvents") +class CognitoAdminListUserAuthEventsTest { + + private static final String PASSWORD = "CompatPass1!"; + + private static CognitoIdentityProviderClient cognito; + private static String plusPoolId; + private static String essentialsPoolId; + private static String username; + + @BeforeAll + static void setup() { + cognito = TestFixtures.cognitoClient(); + + plusPoolId = cognito.createUserPool(b -> b + .poolName(TestFixtures.uniqueName("compat-auth-events-plus")) + .userPoolTier(UserPoolTierType.PLUS) + .userPoolAddOns(a -> a.advancedSecurityMode(AdvancedSecurityModeType.AUDIT))) + .userPool().id(); + String clientId = cognito.createUserPoolClient(b -> b + .userPoolId(plusPoolId) + .clientName("compat-auth-events-client") + .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH, + ExplicitAuthFlowsType.ALLOW_REFRESH_TOKEN_AUTH)) + .userPoolClient().clientId(); + + username = TestFixtures.uniqueName("auth-events-user"); + cognito.adminCreateUser(b -> b + .userPoolId(plusPoolId) + .username(username) + .messageAction(MessageActionType.SUPPRESS)); + cognito.adminSetUserPassword(b -> b + .userPoolId(plusPoolId) + .username(username) + .password(PASSWORD) + .permanent(true)); + + assertThatThrownBy(() -> cognito.initiateAuth(b -> b + .clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", username, "PASSWORD", "WrongPass1!")))) + .isInstanceOf(NotAuthorizedException.class); + cognito.initiateAuth(b -> b + .clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD))); + + essentialsPoolId = cognito.createUserPool(b -> b + .poolName(TestFixtures.uniqueName("compat-auth-events-essentials"))) + .userPool().id(); + cognito.adminCreateUser(b -> b + .userPoolId(essentialsPoolId) + .username(username) + .messageAction(MessageActionType.SUPPRESS)); + } + + @AfterAll + static void cleanup() { + if (cognito != null) { + deletePoolQuietly(plusPoolId); + deletePoolQuietly(essentialsPoolId); + cognito.close(); + } + } + + @Test + @DisplayName("lists a failed and a successful sign-in, newest first, through the typed model") + void listsSignInEventsNewestFirst() { + AdminListUserAuthEventsResponse response = cognito.adminListUserAuthEvents(b -> b + .userPoolId(plusPoolId) + .username(username)); + + List events = response.authEvents(); + assertThat(events).hasSize(2); + assertThat(events).allSatisfy(event -> { + assertThat(event.eventType()).isEqualTo(EventType.SIGN_IN); + assertThat(event.eventId()).isNotBlank(); + assertThat(event.creationDate()).isInstanceOf(Instant.class).isNotNull(); + assertThat(event.eventRisk()).isNull(); + }); + + AuthEventType newest = events.get(0); + AuthEventType oldest = events.get(1); + assertThat(newest.eventResponse()).isEqualTo(EventResponseType.PASS); + assertThat(oldest.eventResponse()).isEqualTo(EventResponseType.FAIL); + assertThat(newest.creationDate()).isAfterOrEqualTo(oldest.creationDate()); + + assertThat(newest.challengeResponses()).anySatisfy(c -> { + assertThat(c.challengeName()).isEqualTo(ChallengeName.PASSWORD); + assertThat(c.challengeResponse()).isEqualTo(ChallengeResponse.SUCCESS); + }); + assertThat(oldest.challengeResponses()).anySatisfy(c -> { + assertThat(c.challengeName()).isEqualTo(ChallengeName.PASSWORD); + assertThat(c.challengeResponse()).isEqualTo(ChallengeResponse.FAILURE); + }); + } + + @Test + @DisplayName("maxResults pages with a nextToken that fetches the next event") + void paginatesWithNextToken() { + AdminListUserAuthEventsResponse first = cognito.adminListUserAuthEvents(b -> b + .userPoolId(plusPoolId) + .username(username) + .maxResults(1)); + assertThat(first.authEvents()).hasSize(1); + assertThat(first.authEvents().get(0).eventResponse()).isEqualTo(EventResponseType.PASS); + assertThat(first.nextToken()).isNotBlank(); + + AdminListUserAuthEventsResponse second = cognito.adminListUserAuthEvents(b -> b + .userPoolId(plusPoolId) + .username(username) + .maxResults(1) + .nextToken(first.nextToken())); + assertThat(second.authEvents()).hasSize(1); + assertThat(second.authEvents().get(0).eventResponse()).isEqualTo(EventResponseType.FAIL); + assertThat(second.authEvents().get(0).eventId()) + .isNotEqualTo(first.authEvents().get(0).eventId()); + } + + @Test + @DisplayName("a default (Essentials) pool is UserPoolAddOnNotEnabledException") + void essentialsPoolIsNotEnabled() { + assertThatThrownBy(() -> cognito.adminListUserAuthEvents(b -> b + .userPoolId(essentialsPoolId) + .username(username))) + .isInstanceOf(UserPoolAddOnNotEnabledException.class); + } + + private static void deletePoolQuietly(String userPoolId) { + if (userPoolId == null) { + return; + } + try { + cognito.deleteUserPool(b -> b.userPoolId(userPoolId)); + } catch (Exception ignored) { + // Cleanup only. A failed delete must not hide the test result. + } + } +} diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 5a6a2f75f5..b384f9ee67 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -257,6 +257,7 @@ further divergences, both deliberate: |--------|-------------| | AdminCreateUser | Creates a user and sends the invitation, or with `MessageAction` `RESEND` gives an existing `FORCE_CHANGE_PASSWORD` user a new temporary password and sends the invitation again. See [AdminCreateUser invitations](#admincreateuser-invitations). Creating a user invokes the pre sign-up trigger with triggerSource `PreSignUp_AdminCreateUser`, the request's `ValidationData` and `ClientMetadata`, and `callerContext.clientId` `CLIENT_ID_NOT_APPLICABLE`. A trigger error refuses the user with `UserLambdaValidationException`, and its `autoConfirmUser`, `autoVerifyEmail` and `autoVerifyPhone` are ignored, as on AWS. | | AdminGetUser | Returns a user's stored attributes and status, and the MFA settings (`UserMFASettingList`, `PreferredMfaSetting`) once any is turned on. | +| AdminListUserAuthEvents | Lists a user's recorded sign-in events, newest first, `MaxResults` 0 to 60 (0 or absent means 60) with an opaque `NextToken`. Requires threat protection as AWS does: a pool with `UserPoolTier` `PLUS` and `UserPoolAddOns.AdvancedSecurityMode` `AUDIT` or `ENFORCED`, otherwise `UserPoolAddOnNotEnabledException`. Floci stores `AdvancedSecurityMode` on any pool, and does not reject it on a non-`PLUS` pool at `CreateUserPool` or `UpdateUserPool`; such a pool just has no events. Only sign-ins made while the pool qualifies are recorded, for a user that exists, through `InitiateAuth` or `AdminInitiateAuth` with `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH`, `ADMIN_NO_SRP_AUTH` or `USER_SRP_AUTH`. `CUSTOM_AUTH`, `USER_AUTH`, refresh, managed login, federated sign-in and passwordless sign-in record nothing. Every event has `EventType` `SignIn`. A wrong password (or SRP proof) is `Fail` with `Password` `Failure`. A right password that gets tokens at once is `Pass` with `Password` `Success`. A right password followed by a challenge (`NEW_PASSWORD_REQUIRED`, `SMS_MFA`, `EMAIL_OTP`, `SOFTWARE_TOKEN_MFA`, `SELECT_MFA_TYPE`, `MFA_SETUP`) is `InProgress`, and becomes `Pass` when the challenges end in tokens, with `Mfa` `Success` added when an MFA code was verified. A wrong MFA code leaves the event `InProgress`, as does an abandoned challenge. Floci does no risk evaluation and captures no device or location data, so `EventRisk`, `EventContextData` and `EventFeedback` are never returned. `SignUp`, `ForgotPassword`, `PasswordChange` and `ResendCode` events are not recorded. Events are removed with the user (`AdminDeleteUser`, `DeleteUser`) or the pool. | | AdminDeleteUser | Deletes a user from a user pool. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. | | AdminSetUserPassword | Sets a user's password and permanent-password status. | | AdminUpdateUserAttributes | Updates attributes for a user in a user pool. | diff --git a/docs/services/index.md b/docs/services/index.md index 37424285d1..1e5bfb7cc5 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -27,7 +27,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [STS](sts.md) | `POST /` with `Action=` param | Query | 11 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 | -| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 90 | +| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 91 | | [Cognito Identity](cognitoidentity.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityService.*` | JSON 1.1 | 12 | | [Global Accelerator](globalaccelerator.md) | `POST /` + `X-Amz-Target: GlobalAccelerator_V20180706.*` | JSON 1.1 | 22 | | [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 44 | diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index 53d02e9bbc..d59a44c27c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -92,19 +92,22 @@ final class CognitoAuthFlowHandler { private final LinkedHashMap userAuthSessions = new LinkedHashMap<>(); private final LinkedHashMap simulatedUserAuthSessions = new LinkedHashMap<>(); + /** {@code recordAuthEvent}: the sign-in is a monitored flow, so its proof is recorded as a sign-in event. */ private record SrpSession(String userPoolId, String username, String clientId, String aHex, String bHex, String bPublicHex, String secretBlockBase64, Map clientMetadata, - Instant expiresAt) {} + Instant expiresAt, boolean recordAuthEvent) {} - private record PasswordChangeSession(String userPoolId, String username, String clientId, Instant expiresAt) {} + /** {@code authEventId}, here and in the other challenge sessions, is the sign-in event to finish, or null. */ + private record PasswordChangeSession(String userPoolId, String username, String clientId, Instant expiresAt, + String authEventId) {} private enum TotpPhase { SETUP, ASSOCIATED, VERIFIED, CODE_REQUIRED } private record TotpSession(String userPoolId, String username, String clientId, TotpPhase phase, Map clientMetadata, String triggerSource, Instant expiresAt, String secret, - AtomicInteger failedAttempts) {} + AtomicInteger failedAttempts, String authEventId) {} /** * A pending SMS_MFA, email MFA (EMAIL_OTP) or SELECT_MFA_TYPE challenge after a first factor. @@ -112,7 +115,7 @@ final class CognitoAuthFlowHandler { */ private record MfaSession(String userPoolId, String username, String clientId, String challengeName, List choices, Map clientMetadata, String triggerSource, - Instant expiresAt) {} + Instant expiresAt, String authEventId) {} /** * Correlates a USER_AUTH challenge response back to the InitiateAuth/RespondToAuthChallenge @@ -197,7 +200,7 @@ final class CognitoAuthFlowHandler { return switch (authFlow) { case "USER_PASSWORD_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH"); - yield authenticateWithPassword(pool, client, authParameters, clientMetadata); + yield authenticateWithPassword(pool, client, authParameters, clientMetadata, true); } case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> { requireRefreshEnabled(client, authFlow); @@ -205,7 +208,7 @@ final class CognitoAuthFlowHandler { } case "USER_SRP_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_USER_SRP_AUTH"); - yield handleUserSrpAuth(pool, client, authParameters, clientMetadata); + yield handleUserSrpAuth(pool, client, authParameters, clientMetadata, true); } case "CUSTOM_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_CUSTOM_AUTH", "CUSTOM_AUTH_FLOW_ONLY"); @@ -240,16 +243,16 @@ final class CognitoAuthFlowHandler { return switch (authFlow) { case "ADMIN_USER_PASSWORD_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"); - yield authenticateWithPassword(pool, client, authParameters, clientMetadata); + yield authenticateWithPassword(pool, client, authParameters, clientMetadata, true); } case "ADMIN_NO_SRP_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"); - yield authenticateWithPassword(pool, client, authParameters, clientMetadata); + yield authenticateWithPassword(pool, client, authParameters, clientMetadata, true); } case "USER_PASSWORD_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"); - yield authenticateWithPassword(pool, client, authParameters, clientMetadata); + yield authenticateWithPassword(pool, client, authParameters, clientMetadata, true); } case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> { requireRefreshEnabled(client, authFlow); @@ -257,7 +260,7 @@ final class CognitoAuthFlowHandler { } case "ADMIN_USER_SRP_AUTH", "USER_SRP_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_USER_SRP_AUTH"); - yield handleUserSrpAuth(pool, client, authParameters, clientMetadata); + yield handleUserSrpAuth(pool, client, authParameters, clientMetadata, true); } case "CUSTOM_AUTH" -> { requireFlowEnabled(client, authFlow, "ALLOW_CUSTOM_AUTH", "CUSTOM_AUTH_FLOW_ONLY"); @@ -354,7 +357,8 @@ final class CognitoAuthFlowHandler { result.put("SecretCode", secret); if (state != null) { result.put("Session", issueTotpSession(state.userPoolId(), state.username(), state.clientId(), - TotpPhase.ASSOCIATED, state.clientMetadata(), state.triggerSource(), state.expiresAt(), secret)); + TotpPhase.ASSOCIATED, state.clientMetadata(), state.triggerSource(), state.expiresAt(), secret, + state.authEventId())); } return result; } @@ -397,7 +401,7 @@ final class CognitoAuthFlowHandler { totpSessions.remove(session, state); result.put("Session", issueTotpSession(state.userPoolId(), state.username(), state.clientId(), TotpPhase.VERIFIED, state.clientMetadata(), state.triggerSource(), state.expiresAt(), - state.secret())); + state.secret(), state.authEventId())); } return result; } @@ -410,11 +414,11 @@ final class CognitoAuthFlowHandler { private String issueTotpSession(String poolId, String username, String clientId, TotpPhase phase, Map metadata, String triggerSource, Instant expiresAt, - String secret) { + String secret, String authEventId) { purgeExpired(totpSessions, TotpSession::expiresAt); String token = buildSessionToken(poolId, username, clientId); totpSessions.put(token, new TotpSession(poolId, username, clientId, phase, metadata, triggerSource, - expiresAt, secret, new AtomicInteger())); + expiresAt, secret, new AtomicInteger(), authEventId)); return token; } @@ -475,7 +479,7 @@ final class CognitoAuthFlowHandler { } Map metadata = clientMetadata != null && !clientMetadata.isEmpty() ? clientMetadata : state.clientMetadata(); - return authenticationResult(pool, client, user, state.triggerSource(), metadata); + return authenticationResult(pool, client, user, state.triggerSource(), metadata, state.authEventId(), true); } private void countFailedTotpAttempt(String session, TotpSession state) { @@ -501,11 +505,11 @@ final class CognitoAuthFlowHandler { } if ("PASSWORD".equals(challengeName)) { rejectSimulatedUser(consumeUserAuthSession(pool, client, session, "PASSWORD")); - return authenticateWithPassword(pool, client, responses, clientMetadata); + return authenticateWithPassword(pool, client, responses, clientMetadata, false); } if ("PASSWORD_SRP".equals(challengeName)) { rejectSimulatedUser(consumeUserAuthSession(pool, client, session, "PASSWORD_SRP")); - return handleUserSrpAuth(pool, client, responses, clientMetadata); + return handleUserSrpAuth(pool, client, responses, clientMetadata, false); } if ("SMS_MFA".equals(challengeName)) { return handleMessageMfaChallenge(pool, client, "SMS_MFA", session, responses, clientMetadata); @@ -554,7 +558,8 @@ final class CognitoAuthFlowHandler { passwordChangeSessions.remove(session, pending); } CognitoUser user = applyNewPasswordAttributes(pool, responses); - return completePrimaryAuth(pool, client, user, "TokenGeneration_NewPasswordChallenge", clientMetadata); + return completePrimaryAuth(pool, client, user, "TokenGeneration_NewPasswordChallenge", clientMetadata, + pending.authEventId()); } throw new AwsException("InvalidParameterException", "Unsupported challenge: " + challengeName, 400); } @@ -584,21 +589,24 @@ final class CognitoAuthFlowHandler { // ──────────────────────────── USER_PASSWORD / REFRESH ──────────────────────────── + /** @param recordAuthEvent whether this is one of the flows that record a sign-in event, not USER_AUTH's PASSWORD */ private Map authenticateWithPassword(UserPool pool, UserPoolClient client, - Map params, Map clientMetadata) { + Map params, Map clientMetadata, + boolean recordAuthEvent) { 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 = verifyPassword(pool, client, username, password, clientMetadata); + CognitoUser user = verifyPassword(pool, client, username, password, clientMetadata, recordAuthEvent); + String authEventId = recordAuthEvent ? service.recordSignInEvent(pool, user, true) : null; if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { - return buildNewPasswordRequiredChallenge(pool, client, user); + return buildNewPasswordRequiredChallenge(pool, client, user, authEventId); } - return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", clientMetadata); + return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", clientMetadata, authEventId); } /** @@ -608,7 +616,7 @@ final class CognitoAuthFlowHandler { * and it refuses a user who would get a challenge, because the sign-in page answers none. */ CognitoUser authenticateManagedLogin(UserPool pool, UserPoolClient client, String username, String password) { - CognitoUser user = verifyPassword(pool, client, username, password, Map.of()); + CognitoUser user = verifyPassword(pool, client, username, password, Map.of(), false); if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { throw new AwsException("NotAuthorizedException", MANAGED_LOGIN_NEW_PASSWORD, 400); } @@ -714,7 +722,7 @@ final class CognitoAuthFlowHandler { * sign in, and compares the password. */ private CognitoUser verifyPassword(UserPool pool, UserPoolClient client, String username, String password, - Map clientMetadata) { + Map clientMetadata, boolean recordAuthEvent) { CognitoUser user; try { user = service.adminGetUser(pool.getId(), username); @@ -729,6 +737,9 @@ final class CognitoAuthFlowHandler { requireSignInEligible(user); if (user.getPasswordHash() == null || !user.getPasswordHash().equals(service.hashPassword(password))) { + if (recordAuthEvent) { + service.recordSignInEvent(pool, user, false); + } throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400); } return user; @@ -788,10 +799,15 @@ final class CognitoAuthFlowHandler { } private Map buildNewPasswordRequiredChallenge(UserPool pool, UserPoolClient client, CognitoUser user) { + return buildNewPasswordRequiredChallenge(pool, client, user, null); + } + + private Map buildNewPasswordRequiredChallenge(UserPool pool, UserPoolClient client, CognitoUser user, + String authEventId) { String session = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId()); purgeExpired(passwordChangeSessions, PasswordChangeSession::expiresAt); passwordChangeSessions.put(session, new PasswordChangeSession(pool.getId(), user.getUsername(), - client.getClientId(), sessionExpiry(client, clock.instant()))); + client.getClientId(), sessionExpiry(client, clock.instant()), authEventId)); Map result = new HashMap<>(); result.put("ChallengeName", "NEW_PASSWORD_REQUIRED"); result.put("Session", session); @@ -861,9 +877,10 @@ final class CognitoAuthFlowHandler { // ──────────────────────────── SRP ──────────────────────────── + /** @param recordAuthEvent whether this is one of the flows that record a sign-in event, not USER_AUTH's PASSWORD_SRP */ private Map handleUserSrpAuth(UserPool pool, UserPoolClient client, Map authParameters, - Map clientMetadata) { + Map clientMetadata, boolean recordAuthEvent) { String username = authParameters.get("USERNAME"); String aHex = authParameters.get("SRP_A"); if (username == null || aHex == null) { @@ -879,12 +896,12 @@ final class CognitoAuthFlowHandler { throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); } - return buildSrpChallenge(pool, client, user, aHex, clientMetadata, null); + return buildSrpChallenge(pool, client, user, aHex, clientMetadata, null, recordAuthEvent); } private Map buildSrpChallenge(UserPool pool, UserPoolClient client, CognitoUser user, String aHex, Map clientMetadata, - CustomAuthSession custom) { + CustomAuthSession custom, boolean recordAuthEvent) { validateSrpPublicValue(aHex); String[] serverB = CognitoSrpHelper.generateServerB(user.getSrpVerifier()); String bHex = serverB[0]; @@ -899,7 +916,8 @@ final class CognitoAuthFlowHandler { purgeExpired(srpSessions, SrpSession::expiresAt); SrpSession srp = new SrpSession(pool.getId(), user.getUsername(), client.getClientId(), aHex, bHex, bPublicHex, secretBlockBase64, - clientMetadata == null ? Map.of() : clientMetadata, sessionExpiry(client, clock.instant())); + clientMetadata == null ? Map.of() : clientMetadata, sessionExpiry(client, clock.instant()), + recordAuthEvent); if (custom == null) { srpSessions.put(sessionToken, srp); } else { @@ -947,12 +965,14 @@ final class CognitoAuthFlowHandler { Map effectiveMetadata = (clientMetadata != null && !clientMetadata.isEmpty()) ? clientMetadata : srp.clientMetadata(); srpSessions.remove(session); + String authEventId = srp.recordAuthEvent() ? service.recordSignInEvent(pool, user, true) : null; if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { - return buildNewPasswordRequiredChallenge(pool, client, user); + return buildNewPasswordRequiredChallenge(pool, client, user, authEventId); } - return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata); + return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", effectiveMetadata, + authEventId); } private static void validateSrpPublicValue(String aHex) { @@ -998,6 +1018,9 @@ final class CognitoAuthFlowHandler { boolean valid = CognitoSrpHelper.verifySignature(sessionKey, pool.getId(), user.getUsername(), secretBlock, timestamp, claimSignature); if (!valid || !srp.secretBlockBase64().equals(responses.get("PASSWORD_CLAIM_SECRET_BLOCK"))) { + if (srp.recordAuthEvent()) { + service.recordSignInEvent(pool, user, false); + } throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400); } return user; @@ -1095,11 +1118,11 @@ final class CognitoAuthFlowHandler { List advertised = advertiseAvailable ? available : null; return switch (challenge) { case "PASSWORD" -> params.containsKey("PASSWORD") - ? authenticateWithPassword(pool, client, params, clientMetadata) + ? authenticateWithPassword(pool, client, params, clientMetadata, false) : userAuthChallengeResponse(pool, client, user, "PASSWORD", advertised, Map.of("USERNAME", user.getUsername())); case "PASSWORD_SRP" -> params.containsKey("SRP_A") - ? handleUserSrpAuth(pool, client, params, clientMetadata) + ? handleUserSrpAuth(pool, client, params, clientMetadata, false) : userAuthChallengeResponse(pool, client, user, "PASSWORD_SRP", advertised, Map.of("USERNAME", user.getUsername())); case "EMAIL_OTP" -> issueOtpChallenge(pool, client, user, "EMAIL_OTP", "email", "EMAIL", @@ -1521,7 +1544,8 @@ final class CognitoAuthFlowHandler { String challengeName = (String) defineResp.getOrDefault("challengeName", "CUSTOM_CHALLENGE"); state.currentChallengeName = challengeName; if (srpAuth && "PASSWORD_VERIFIER".equals(challengeName)) { - return buildSrpChallenge(pool, client, user, authParameters.get("SRP_A"), state.clientMetadata, state); + return buildSrpChallenge(pool, client, user, authParameters.get("SRP_A"), state.clientMetadata, state, + false); } Map publicParams = new HashMap<>(); @@ -2328,26 +2352,33 @@ final class CognitoAuthFlowHandler { */ private Map completePrimaryAuth(UserPool pool, UserPoolClient client, CognitoUser user, String triggerSource, Map clientMetadata) { + return completePrimaryAuth(pool, client, user, triggerSource, clientMetadata, null); + } + + /** @param authEventId the sign-in event this first factor started, finished when tokens are issued, or null */ + private Map completePrimaryAuth(UserPool pool, UserPoolClient client, CognitoUser user, + String triggerSource, Map clientMetadata, + String authEventId) { String mode = pool.getMfaConfiguration(); if (!"ON".equals(mode) && !"OPTIONAL".equals(mode)) { - return authenticationResult(pool, client, user, triggerSource, clientMetadata); + return authenticationResult(pool, client, user, triggerSource, clientMetadata, authEventId, false); } Map metadata = clientMetadata == null ? Map.of() : Map.copyOf(clientMetadata); List factors = mfaFactors(pool, user); if (factors.isEmpty()) { if ("ON".equals(mode) && Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled())) { - return totpChallenge(pool, client, user, TotpPhase.SETUP, triggerSource, metadata); + return totpChallenge(pool, client, user, TotpPhase.SETUP, triggerSource, metadata, authEventId); } - return authenticationResult(pool, client, user, triggerSource, clientMetadata); + return authenticationResult(pool, client, user, triggerSource, clientMetadata, authEventId, false); } String preferred = CognitoService.preferredMfaSetting(pool, user); if (preferred != null && factors.contains(preferred)) { - return startMfaChallenge(pool, client, user, preferred, triggerSource, metadata); + return startMfaChallenge(pool, client, user, preferred, triggerSource, metadata, authEventId); } if (factors.size() == 1) { - return startMfaChallenge(pool, client, user, factors.get(0), triggerSource, metadata); + return startMfaChallenge(pool, client, user, factors.get(0), triggerSource, metadata, authEventId); } - return selectMfaTypeChallenge(pool, client, user, factors, triggerSource, metadata); + return selectMfaTypeChallenge(pool, client, user, factors, triggerSource, metadata, authEventId); } /** @@ -2413,9 +2444,9 @@ final class CognitoAuthFlowHandler { private Map startMfaChallenge(UserPool pool, UserPoolClient client, CognitoUser user, String factor, String triggerSource, - Map metadata) { + Map metadata, String authEventId) { if ("SOFTWARE_TOKEN_MFA".equals(factor)) { - return totpChallenge(pool, client, user, TotpPhase.CODE_REQUIRED, triggerSource, metadata); + return totpChallenge(pool, client, user, TotpPhase.CODE_REQUIRED, triggerSource, metadata, authEventId); } boolean sms = "SMS_MFA".equals(factor); Map customMessage = customEmailSenderTakesOver(pool, sms ? "SMS" : "EMAIL") ? Map.of() @@ -2426,14 +2457,15 @@ final class CognitoAuthFlowHandler { parameters.put("USERNAME", user.getUsername()); Map result = new HashMap<>(); result.put("ChallengeName", factor); - result.put("Session", issueMfaSession(pool, client, user, factor, List.of(), triggerSource, metadata)); + result.put("Session", issueMfaSession(pool, client, user, factor, List.of(), triggerSource, metadata, + authEventId)); result.put("ChallengeParameters", parameters); return result; } private Map selectMfaTypeChallenge(UserPool pool, UserPoolClient client, CognitoUser user, List factors, String triggerSource, - Map metadata) { + Map metadata, String authEventId) { Map parameters = new HashMap<>(); parameters.put("USERNAME", user.getUsername()); try { @@ -2444,19 +2476,20 @@ final class CognitoAuthFlowHandler { Map result = new HashMap<>(); result.put("ChallengeName", "SELECT_MFA_TYPE"); result.put("Session", issueMfaSession(pool, client, user, "SELECT_MFA_TYPE", factors, triggerSource, - metadata)); + metadata, authEventId)); result.put("ChallengeParameters", parameters); return result; } private Map totpChallenge(UserPool pool, UserPoolClient client, CognitoUser user, - TotpPhase phase, String triggerSource, Map metadata) { + TotpPhase phase, String triggerSource, Map metadata, + String authEventId) { String challengeName = phase == TotpPhase.SETUP ? "MFA_SETUP" : "SOFTWARE_TOKEN_MFA"; Map result = new HashMap<>(); result.put("ChallengeName", challengeName); result.put("Session", issueTotpSession(pool.getId(), user.getUsername(), client.getClientId(), phase, metadata, triggerSource, sessionExpiry(client, clock.instant()), - user.getSoftwareTokenMfaSecret())); + user.getSoftwareTokenMfaSecret(), authEventId)); Map parameters = new HashMap<>(); if (phase == TotpPhase.SETUP) { parameters.put("USERNAME", user.getUsername()); @@ -2473,11 +2506,12 @@ final class CognitoAuthFlowHandler { } private String issueMfaSession(UserPool pool, UserPoolClient client, CognitoUser user, String challengeName, - List choices, String triggerSource, Map metadata) { + List choices, String triggerSource, Map metadata, + String authEventId) { purgeExpired(mfaSessions, MfaSession::expiresAt); String token = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId()); mfaSessions.put(token, new MfaSession(pool.getId(), user.getUsername(), client.getClientId(), challengeName, - List.copyOf(choices), metadata, triggerSource, sessionExpiry(client, clock.instant()))); + List.copyOf(choices), metadata, triggerSource, sessionExpiry(client, clock.instant()), authEventId)); return token; } @@ -2529,7 +2563,7 @@ final class CognitoAuthFlowHandler { user = service.adminGetUser(pool.getId(), user.getUsername()); Map metadata = clientMetadata != null && !clientMetadata.isEmpty() ? clientMetadata : state.clientMetadata(); - return authenticationResult(pool, client, user, state.triggerSource(), metadata); + return authenticationResult(pool, client, user, state.triggerSource(), metadata, state.authEventId(), true); } /** Answers SELECT_MFA_TYPE: {@code ANSWER} names one of {@code MFAS_CAN_CHOOSE}, whose challenge follows. */ @@ -2552,13 +2586,21 @@ final class CognitoAuthFlowHandler { requireSignInEligible(user); Map metadata = clientMetadata != null && !clientMetadata.isEmpty() ? Map.copyOf(clientMetadata) : state.clientMetadata(); - return startMfaChallenge(pool, client, user, answer, state.triggerSource(), metadata); + return startMfaChallenge(pool, client, user, answer, state.triggerSource(), metadata, state.authEventId()); } private Map authenticationResult(UserPool pool, UserPoolClient client, CognitoUser user, String triggerSource, Map clientMetadata) { + return authenticationResult(pool, client, user, triggerSource, clientMetadata, null, false); + } + + /** Issues the tokens and finishes the sign-in event {@code authEventId}, if any, as Pass. */ + private Map authenticationResult(UserPool pool, UserPoolClient client, CognitoUser user, + String triggerSource, Map clientMetadata, + String authEventId, boolean mfaVerified) { Map result = new HashMap<>(); result.put("AuthenticationResult", issueTokens(pool, client, user, triggerSource, clientMetadata)); + service.completeSignInEvent(pool.getId(), user, authEventId, mfaVerified); return result; } 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 051172f04c..c710e4ad28 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 @@ -149,6 +149,7 @@ public class CognitoJsonHandler { case "StartWebAuthnRegistration" -> handleStartWebAuthnRegistration(request); case "CompleteWebAuthnRegistration" -> handleCompleteWebAuthnRegistration(request); case "ListWebAuthnCredentials" -> handleListWebAuthnCredentials(request); + case "AdminListUserAuthEvents" -> handleAdminListUserAuthEvents(request); case "DeleteWebAuthnCredential" -> handleDeleteWebAuthnCredential(request); default -> Response.status(400) .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported.")) @@ -1643,6 +1644,14 @@ public class CognitoJsonHandler { request.hasNonNull("NextToken") ? request.path("NextToken").asText() : null))).build(); } + private Response handleAdminListUserAuthEvents(JsonNode request) { + return Response.ok(objectMapper.valueToTree(service.adminListUserAuthEvents( + request.path("UserPoolId").asText(), + request.path("Username").asText(), + request.hasNonNull("MaxResults") ? request.path("MaxResults").asInt() : null, + request.hasNonNull("NextToken") ? request.path("NextToken").asText() : null))).build(); + } + private Response handleDeleteWebAuthnCredential(JsonNode request) { service.deleteWebAuthnCredential(request.path("AccessToken").asText(), request.path("CredentialId").asText()); return Response.ok(objectMapper.createObjectNode()).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 2b64063527..f013283efe 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 @@ -31,6 +31,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.acm.AcmService; import io.github.hectorvent.floci.services.acm.model.Certificate; import io.github.hectorvent.floci.services.acm.model.CertificateStatus; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthEvent; import io.github.hectorvent.floci.services.cognito.model.CognitoGroup; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; import io.github.hectorvent.floci.services.cognito.model.EmailMfaSettings; @@ -100,6 +101,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags; @@ -124,6 +126,7 @@ public class CognitoService implements ResourceProvider { private static final Pattern EMAIL_ATTRIBUTE_PATTERN = Pattern.compile("[^\\s\\p{Cntrl}@<>,;]+@[^\\s\\p{Cntrl}@<>,;]+"); private static final int EMAIL_ATTRIBUTE_MAX_LENGTH = 2048; + private static final int MAX_AUTH_EVENTS_PAGE = 60; /** * No configured CloudFront suffix, for the test constructors: the suffix then follows the * request's partition. CDI wires {@code floci.services.cloudfront.domain-suffix}. @@ -182,6 +185,9 @@ public class CognitoService implements ResourceProvider { private final StorageBackend userStore; private final StorageBackend groupStore; private final StorageBackend revokedTokenStore; + private final StorageBackend authEventStore; + private final AtomicLong authEventSequence = new AtomicLong(); + private final Clock clock; private final String baseUrl; private final String cloudFrontDomainSuffix; private final RegionResolver regionResolver; @@ -245,6 +251,8 @@ public class CognitoService implements ResourceProvider { new TypeReference>() {}), storageFactory.create("cognito", "cognito-revoked-tokens.json", new TypeReference>() {}), + storageFactory.create("cognito", "cognito-auth-events.json", + new TypeReference>() {}), trimTrailingSlash(emulatorConfig.effectiveBaseUrl()), emulatorConfig.services().cloudfront().domainSuffix().orElse(null), regionResolver, @@ -378,7 +386,34 @@ public class CognitoService implements ResourceProvider { Clock clock, boolean enforceTokenValidityLimits, CustomSenderCodeEncryptor customSenderCodeEncryptor) { + this(poolStore, clientStore, resourceServerStore, domainStore, identityProviderStore, userStore, + groupStore, revokedTokenStore, new InMemoryStorage<>(), baseUrl, cloudFrontDomainSuffix, + regionResolver, lambdaService, acmService, verificationCodeService, messageDispatcher, + certificateManager, clock, enforceTokenValidityLimits, customSenderCodeEncryptor); + } + + /** As above, with the store of the sign-in events that {@code AdminListUserAuthEvents} lists. */ + CognitoService(StorageBackend poolStore, + StorageBackend clientStore, + StorageBackend resourceServerStore, + StorageBackend domainStore, + StorageBackend identityProviderStore, + StorageBackend userStore, + StorageBackend groupStore, + StorageBackend revokedTokenStore, + StorageBackend authEventStore, + String baseUrl, + String cloudFrontDomainSuffix, + RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService, + VerificationCodeService verificationCodeService, + CognitoMessageDispatcher messageDispatcher, + TlsCertificateManager certificateManager, + Clock clock, + boolean enforceTokenValidityLimits, + CustomSenderCodeEncryptor customSenderCodeEncryptor) { this.poolStore = poolStore; + this.authEventStore = authEventStore; + this.clock = clock; this.clientStore = clientStore; this.resourceServerStore = resourceServerStore; this.domainStore = domainStore; @@ -1148,6 +1183,7 @@ public class CognitoService implements ResourceProvider { userStore.delete(userKey(id, u.getUsername())); } }); + deleteAuthEventsOfPool(id); resourceServerStore.scan(k -> k.startsWith(prefix)) .forEach(r -> resourceServerStore.delete(resourceServerKey(id, r.getIdentifier()))); // Clients are keyed by client id alone, so they are found by their userPoolId field. @@ -2740,6 +2776,7 @@ public class CognitoService implements ResourceProvider { }); } userStore.delete(userKey(userPoolId, user.getUsername())); + deleteAuthEventsOfUser(userPoolId, user); } public void adminSetUserPassword(String userPoolId, String username, String password, boolean permanent) { @@ -3979,6 +4016,183 @@ public class CognitoService implements ResourceProvider { return String.format(Locale.ROOT, "%019d/%s", credential.getCreatedAtMillis(), credential.getCredentialId()); } + // ──────────────────────────── Sign-in events ──────────────────────────── + + /** + * Whether the pool records sign-in events: AWS offers them with threat protection, which needs the + * Plus feature plan and an {@code AdvancedSecurityMode} of AUDIT or ENFORCED. Floci stores both + * settings without checking one against the other, so a pool can hold a mode its plan never allows. + */ + static boolean signInEventsEnabled(UserPool pool) { + if (!"PLUS".equals(pool.getUserPoolTier()) || pool.getUserPoolAddOns() == null) { + return false; + } + Object mode = pool.getUserPoolAddOns().get("AdvancedSecurityMode"); + return "AUDIT".equals(mode) || "ENFORCED".equals(mode); + } + + /** + * Records a SignIn event for a user who gave the right ({@code passwordVerified}) or wrong password, + * when the pool records events. A right password is {@code InProgress} until the sign-in ends in + * tokens, which {@link #completeSignInEvent} then marks Pass. Returns the event id, or null when + * nothing was recorded. A failure here is logged and never reaches the sign-in. + */ + String recordSignInEvent(UserPool pool, CognitoUser user, boolean passwordVerified) { + if (!signInEventsEnabled(pool)) { + return null; + } + try { + CognitoAuthEvent event = new CognitoAuthEvent(); + event.setEventId(UUID.randomUUID().toString()); + event.setUserPoolId(pool.getId()); + event.setUserSub(authEventSubject(user)); + event.setEventType("SignIn"); + event.setEventResponse(passwordVerified ? "InProgress" : "Fail"); + event.setCreationMillis(clock.millis()); + event.setSequence(authEventSequence.incrementAndGet()); + event.getChallengeResponses().add(new CognitoAuthEvent.Challenge("Password", + passwordVerified ? "Success" : "Failure")); + synchronized (userLock(pool.getId(), user.getUsername())) { + if (!userStillOwnsAuthEvents(pool.getId(), user)) { + return null; + } + authEventStore.put(authEventKey(pool.getId(), event.getUserSub(), event.getEventId()), event); + } + return event.getEventId(); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not record a sign-in event for user {0} in pool {1}", user.getUsername(), + pool.getId()); + return null; + } + } + + /** Marks a SignIn event Pass once its sign-in ended in tokens, with the MFA code that was verified on the way. */ + void completeSignInEvent(String poolId, CognitoUser user, String eventId, boolean mfaVerified) { + if (eventId == null) { + return; + } + try { + String key = authEventKey(poolId, authEventSubject(user), eventId); + // The user's lock is the one its deletion sweeps the events under, so a sign-in that finishes + // after the user is gone cannot write the event back. + synchronized (userLock(poolId, user.getUsername())) { + if (!userStillOwnsAuthEvents(poolId, user)) { + return; + } + authEventStore.get(key).ifPresent(event -> { + event.setEventResponse("Pass"); + if (mfaVerified) { + event.getChallengeResponses().add(new CognitoAuthEvent.Challenge("Mfa", "Success")); + } + authEventStore.put(key, event); + }); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not complete sign-in event {0} in pool {1}", eventId, poolId); + } + } + + private boolean userStillOwnsAuthEvents(String poolId, CognitoUser user) { + return userStore.get(userKey(poolId, user.getUsername())) + .map(stored -> authEventSubject(stored).equals(authEventSubject(user))) + .orElse(false); + } + + private static String authEventSubject(CognitoUser user) { + String sub = user.getAttributes() == null ? null : user.getAttributes().get("sub"); + return sub != null ? sub : user.getUsername(); + } + + private static String authEventKey(String poolId, String userSub, String eventId) { + return poolId + "::" + userSub + "::" + eventId; + } + + /** + * The keys of the events a pool, or one of its users when {@code userSub} is given, owns. Pool ids and + * subs are caller-chosen and may contain the key delimiter, so a key prefix can also match another + * pool's or user's events; the stored event's own fields settle ownership. + */ + private List authEventKeysOwnedBy(String poolId, String userSub) { + String prefix = userSub == null ? poolId + "::" : authEventKey(poolId, userSub, ""); + return authEventStore.keys().stream() + .filter(k -> k.startsWith(prefix)) + .filter(k -> authEventStore.get(k) + .map(e -> poolId.equals(e.getUserPoolId()) + && (userSub == null || userSub.equals(e.getUserSub()))) + .orElse(false)) + .toList(); + } + + private void deleteAuthEventsOfUser(String poolId, CognitoUser user) { + authEventKeysOwnedBy(poolId, authEventSubject(user)).forEach(authEventStore::delete); + } + + private void deleteAuthEventsOfPool(String poolId) { + authEventKeysOwnedBy(poolId, null).forEach(authEventStore::delete); + } + + /** + * AdminListUserAuthEvents: the user's recorded sign-ins, newest first, a page of at most 60 at a time. + * {@code NextToken} is a cursor on the last event listed, so an event recorded between two pages does + * not shift the next page. + */ + public Map adminListUserAuthEvents(String userPoolId, String username, Integer maxResults, + String nextToken) { + if (maxResults != null && (maxResults < 0 || maxResults > MAX_AUTH_EVENTS_PAGE)) { + String constraint = maxResults < 0 + ? "greater than or equal to 0" + : "less than or equal to " + MAX_AUTH_EVENTS_PAGE; + throw validationError( + "Value '" + maxResults + "' at 'maxResults' failed to satisfy " + + "constraint: Member must have value " + constraint); + } + UserPool pool = poolStore.get(userPoolId).orElseThrow(() -> userPoolNotFound(userPoolId)); + if (!signInEventsEnabled(pool)) { + throw new AwsException("UserPoolAddOnNotEnabledException", + "Advanced security features are not enabled for this user pool.", 400); + } + CognitoUser user = adminGetUser(userPoolId, username); + int pageSize = maxResults == null || maxResults == 0 ? MAX_AUTH_EVENTS_PAGE : maxResults; + List events = authEventKeysOwnedBy(userPoolId, authEventSubject(user)).stream() + .flatMap(k -> authEventStore.get(k).stream()) + .toList(); + PaginatedResult listed = Pagination.paginate(events, + CognitoService::authEventCursor, pageSize, nextToken, "AdminListUserAuthEvents", + invalid -> new AwsException("InvalidParameterException", "Invalid NextToken", 400)); + List> page = new ArrayList<>(); + for (CognitoAuthEvent event : listed.items()) { + Map description = new LinkedHashMap<>(); + description.put("EventId", event.getEventId()); + description.put("EventType", event.getEventType()); + description.put("CreationDate", EpochSeconds.fromMillis(event.getCreationMillis())); + description.put("EventResponse", event.getEventResponse()); + List> challenges = new ArrayList<>(); + for (CognitoAuthEvent.Challenge challenge : event.getChallengeResponses()) { + Map entry = new LinkedHashMap<>(); + entry.put("ChallengeName", challenge.getChallengeName()); + entry.put("ChallengeResponse", challenge.getChallengeResponse()); + challenges.add(entry); + } + description.put("ChallengeResponses", challenges); + page.add(description); + } + Map response = new LinkedHashMap<>(); + response.put("AuthEvents", page); + if (listed.nextToken() != null) { + response.put("NextToken", listed.nextToken()); + } + return response; + } + + /** + * Sorts ascending as newest first: both times are inverted, and the event id settles two events + * created in the same millisecond with the same sequence, which only a restart can produce. + */ + private static String authEventCursor(CognitoAuthEvent event) { + return String.format(Locale.ROOT, "%019d/%019d/%s", Long.MAX_VALUE - event.getCreationMillis(), + Long.MAX_VALUE - event.getSequence(), event.getEventId()); + } + /** DeleteWebAuthnCredential: removes one of the access token's user's passkeys. */ public void deleteWebAuthnCredential(String accessToken, String credentialId) { VerifiedAccessToken token = verifyAccessToken(accessToken); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthEvent.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthEvent.java new file mode 100644 index 0000000000..fe238c6466 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthEvent.java @@ -0,0 +1,76 @@ +package io.github.hectorvent.floci.services.cognito.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; + +/** + * One sign-in attempt recorded for {@code AdminListUserAuthEvents}. The event belongs to the user's + * {@code sub}, so a user deleted and created again under the same username starts with no history. + * {@code sequence} orders events created in the same millisecond. Each challenge is a + * {@code ChallengeName} ({@code Password} or {@code Mfa}) with its {@code ChallengeResponse} + * ({@code Success} or {@code Failure}). + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class CognitoAuthEvent { + + /** One {@code ChallengeResponseType}. */ + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Challenge { + private String challengeName; + private String challengeResponse; + + public Challenge() { + } + + public Challenge(String challengeName, String challengeResponse) { + this.challengeName = challengeName; + this.challengeResponse = challengeResponse; + } + + public String getChallengeName() { return challengeName; } + public void setChallengeName(String challengeName) { this.challengeName = challengeName; } + + public String getChallengeResponse() { return challengeResponse; } + public void setChallengeResponse(String challengeResponse) { this.challengeResponse = challengeResponse; } + } + + private String eventId; + private String userPoolId; + private String userSub; + private String eventType; + private String eventResponse; + private long creationMillis; + private long sequence; + private List challengeResponses = new ArrayList<>(); + + public String getEventId() { return eventId; } + public void setEventId(String eventId) { this.eventId = eventId; } + + public String getUserPoolId() { return userPoolId; } + public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; } + + public String getUserSub() { return userSub; } + public void setUserSub(String userSub) { this.userSub = userSub; } + + public String getEventType() { return eventType; } + public void setEventType(String eventType) { this.eventType = eventType; } + + public String getEventResponse() { return eventResponse; } + public void setEventResponse(String eventResponse) { this.eventResponse = eventResponse; } + + public long getCreationMillis() { return creationMillis; } + public void setCreationMillis(long creationMillis) { this.creationMillis = creationMillis; } + + public long getSequence() { return sequence; } + public void setSequence(long sequence) { this.sequence = sequence; } + + public List getChallengeResponses() { return challengeResponses; } + public void setChallengeResponses(List challengeResponses) { + this.challengeResponses = challengeResponses; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAdminListUserAuthEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAdminListUserAuthEventsIntegrationTest.java new file mode 100644 index 0000000000..b4a192ebd3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAdminListUserAuthEventsIntegrationTest.java @@ -0,0 +1,447 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class CognitoAdminListUserAuthEventsIntegrationTest { + private static final String PASSWORD = "Perm1234!"; + private static final String WRONG_PASSWORD = "Wrong1234!"; + + @Inject + Clock clock; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void poolWithoutThreatProtectionRefusesTheOperation() throws Exception { + String defaultPool = createPool("\"UserPoolTier\":\"ESSENTIALS\""); + String essentialsAudit = createPool("\"UserPoolTier\":\"ESSENTIALS\"," + + "\"UserPoolAddOns\":{\"AdvancedSecurityMode\":\"AUDIT\"}"); + String plusOff = createPool("\"UserPoolTier\":\"PLUS\",\"UserPoolAddOns\":{\"AdvancedSecurityMode\":\"OFF\"}"); + String plusNoAddOns = createPool("\"UserPoolTier\":\"PLUS\""); + for (String poolId : new String[] {defaultPool, essentialsAudit, plusOff, plusNoAddOns}) { + String username = createUser(poolId); + listEvents(poolId, username, "") + .then().statusCode(400) + .body("__type", equalTo("UserPoolAddOnNotEnabledException")); + } + } + + @Test + void missingPoolAndMissingUserAreReported() throws Exception { + listEvents("us-east-1_doesnotexist", "nobody", "") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + String poolId = createEligiblePool("AUDIT"); + listEvents(poolId, "nobody-" + UUID.randomUUID(), "") + .then().statusCode(400).body("__type", equalTo("UserNotFoundException")); + } + + @Test + void poolIsCheckedBeforeEligibilityAndEligibilityBeforeUser() throws Exception { + String ineligible = createPool("\"UserPoolTier\":\"ESSENTIALS\""); + listEvents(ineligible, "nobody", "") + .then().statusCode(400).body("__type", equalTo("UserPoolAddOnNotEnabledException")); + } + + @Test + void userWithoutSignInsHasNoEvents() throws Exception { + String poolId = createEligiblePool("ENFORCED"); + String username = createUser(poolId); + listEvents(poolId, username, "") + .then().statusCode(200) + .body("AuthEvents.size()", equalTo(0)) + .body("containsKey('NextToken')", equalTo(false)); + } + + @Test + void failedThenPassedSignInIsListedNewestFirst() throws Exception { + String poolId = createEligiblePool("AUDIT"); + String clientId = createClient(poolId); + String username = createUser(poolId); + + cognitoAction("InitiateAuth", passwordAuth(clientId, username, WRONG_PASSWORD)) + .then().statusCode(400).body("__type", equalTo("NotAuthorizedException")); + cognitoJson("InitiateAuth", passwordAuth(clientId, username, PASSWORD)); + + JsonNode events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")) + .path("AuthEvents"); + assertEquals(2, events.size()); + JsonNode passed = events.get(0); + JsonNode failed = events.get(1); + assertEquals("SignIn", passed.path("EventType").asText()); + assertEquals("Pass", passed.path("EventResponse").asText()); + assertChallenges(passed, "Password", "Success"); + assertEquals("SignIn", failed.path("EventType").asText()); + assertEquals("Fail", failed.path("EventResponse").asText()); + assertChallenges(failed, "Password", "Failure"); + assertTrue(passed.path("CreationDate").isNumber()); + assertTrue(passed.path("CreationDate").asDouble() >= failed.path("CreationDate").asDouble()); + assertFalse(passed.path("EventId").asText().isEmpty()); + assertFalse(passed.path("EventId").asText().equals(failed.path("EventId").asText())); + for (JsonNode event : events) { + assertTrue(event.path("EventRisk").isMissingNode()); + assertTrue(event.path("EventContextData").isMissingNode()); + assertTrue(event.path("EventFeedback").isMissingNode()); + } + } + + @Test + void adminInitiateAuthRecordsAndTheSubResolvesTheUser() throws Exception { + String poolId = createEligiblePool("AUDIT"); + String clientId = createClient(poolId); + String username = createUser(poolId); + cognitoAction("AdminInitiateAuth", """ + {"UserPoolId":"%s","ClientId":"%s","AuthFlow":"ADMIN_USER_PASSWORD_AUTH", + "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}} + """.formatted(poolId, clientId, username, WRONG_PASSWORD)) + .then().statusCode(400); + String sub = ""; + for (JsonNode attribute : cognitoJson("AdminGetUser", """ + {"UserPoolId":"%s","Username":"%s"} + """.formatted(poolId, username)).path("UserAttributes")) { + if ("sub".equals(attribute.path("Name").asText())) { + sub = attribute.path("Value").asText(); + } + } + assertFalse(sub.isEmpty()); + JsonNode events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, sub, "")).path("AuthEvents"); + assertEquals(1, events.size()); + assertEquals("Fail", events.get(0).path("EventResponse").asText()); + } + + @Test + void unknownUserAndIneligiblePoolRecordNothing() throws Exception { + String ineligible = createPool("\"UserPoolTier\":\"PLUS\""); + String clientId = createClient(ineligible); + String username = createUser(ineligible); + cognitoJson("InitiateAuth", passwordAuth(clientId, username, PASSWORD)); + cognitoAction("InitiateAuth", passwordAuth(clientId, username, WRONG_PASSWORD)).then().statusCode(400); + + cognitoJson("UpdateUserPool", """ + {"UserPoolId":"%s","UserPoolTier":"PLUS","UserPoolAddOns":{"AdvancedSecurityMode":"AUDIT"}} + """.formatted(ineligible)); + listEvents(ineligible, username, "").then().statusCode(200).body("AuthEvents.size()", equalTo(0)); + + cognitoAction("InitiateAuth", passwordAuth(clientId, "ghost-" + UUID.randomUUID(), PASSWORD)) + .then().statusCode(400); + listEvents(ineligible, username, "").then().statusCode(200).body("AuthEvents.size()", equalTo(0)); + } + + @Test + void paginationWalksEveryEventOnceNewestFirst() throws Exception { + String poolId = createEligiblePool("AUDIT"); + String clientId = createClient(poolId); + String username = createUser(poolId); + for (int i = 0; i < 5; i++) { + if (i % 2 == 0) { + cognitoAction("InitiateAuth", passwordAuth(clientId, username, WRONG_PASSWORD)).then().statusCode(400); + } else { + cognitoJson("InitiateAuth", passwordAuth(clientId, username, PASSWORD)); + } + } + JsonNode all = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals(5, all.size()); + + JsonNode first = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "\"MaxResults\":2")); + assertEquals(2, first.path("AuthEvents").size()); + assertFalse(first.path("NextToken").asText().isEmpty()); + JsonNode second = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, + "\"MaxResults\":2,\"NextToken\":\"" + first.path("NextToken").asText() + "\"")); + assertEquals(2, second.path("AuthEvents").size()); + JsonNode third = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, + "\"MaxResults\":2,\"NextToken\":\"" + second.path("NextToken").asText() + "\"")); + assertEquals(1, third.path("AuthEvents").size()); + assertTrue(third.path("NextToken").isMissingNode()); + + Set seen = new HashSet<>(); + int index = 0; + for (JsonNode page : new JsonNode[] {first, second, third}) { + for (JsonNode event : page.path("AuthEvents")) { + assertEquals(all.get(index++).path("EventId").asText(), event.path("EventId").asText()); + assertTrue(seen.add(event.path("EventId").asText())); + } + } + assertEquals(5, seen.size()); + + JsonNode zero = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "\"MaxResults\":0")); + assertEquals(5, zero.path("AuthEvents").size()); + } + + @Test + void invalidPageArgumentsAreRejected() throws Exception { + String poolId = createEligiblePool("AUDIT"); + String username = createUser(poolId); + for (int bad : new int[] {61, -1}) { + listEvents(poolId, username, "\"MaxResults\":" + bad) + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterException")) + .body("message", containsString("1 validation error detected")) + .body("message", containsString("maxResults")); + } + listEvents(poolId, username, "\"NextToken\":\"bogus\"") + .then().statusCode(400).body("__type", equalTo("InvalidParameterException")); + } + + @Test + void newPasswordChallengeStaysInProgressUntilItIsAnswered() throws Exception { + String poolId = createEligiblePool("ENFORCED"); + String clientId = createClient(poolId); + String username = "temp-" + UUID.randomUUID(); + cognitoJson("AdminCreateUser", """ + {"UserPoolId":"%s","Username":"%s","TemporaryPassword":"Temp1234!","MessageAction":"SUPPRESS"} + """.formatted(poolId, username)); + + JsonNode challenge = cognitoJson("InitiateAuth", passwordAuth(clientId, username, "Temp1234!")); + assertEquals("NEW_PASSWORD_REQUIRED", challenge.path("ChallengeName").asText()); + JsonNode events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals(1, events.size()); + assertEquals("InProgress", events.get(0).path("EventResponse").asText()); + assertChallenges(events.get(0), "Password", "Success"); + String eventId = events.get(0).path("EventId").asText(); + + JsonNode done = cognitoJson("RespondToAuthChallenge", """ + {"ClientId":"%s","ChallengeName":"NEW_PASSWORD_REQUIRED","Session":"%s", + "ChallengeResponses":{"USERNAME":"%s","NEW_PASSWORD":"%s"}} + """.formatted(clientId, challenge.path("Session").asText(), username, PASSWORD)); + assertFalse(done.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals(1, events.size()); + assertEquals(eventId, events.get(0).path("EventId").asText()); + assertEquals("Pass", events.get(0).path("EventResponse").asText()); + assertChallenges(events.get(0), "Password", "Success"); + } + + @Test + void softwareTokenMfaSignInAppendsTheMfaChallenge() throws Exception { + String poolId = createEligiblePool("AUDIT"); + cognitoJson("SetUserPoolMfaConfig", """ + {"UserPoolId":"%s","MfaConfiguration":"OPTIONAL","SoftwareTokenMfaConfiguration":{"Enabled":true}} + """.formatted(poolId)); + String clientId = createClient(poolId); + String username = createUser(poolId); + String accessToken = cognitoJson("InitiateAuth", passwordAuth(clientId, username, PASSWORD)) + .path("AuthenticationResult").path("AccessToken").asText(); + String secret = cognitoJson("AssociateSoftwareToken", """ + {"AccessToken":"%s"} + """.formatted(accessToken)).path("SecretCode").asText(); + cognitoJson("VerifySoftwareToken", """ + {"AccessToken":"%s","UserCode":"%s"} + """.formatted(accessToken, CognitoTotp.code(secret, clock.instant()))); + cognitoJson("SetUserMFAPreference", """ + {"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true,"PreferredMfa":true}} + """.formatted(accessToken)); + + JsonNode challenged = cognitoJson("InitiateAuth", passwordAuth(clientId, username, PASSWORD)); + assertEquals("SOFTWARE_TOKEN_MFA", challenged.path("ChallengeName").asText()); + JsonNode events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals(2, events.size()); + assertEquals("InProgress", events.get(0).path("EventResponse").asText()); + assertEquals("Pass", events.get(1).path("EventResponse").asText()); + + cognitoAction("RespondToAuthChallenge", mfaResponse(clientId, challenged, username, + invalidTotpCode(secret, clock.instant()))) + .then().statusCode(400).body("__type", equalTo("CodeMismatchException")); + events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals("InProgress", events.get(0).path("EventResponse").asText()); + assertEquals(1, events.get(0).path("ChallengeResponses").size()); + + String code = CognitoTotp.code(secret, clock.instant().plusSeconds(30)); + JsonNode signedIn = cognitoJson("RespondToAuthChallenge", mfaResponse(clientId, challenged, username, code)); + assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals(2, events.size()); + JsonNode event = events.get(0); + assertEquals("Pass", event.path("EventResponse").asText()); + assertEquals(2, event.path("ChallengeResponses").size()); + assertEquals("Password", event.path("ChallengeResponses").get(0).path("ChallengeName").asText()); + assertEquals("Success", event.path("ChallengeResponses").get(0).path("ChallengeResponse").asText()); + assertEquals("Mfa", event.path("ChallengeResponses").get(1).path("ChallengeName").asText()); + assertEquals("Success", event.path("ChallengeResponses").get(1).path("ChallengeResponse").asText()); + } + + @Test + void srpWrongProofFailsAndRightProofPasses() throws Exception { + String poolId = createEligiblePool("AUDIT"); + String clientId = createClient(poolId); + String username = createUser(poolId); + + JsonNode wrong = srpStart(clientId, username); + Map badProof = CognitoSrpTestClient.proof(poolId, username, WRONG_PASSWORD, + jsonMap(wrong.path("ChallengeParameters"))); + cognitoAction("RespondToAuthChallenge", srpResponse(clientId, wrong, badProof)) + .then().statusCode(400).body("__type", equalTo("NotAuthorizedException")); + + JsonNode right = srpStart(clientId, username); + Map proof = CognitoSrpTestClient.proof(poolId, username, PASSWORD, + jsonMap(right.path("ChallengeParameters"))); + JsonNode done = cognitoJson("RespondToAuthChallenge", srpResponse(clientId, right, proof)); + assertFalse(done.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + + JsonNode events = cognitoJson("AdminListUserAuthEvents", listBody(poolId, username, "")).path("AuthEvents"); + assertEquals(2, events.size()); + assertEquals("Pass", events.get(0).path("EventResponse").asText()); + assertEquals("Fail", events.get(1).path("EventResponse").asText()); + assertChallenges(events.get(1), "Password", "Failure"); + } + + @Test + void recreatedUserStartsWithNoHistory() throws Exception { + String poolId = createEligiblePool("AUDIT"); + String clientId = createClient(poolId); + String username = createUser(poolId); + cognitoJson("InitiateAuth", passwordAuth(clientId, username, PASSWORD)); + listEvents(poolId, username, "").then().body("AuthEvents.size()", equalTo(1)); + + cognitoJson("AdminDeleteUser", """ + {"UserPoolId":"%s","Username":"%s"} + """.formatted(poolId, username)); + createUser(poolId, username); + listEvents(poolId, username, "").then().statusCode(200).body("AuthEvents.size()", equalTo(0)); + } + + @Test + void userAuthChoiceFlowRecordsNothing() throws Exception { + String poolId = createEligiblePool("AUDIT"); + cognitoJson("UpdateUserPool", """ + {"UserPoolId":"%s","UserPoolTier":"PLUS","UserPoolAddOns":{"AdvancedSecurityMode":"AUDIT"}, + "Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD"]}}} + """.formatted(poolId)); + String clientId = cognitoJson("CreateUserPoolClient", """ + {"UserPoolId":"%s","ClientName":"choice", + "ExplicitAuthFlows":["ALLOW_USER_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]} + """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText(); + String username = createUser(poolId); + JsonNode done = cognitoJson("InitiateAuth", """ + {"ClientId":"%s","AuthFlow":"USER_AUTH", + "AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"PASSWORD","PASSWORD":"%s"}} + """.formatted(clientId, username, PASSWORD)); + assertFalse(done.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + listEvents(poolId, username, "").then().statusCode(200).body("AuthEvents.size()", equalTo(0)); + } + + // ──────────────────────────── helpers ──────────────────────────── + + /** A six-digit code that is no valid TOTP for the secret within two steps either side of now. */ + private static String invalidTotpCode(String secret, Instant now) { + for (int i = 0; i < 1_000_000; i++) { + String candidate = String.format(Locale.ROOT, "%06d", i); + if (!CognitoTotp.validCode(secret, candidate, now.minusSeconds(30)) + && !CognitoTotp.validCode(secret, candidate, now) + && !CognitoTotp.validCode(secret, candidate, now.plusSeconds(30))) { + return candidate; + } + } + throw new IllegalStateException("Every six-digit code is valid"); + } + + private static void assertChallenges(JsonNode event, String name, String response) { + assertEquals(1, event.path("ChallengeResponses").size()); + assertEquals(name, event.path("ChallengeResponses").get(0).path("ChallengeName").asText()); + assertEquals(response, event.path("ChallengeResponses").get(0).path("ChallengeResponse").asText()); + } + + private static String createEligiblePool(String mode) throws Exception { + return createPool("\"UserPoolTier\":\"PLUS\",\"UserPoolAddOns\":{\"AdvancedSecurityMode\":\"" + mode + "\"}"); + } + + private static String createPool(String extra) throws Exception { + return cognitoJson("CreateUserPool", """ + {"PoolName":"AuthEvents-%s",%s} + """.formatted(UUID.randomUUID(), extra)).path("UserPool").path("Id").asText(); + } + + private static String createClient(String poolId) throws Exception { + return cognitoJson("CreateUserPoolClient", """ + {"UserPoolId":"%s","ClientName":"auth-events-client", + "ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH", + "ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]} + """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText(); + } + + private static String createUser(String poolId) throws Exception { + String username = "user-" + UUID.randomUUID(); + createUser(poolId, username); + return username; + } + + private static void createUser(String poolId, String username) throws Exception { + cognitoJson("AdminCreateUser", """ + {"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS"} + """.formatted(poolId, username)); + cognitoJson("AdminSetUserPassword", """ + {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true} + """.formatted(poolId, username, PASSWORD)); + } + + private static String passwordAuth(String clientId, String username, String password) { + return """ + {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH", + "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}} + """.formatted(clientId, username, password); + } + + private static String listBody(String poolId, String username, String extra) { + return "{\"UserPoolId\":\"" + poolId + "\",\"Username\":\"" + username + "\"" + + (extra.isEmpty() ? "" : "," + extra) + "}"; + } + + private static Response listEvents(String poolId, String username, String extra) { + return cognitoAction("AdminListUserAuthEvents", listBody(poolId, username, extra)); + } + + private static String mfaResponse(String clientId, JsonNode challenge, String username, String code) { + return """ + {"ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s", + "ChallengeResponses":{"USERNAME":"%s","SOFTWARE_TOKEN_MFA_CODE":"%s"}} + """.formatted(clientId, challenge.path("Session").asText(), username, code); + } + + private static JsonNode srpStart(String clientId, String username) throws Exception { + return cognitoJson("InitiateAuth", """ + {"ClientId":"%s","AuthFlow":"USER_SRP_AUTH", + "AuthParameters":{"USERNAME":"%s","SRP_A":"%s"}} + """.formatted(clientId, username, CognitoSrpTestClient.publicA())); + } + + private static String srpResponse(String clientId, JsonNode challenge, Map proof) { + return """ + {"ClientId":"%s","ChallengeName":"PASSWORD_VERIFIER","Session":"%s", + "ChallengeResponses":{"USERNAME":"%s","PASSWORD_CLAIM_SECRET_BLOCK":"%s", + "PASSWORD_CLAIM_SIGNATURE":"%s","TIMESTAMP":"%s"}} + """.formatted(clientId, challenge.path("Session").asText(), proof.get("USERNAME"), + proof.get("PASSWORD_CLAIM_SECRET_BLOCK"), proof.get("PASSWORD_CLAIM_SIGNATURE"), + proof.get("TIMESTAMP")); + } + + private static Map jsonMap(JsonNode node) { + Map map = new HashMap<>(); + node.fields().forEachRemaining(entry -> map.put(entry.getKey(), entry.getValue().asText())); + return map; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthEventsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthEventsServiceTest.java new file mode 100644 index 0000000000..c17e19d078 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthEventsServiceTest.java @@ -0,0 +1,251 @@ +package io.github.hectorvent.floci.services.cognito; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.acm.AcmService; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthEvent; +import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.UserPool; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Collections; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class CognitoAuthEventsServiceTest { + + private InMemoryStorage authEvents; + private CognitoService service; + + @BeforeEach + void setUp() { + authEvents = new InMemoryStorage<>(); + AcmService acmService = mock(AcmService.class); + CognitoCertificateStubs.everyCertificateIsIssued(acmService); + // A frozen clock: every event is created in the same millisecond, so only the sequence orders them. + Clock frozen = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC); + service = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), authEvents, "http://localhost:4566", null, + new RegionResolver("us-east-1", "000000000000"), null, acmService, null, null, null, frozen, true, + null); + } + + @Test + void onlyPlusWithAuditOrEnforcedRecordsEvents() { + assertFalse(CognitoService.signInEventsEnabled(pool(null, null))); + assertFalse(CognitoService.signInEventsEnabled(pool("ESSENTIALS", "AUDIT"))); + assertFalse(CognitoService.signInEventsEnabled(pool("LITE", "ENFORCED"))); + assertFalse(CognitoService.signInEventsEnabled(pool("PLUS", "OFF"))); + assertFalse(CognitoService.signInEventsEnabled(pool("PLUS", null))); + assertTrue(CognitoService.signInEventsEnabled(pool("PLUS", "AUDIT"))); + assertTrue(CognitoService.signInEventsEnabled(pool("PLUS", "ENFORCED"))); + } + + @Test + void ineligiblePoolRecordsNothing() { + UserPool pool = createPool("ESSENTIALS", "AUDIT"); + CognitoUser user = createUser(pool, "alice"); + + assertNull(service.recordSignInEvent(pool, user, true)); + assertEquals(0, authEvents.keys().size()); + } + + @Test + void eventsCreatedInTheSameMillisecondListNewestFirstAcrossPages() { + UserPool pool = createPool("PLUS", "AUDIT"); + CognitoUser user = createUser(pool, "alice"); + List recorded = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + recorded.add(service.recordSignInEvent(pool, user, i % 2 == 0)); + } + + List listed = new ArrayList<>(); + String token = null; + do { + Map page = service.adminListUserAuthEvents(pool.getId(), "alice", 2, token); + for (Object event : (List) page.get("AuthEvents")) { + listed.add((String) ((Map) event).get("EventId")); + } + token = (String) page.get("NextToken"); + } while (token != null); + + List newestFirst = new ArrayList<>(recorded); + Collections.reverse(newestFirst); + assertEquals(newestFirst, listed); + } + + @Test + void tokenSurvivesAnEventRecordedBetweenPages() { + UserPool pool = createPool("PLUS", "AUDIT"); + CognitoUser user = createUser(pool, "alice"); + String oldest = service.recordSignInEvent(pool, user, true); + String middle = service.recordSignInEvent(pool, user, true); + String newest = service.recordSignInEvent(pool, user, true); + + Map first = service.adminListUserAuthEvents(pool.getId(), "alice", 2, null); + service.recordSignInEvent(pool, user, false); + Map second = service.adminListUserAuthEvents(pool.getId(), "alice", 2, + (String) first.get("NextToken")); + + List secondEvents = (List) second.get("AuthEvents"); + assertEquals(1, secondEvents.size()); + assertEquals(oldest, ((Map) secondEvents.get(0)).get("EventId")); + assertNotNull(middle); + assertNotNull(newest); + assertFalse(second.containsKey("NextToken")); + } + + @Test + void completingAnEventMarksPassAndAddsTheMfaChallenge() { + UserPool pool = createPool("PLUS", "ENFORCED"); + CognitoUser user = createUser(pool, "alice"); + String eventId = service.recordSignInEvent(pool, user, true); + + service.completeSignInEvent(pool.getId(), user, eventId, true); + + List events = (List) service.adminListUserAuthEvents(pool.getId(), "alice", null, null) + .get("AuthEvents"); + Map event = (Map) events.get(0); + assertEquals("Pass", event.get("EventResponse")); + assertEquals(2, ((List) event.get("ChallengeResponses")).size()); + assertFalse(event.containsKey("EventRisk")); + } + + @Test + void deletingTheUserOrThePoolDeletesItsEvents() { + UserPool pool = createPool("PLUS", "AUDIT"); + CognitoUser alice = createUser(pool, "alice"); + CognitoUser bob = createUser(pool, "bob"); + service.recordSignInEvent(pool, alice, true); + service.recordSignInEvent(pool, bob, true); + assertEquals(2, authEvents.keys().size()); + + service.adminDeleteUser(pool.getId(), "alice"); + assertEquals(1, authEvents.keys().size()); + + service.deleteUserPool(pool.getId()); + assertEquals(0, authEvents.keys().size()); + } + + @Test + void delimiterOverlappingSubsKeepTheirOwnEvents() { + UserPool pool = createPool("PLUS", "AUDIT"); + CognitoUser shortSub = createUserWithSub(pool, "short-user", "a"); + CognitoUser longSub = createUserWithSub(pool, "long-user", "a::b"); + String shortEvent = service.recordSignInEvent(pool, shortSub, true); + String longEvent = service.recordSignInEvent(pool, longSub, true); + + assertEquals(List.of(shortEvent), listedEventIds(pool.getId(), "short-user")); + assertEquals(List.of(longEvent), listedEventIds(pool.getId(), "long-user")); + + service.adminDeleteUser(pool.getId(), "short-user"); + + assertEquals(List.of(longEvent), listedEventIds(pool.getId(), "long-user")); + assertEquals(1, authEvents.keys().size()); + } + + @Test + void delimiterOverlappingPoolIdsKeepTheirOwnEvents() { + UserPool outer = createPoolWithId("us-east-1_pool"); + UserPool inner = createPoolWithId("us-east-1_pool::x"); + CognitoUser outerUser = createUserWithSub(outer, "alice", "x::alice"); + CognitoUser innerUser = createUserWithSub(inner, "alice", "alice"); + String outerEvent = service.recordSignInEvent(outer, outerUser, true); + String innerEvent = service.recordSignInEvent(inner, innerUser, true); + + assertEquals(List.of(outerEvent), listedEventIds(outer.getId(), "alice")); + assertEquals(List.of(innerEvent), listedEventIds(inner.getId(), "alice")); + + service.deleteUserPool(outer.getId()); + + assertEquals(List.of(innerEvent), listedEventIds(inner.getId(), "alice")); + assertEquals(1, authEvents.keys().size()); + } + + @Test + void signInEventsOfADeletedUserAreNotRecreated() { + UserPool pool = createPool("PLUS", "AUDIT"); + CognitoUser stale = createUser(pool, "alice"); + String eventId = service.recordSignInEvent(pool, stale, true); + service.adminDeleteUser(pool.getId(), "alice"); + assertEquals(0, authEvents.keys().size()); + + service.completeSignInEvent(pool.getId(), stale, eventId, true); + assertEquals(0, authEvents.keys().size()); + + assertNull(service.recordSignInEvent(pool, stale, true)); + assertEquals(0, authEvents.keys().size()); + } + + @Test + void ineligibleListingFailsBeforeTheUserIsLookedUp() { + UserPool pool = createPool("ESSENTIALS", null); + + AwsException error = assertThrows(AwsException.class, + () -> service.adminListUserAuthEvents(pool.getId(), "nobody", null, null)); + assertEquals("UserPoolAddOnNotEnabledException", error.getErrorCode()); + } + + private UserPool createPool(String tier, String mode) { + Map request = new HashMap<>(); + request.put("PoolName", "events"); + request.put("UserPoolTier", tier); + if (mode != null) { + request.put("UserPoolAddOns", Map.of("AdvancedSecurityMode", mode)); + } + return service.createUserPool(request, "us-east-1"); + } + + private CognitoUser createUser(UserPool pool, String username) { + service.adminCreateUser(pool.getId(), username, Map.of(), "TempPass1!"); + return service.adminGetUser(pool.getId(), username); + } + + private List listedEventIds(String poolId, String username) { + List ids = new ArrayList<>(); + for (Object event : (List) service.adminListUserAuthEvents(poolId, username, null, null) + .get("AuthEvents")) { + ids.add((String) ((Map) event).get("EventId")); + } + return ids; + } + + private UserPool createPoolWithId(String id) { + Map request = new HashMap<>(); + request.put("PoolName", "events"); + request.put("UserPoolTier", "PLUS"); + request.put("UserPoolAddOns", Map.of("AdvancedSecurityMode", "AUDIT")); + request.put("UserPoolTags", new HashMap<>(Map.of("floci:override-id", id))); + return service.createUserPool(request, "us-east-1"); + } + + private CognitoUser createUserWithSub(UserPool pool, String username, String sub) { + service.adminCreateUser(pool.getId(), username, Map.of("sub", sub), "TempPass1!"); + return service.adminGetUser(pool.getId(), username); + } + + private static UserPool pool(String tier, String mode) { + UserPool pool = new UserPool(); + pool.setUserPoolTier(tier); + if (mode != null) { + pool.setUserPoolAddOns(Map.of("AdvancedSecurityMode", mode)); + } + return pool; + } +}