Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void> revokeSavedSessions(UUID playerUuid) {
return sessionService.revokeActiveSessionForPlayer(playerUuid)
.thenCompose(v -> accountRepository.findByUuid(playerUuid)
.thenCompose(account -> account.isEmpty() ? CompletableFuture.<Void>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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,13 +266,19 @@ private CompletableFuture<CredentialCheck> 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
? CompletableFuture.completedFuture(null)
: 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.<Void>completedFuture(null))
.thenApply(v -> rejected(AuthResult.INVALID_PASSWORD, normalized));
}
if (account.isTemporaryPasswordExpired(now)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,15 @@ private CompletableFuture<Boolean> checkCode(Account account, TotpRepository.Sta
}

private CompletableFuture<Outcome> 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.<Void>completedFuture(null))
.thenApply(v -> Outcome.of(Status.INVALID_CODE));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ public CompletableFuture<Void> executeSessions(UUID playerUuid, boolean revoke)
}
SessionService sessions = authService.getSessionService();
CompletableFuture<String> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ public enum SecurityEventType {
LOGIN_NEW_ADDRESS,
TWO_FACTOR_ENABLED,
TWO_FACTOR_DISABLED,
LOGIN_FAILURE,
PASSWORD_CHANGE,
ACCOUNT_LOCKED,
ACCOUNT_UNLOCKED,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

Expand Down
Loading