diff --git a/ROADMAP.md b/ROADMAP.md index 57a624f..aeb840e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -78,8 +78,9 @@ server checklist is in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTING.md). - [x] Session restore skips suspended and permanently locked accounts and checks every session of the player. - [ ] Proxy forwarding is detected by a heuristic (shared local address), not by reading the proxy settings. - [ ] Config and database file permissions, and plaintext webhook and bot tokens in `config.yml`. -- [ ] Audit events defined but never written (`LOGIN_FAILURE`, `ACCOUNT_LOCKED`, `ADMIN_ACTION`, - `SESSION_REVOKED`); audit write errors are swallowed. +- [x] Audit events: `ACCOUNT_LOCKED` is written by the password or 2FA failure that locks the account, + `SESSION_REVOKED` by `/sessions revoke`; `LOGIN_FAILURE` was removed (failures are in `login_attempts` + with their reason). A failed audit write is logged as a warning and never fails the login itself. - [x] Tests: mixin parity across the 17 Fabric targets (`MixinAuditTest`); concurrent registration on a real PostgreSQL (`PostgresIntegrationTest`, runs in CI). - [ ] Tests: Paper and Fabric restriction parity. diff --git a/core/src/main/java/io/github/touchfalls/authsecured/application/AuthService.java b/core/src/main/java/io/github/touchfalls/authsecured/application/AuthService.java index ad7be08..6f62718 100644 --- a/core/src/main/java/io/github/touchfalls/authsecured/application/AuthService.java +++ b/core/src/main/java/io/github/touchfalls/authsecured/application/AuthService.java @@ -220,6 +220,17 @@ private static String actorMetadata(UUID actor, String unregistered) { + (unregistered == null ? "" : ",\"unregistered\":\"" + unregistered + "\"") + "}"; } + /** {@code /sessions revoke}: ends every saved session of the player's account and audits it. */ + public CompletableFuture revokeSavedSessions(UUID playerUuid) { + return sessionService.revokeActiveSessionForPlayer(playerUuid) + .thenCompose(v -> accountRepository.findByUuid(playerUuid) + .thenCompose(account -> account.isEmpty() ? CompletableFuture.completedFuture(null) + : securityService.logSecurityEvent(account.get().getId(), + SecurityEventType.SESSION_REVOKED, null, "{}")) + // The sessions are already gone; a failed audit write must not report the command as failed. + .exceptionally(error -> null)); + } + public SessionService getSessionService() { return sessionService; } diff --git a/core/src/main/java/io/github/touchfalls/authsecured/application/LoginService.java b/core/src/main/java/io/github/touchfalls/authsecured/application/LoginService.java index 789572f..81d78d5 100644 --- a/core/src/main/java/io/github/touchfalls/authsecured/application/LoginService.java +++ b/core/src/main/java/io/github/touchfalls/authsecured/application/LoginService.java @@ -266,6 +266,9 @@ private CompletableFuture evaluate(Account account, boolean val } if (!valid) { securityNotifier.loginFailure(alertName, "INVALID_PASSWORD"); + // shortcut: predicted from the snapshot read before the hash check; checks for one player run one + // at a time, so only two players typing the same name at once could miss or double the event. + boolean locks = account.nextFailureLocks(maxFailedAttempts, now); return accountRepository.incrementFailedAttemptsAtomic( account.getId(), maxFailedAttempts, lockDurationSeconds, now) .thenCompose(updated -> updated @@ -273,6 +276,9 @@ private CompletableFuture evaluate(Account account, boolean val : CompletableFuture.failedFuture(new IllegalStateException("Account disappeared"))) .thenCompose(v -> rateLimitService.recordFailedLoginAttempt(normalized, ipHash)) .thenCompose(v -> securityService.logLoginAttempt(account.getId(), ipHash, false, "INVALID_PASSWORD")) + .thenCompose(v -> locks ? securityService.logSecurityEvent( + account.getId(), SecurityEventType.ACCOUNT_LOCKED, ipHash, "{}") + : CompletableFuture.completedFuture(null)) .thenApply(v -> rejected(AuthResult.INVALID_PASSWORD, normalized)); } if (account.isTemporaryPasswordExpired(now)) { diff --git a/core/src/main/java/io/github/touchfalls/authsecured/application/TwoFactorService.java b/core/src/main/java/io/github/touchfalls/authsecured/application/TwoFactorService.java index d6b6c29..53ba563 100644 --- a/core/src/main/java/io/github/touchfalls/authsecured/application/TwoFactorService.java +++ b/core/src/main/java/io/github/touchfalls/authsecured/application/TwoFactorService.java @@ -186,10 +186,15 @@ private CompletableFuture checkCode(Account account, TotpRepository.Sta } private CompletableFuture recordFailure(Account account, byte[] ipHash) { + Instant now = Instant.now(); + boolean locks = account.nextFailureLocks(maxFailedAttempts, now); // same shortcut as in LoginService return accountRepository.incrementFailedAttemptsAtomic( - account.getId(), maxFailedAttempts, lockDurationSeconds, Instant.now()) + account.getId(), maxFailedAttempts, lockDurationSeconds, now) .thenCompose(v -> rateLimitService.recordFailedLoginAttempt(account.getUsernameNormalized(), ipHash)) .thenCompose(v -> securityService.logLoginAttempt(account.getId(), ipHash, false, "INVALID_TWO_FACTOR_CODE")) + .thenCompose(v -> locks ? securityService.logSecurityEvent( + account.getId(), SecurityEventType.ACCOUNT_LOCKED, ipHash, "{}") + : CompletableFuture.completedFuture(null)) .thenApply(v -> Outcome.of(Status.INVALID_CODE)); } diff --git a/core/src/main/java/io/github/touchfalls/authsecured/application/UnifiedCommandServiceImpl.java b/core/src/main/java/io/github/touchfalls/authsecured/application/UnifiedCommandServiceImpl.java index 4bd8db3..9eed048 100644 --- a/core/src/main/java/io/github/touchfalls/authsecured/application/UnifiedCommandServiceImpl.java +++ b/core/src/main/java/io/github/touchfalls/authsecured/application/UnifiedCommandServiceImpl.java @@ -337,7 +337,7 @@ public CompletableFuture executeSessions(UUID playerUuid, boolean revoke) } SessionService sessions = authService.getSessionService(); CompletableFuture message = revoke - ? sessions.revokeActiveSessionForPlayer(playerUuid) + ? authService.revokeSavedSessions(playerUuid) .thenApply(ignored -> localizationManager.getMessage("messages.sessions-revoked", "&aAll saved sessions were ended. You stay logged in on this connection.")) : sessions.countActiveSessions(playerUuid) diff --git a/core/src/main/java/io/github/touchfalls/authsecured/domain/account/Account.java b/core/src/main/java/io/github/touchfalls/authsecured/domain/account/Account.java index 52543a9..6aba3d7 100644 --- a/core/src/main/java/io/github/touchfalls/authsecured/domain/account/Account.java +++ b/core/src/main/java/io/github/touchfalls/authsecured/domain/account/Account.java @@ -62,6 +62,17 @@ public boolean isLocked(Instant currentTime) { return false; } + /** + * Whether one more failure locks the account, by the same rule as + * {@code AccountRepository.incrementFailedAttemptsAtomic}: an expired lock restarts the count at 1. + */ + public boolean nextFailureLocks(int maxAttempts, Instant currentTime) { + if (status == AccountStatus.SUSPENDED) return false; + boolean lockExpired = status == AccountStatus.LOCKED && lockedUntil != null + && !currentTime.isBefore(lockedUntil); + return (lockExpired ? 1 : failedLoginAttempts + 1) >= maxAttempts; + } + public void recordFailedAttempt(int maxAttempts, long lockDurationSeconds, Instant currentTime) { this.failedLoginAttempts++; this.updatedAt = currentTime; diff --git a/core/src/main/java/io/github/touchfalls/authsecured/domain/security/SecurityEventType.java b/core/src/main/java/io/github/touchfalls/authsecured/domain/security/SecurityEventType.java index 0bf823e..ffb5fb8 100644 --- a/core/src/main/java/io/github/touchfalls/authsecured/domain/security/SecurityEventType.java +++ b/core/src/main/java/io/github/touchfalls/authsecured/domain/security/SecurityEventType.java @@ -7,7 +7,6 @@ public enum SecurityEventType { LOGIN_NEW_ADDRESS, TWO_FACTOR_ENABLED, TWO_FACTOR_DISABLED, - LOGIN_FAILURE, PASSWORD_CHANGE, ACCOUNT_LOCKED, ACCOUNT_UNLOCKED, diff --git a/core/src/test/java/io/github/touchfalls/authsecured/AccountLockStateTest.java b/core/src/test/java/io/github/touchfalls/authsecured/AccountLockStateTest.java index c4dc39c..4cbae65 100644 --- a/core/src/test/java/io/github/touchfalls/authsecured/AccountLockStateTest.java +++ b/core/src/test/java/io/github/touchfalls/authsecured/AccountLockStateTest.java @@ -8,6 +8,8 @@ import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class AccountLockStateTest { @Test @@ -24,4 +26,21 @@ void handlesEveryStatusAndLockExpiryCombination() { } } } + + @Test + void nextFailureLocksFollowsTheAtomicIncrementRule() { + Instant now = Instant.now(); + assertFalse(account(AccountStatus.ACTIVE, 3, null, now).nextFailureLocks(5, now)); + assertTrue(account(AccountStatus.ACTIVE, 4, null, now).nextFailureLocks(5, now)); + // An expired lock restarts the count at 1 instead of re-locking right away. + assertFalse(account(AccountStatus.LOCKED, 5, now.minusSeconds(1), now).nextFailureLocks(5, now)); + assertTrue(account(AccountStatus.LOCKED, 5, now.minusSeconds(1), now).nextFailureLocks(1, now)); + // A suspension is never turned into a lock. + assertFalse(account(AccountStatus.SUSPENDED, 4, null, now).nextFailureLocks(5, now)); + } + + private static Account account(AccountStatus status, int failures, Instant until, Instant now) { + return new Account(1L, UUID.randomUUID(), "Player", "player", "hash", status, failures, until, + now, now, null, now); + } } diff --git a/core/src/test/java/io/github/touchfalls/authsecured/AuthServiceSecurityTest.java b/core/src/test/java/io/github/touchfalls/authsecured/AuthServiceSecurityTest.java index 64f9b94..c2b5dbd 100644 --- a/core/src/test/java/io/github/touchfalls/authsecured/AuthServiceSecurityTest.java +++ b/core/src/test/java/io/github/touchfalls/authsecured/AuthServiceSecurityTest.java @@ -183,4 +183,28 @@ private static SecurityService auditSink() { .thenReturn(CompletableFuture.completedFuture(null)); return security; } + + @Test + void revokingSavedSessionsIsAuditedAndAFailedAuditDoesNotFailTheCommand() { + SessionService sessions = mock(SessionService.class); + SecurityService security = mock(SecurityService.class); + AccountRepository accounts = mock(AccountRepository.class); + UUID uuid = UUID.randomUUID(); + Instant now = Instant.now(); + Account account = new Account(9L, uuid, "Player", "player", "hash", + io.github.touchfalls.authsecured.domain.account.AccountStatus.ACTIVE, 0, null, now, now, null, now); + when(sessions.revokeActiveSessionForPlayer(uuid)).thenReturn(CompletableFuture.completedFuture(null)); + when(accounts.findByUuid(uuid)).thenReturn(CompletableFuture.completedFuture(Optional.of(account))); + when(security.logSecurityEvent(any(), any(), any(), anyString())) + .thenReturn(CompletableFuture.completedFuture(null)); + AuthService service = new AuthService(mock(RegistrationService.class), mock(LoginService.class), + mock(PasswordService.class), sessions, security, accounts); + + service.revokeSavedSessions(uuid).join(); + verify(sessions).revokeActiveSessionForPlayer(uuid); + verify(security).logSecurityEvent(9L, SecurityEventType.SESSION_REVOKED, null, "{}"); + + when(accounts.findByUuid(uuid)).thenReturn(CompletableFuture.failedFuture(new IllegalStateException("db"))); + service.revokeSavedSessions(uuid).join(); + } } diff --git a/core/src/test/java/io/github/touchfalls/authsecured/LoginServiceSecurityTest.java b/core/src/test/java/io/github/touchfalls/authsecured/LoginServiceSecurityTest.java index 0fa6d27..3d80bd4 100644 --- a/core/src/test/java/io/github/touchfalls/authsecured/LoginServiceSecurityTest.java +++ b/core/src/test/java/io/github/touchfalls/authsecured/LoginServiceSecurityTest.java @@ -88,6 +88,42 @@ void lockedAccountAnswersIdenticallyForWrongAndCorrectPasswords() { } } + @Test + void theFailureThatLocksTheAccountIsAudited() { + for (int previousFailures : new int[]{3, 4}) { + AccountRepository accounts = mock(AccountRepository.class); + PasswordService passwords = mock(PasswordService.class); + RateLimitService limits = mock(RateLimitService.class); + SecurityService security = mock(SecurityService.class); + UUID uuid = UUID.randomUUID(); + Instant now = Instant.now(); + Account account = new Account(7L, uuid, "Player", "player", "hash", + io.github.touchfalls.authsecured.domain.account.AccountStatus.ACTIVE, + previousFailures, null, now, now, null, now); + + when(limits.isIpRateLimited(any())).thenReturn(CompletableFuture.completedFuture(false)); + when(limits.isAccountRateLimited(anyString())).thenReturn(CompletableFuture.completedFuture(false)); + when(limits.recordFailedLoginAttempt(anyString(), any())).thenReturn(CompletableFuture.completedFuture(null)); + when(security.logLoginAttempt(any(), any(), anyBoolean(), anyString())) + .thenReturn(CompletableFuture.completedFuture(null)); + when(security.logSecurityEvent(any(), any(), any(), anyString())) + .thenReturn(CompletableFuture.completedFuture(null)); + when(accounts.findByUuid(uuid)).thenReturn(CompletableFuture.completedFuture(Optional.of(account))); + when(accounts.incrementFailedAttemptsAtomic(any(), anyInt(), anyLong(), any())) + .thenReturn(CompletableFuture.completedFuture(true)); + when(passwords.verifyPasswordAsync(any(), eq("hash"))).thenReturn(CompletableFuture.completedFuture(false)); + + LoginService service = new LoginService(accounts, passwords, limits, + mock(SessionService.class), security, 5, 900); + + assertEquals(AuthResult.INVALID_PASSWORD, + service.login(uuid, "Player", "guess".toCharArray(), new byte[]{1}).join()); + verify(security, times(previousFailures == 4 ? 1 : 0)).logSecurityEvent(7L, + io.github.touchfalls.authsecured.domain.security.SecurityEventType.ACCOUNT_LOCKED, + new byte[]{1}, "{}"); + } + } + @Test void failuresWithoutAnAccountNeverCountAgainstTheNamedAccount() { AccountRepository accounts = mock(AccountRepository.class); diff --git a/core/src/test/java/io/github/touchfalls/authsecured/UnifiedCommandServiceTest.java b/core/src/test/java/io/github/touchfalls/authsecured/UnifiedCommandServiceTest.java index 08d3595..8f8f024 100644 --- a/core/src/test/java/io/github/touchfalls/authsecured/UnifiedCommandServiceTest.java +++ b/core/src/test/java/io/github/touchfalls/authsecured/UnifiedCommandServiceTest.java @@ -229,13 +229,13 @@ void sessionsShowsCountAndRevokeKeepsTheConnectionAuthenticated() { when(authService.getSessionService()).thenReturn(sessionService); when(restrictionAdapter.isAuthenticated(playerUuid)).thenReturn(true); when(sessionService.countActiveSessions(playerUuid)).thenReturn(CompletableFuture.completedFuture(3)); - when(sessionService.revokeActiveSessionForPlayer(playerUuid)).thenReturn(CompletableFuture.completedFuture(null)); + when(authService.revokeSavedSessions(playerUuid)).thenReturn(CompletableFuture.completedFuture(null)); commandExecutor.executeSessions(playerUuid, false).join(); verify(platform).sendMessage(eq(playerUuid), contains("3")); commandExecutor.executeSessions(playerUuid, true).join(); - verify(sessionService).revokeActiveSessionForPlayer(playerUuid); + verify(authService).revokeSavedSessions(playerUuid); verify(restrictionAdapter, never()).setPlayerUnauthenticated(any(), any()); }