fix: harden authentication and revoke stale sessions

This commit is contained in:
xpp committed 2026-10-21 22:05:43 +08:00
1 parent c716ec7478
commit d994ffb9a5
14 files changed
+373 -29

No files matched your search

@@ -24,6 +24,8 @@ import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
@Service
public class AuthService {
@@ -34,6 +36,10 @@ public class AuthService {
private final ObjectMapper objectMapper;
private final int sessionTtlHours;
private final SecretCipher secretCipher;
private final LoginAttemptLimiter loginAttempts;
private final TransactionTemplate loginTransactions;
// Valid PBKDF2 shape for comparable unknown-account work; this is not a usable user credential.
private static final String UNKNOWN_PASSWORD_HASH = "pbkdf2$210000$AAECAwQFBgcICQoLDA0ODw$_ZW4zVJDiheXQ51WuP_SSr_f8xjYJXBHvjkzLlPtFHo";
@Autowired private TotpService totp;
/** Kept for isolated unit tests that do not exercise encrypted invitation display. */
@@ -59,6 +65,8 @@ public class AuthService {
this.objectMapper = objectMapper;
this.sessionTtlHours = sessionTtlHours;
this.secretCipher = secretCipher;
this.loginAttempts = new LoginAttemptLimiter(jdbc);
this.loginTransactions = jdbc.getDataSource() == null ? null : new TransactionTemplate(new DataSourceTransactionManager(jdbc.getDataSource()));
}
public record UserView(
@@ -91,7 +99,7 @@ public class AuthService {
@Transactional
public void ensureAdmin(String accountInput, String password, String displayName) {
String account = normalizeAccount(accountInput);
if (account.isBlank() || password == null || password.isBlank()) {
if (account.isBlank()) {
throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500);
}
// Serialize bootstrap across replicas, including the first creation.
@@ -112,6 +120,10 @@ public class AuthService {
return;
}
OffsetDateTime now = now();
PasswordPolicy.validate(password);
if (java.util.Set.of("admin123", "generate_admin_password", "replace-with-a-strong-initial-password").contains(password.strip().toLowerCase(Locale.ROOT))) {
throw new ApiException("INVALID_ADMIN_CONFIG", "首次启动必须配置非默认、非示例占位的管理员密码", 500);
}
jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'super_admin', 'active', ?, ?)",
UUID.randomUUID(), account, accountKind(account), passwordHasher.hash(password),
@@ -123,18 +135,36 @@ public class AuthService {
return login(accountInput,password,null,meta);
}
public AuthResult login(String accountInput,String password,String otp,RequestMeta meta) {
UserRow user = findUserByAccount(normalizeAccount(accountInput));
if (user == null || !passwordHasher.matches(password, user.passwordHash())) {
String account = normalizeAccount(accountInput);
if (account.length() > 320 || password == null || password.length() > 4096) throw new ApiException("INVALID_CREDENTIALS", "账号或密码错误", 401);
loginAttempts.check(account, meta == null ? null : meta.ipAddress());
// Acquire the row lock only AFTER the independently committed limiter. Do not hold a pool
// connection while asking REQUIRES_NEW for another connection under concurrent login load.
if (loginTransactions == null) throw new IllegalStateException("Login requires a transactional data source");
LoginOutcome outcome = loginTransactions.execute(status -> authenticateLocked(account, password, otp, meta));
if (outcome.error() != null) throw outcome.error();
return outcome.result();
}
private record LoginOutcome(AuthResult result, ApiException error) {}
private LoginOutcome authenticateLocked(String account, String password, String otp, RequestMeta meta) {
UserRow user = findUserByAccountLocked(account);
boolean matches = passwordHasher.matches(password, user == null ? UNKNOWN_PASSWORD_HASH : user.passwordHash());
if (user == null || !matches) {
throw new ApiException("INVALID_CREDENTIALS", "账号或密码错误", 401);
}
if (!"active".equals(user.status())) {
throw new ApiException("ACCOUNT_DISABLED", "账号已停用", 403);
}
if(totp!=null) totp.verifyLogin(user.id(),otp);
if(totp!=null) {
try { totp.verifyLogin(user.id(),otp); }
catch (ApiException exception) { return new LoginOutcome(null, exception); } // Persist MFA failure/replay counters.
}
OffsetDateTime loginAt = now();
jdbc.update("UPDATE users SET last_login_at = ?, updated_at = ? WHERE id = ?", loginAt, loginAt, user.id());
audit("user.logged_in", user.id(), meta, Map.of());
return new AuthResult(createSession(user.id(), meta), toView(user, loginAt));
return new LoginOutcome(new AuthResult(createSession(user.id(), meta), toView(user, loginAt)), null);
}
public void verifyPassword(UUID userId,String password) {
String hash=jdbc.queryForObject("SELECT password_hash FROM users WHERE id=? AND status='active'",String.class,userId);
@@ -151,9 +181,7 @@ public class AuthService {
) {
String account = normalizeAccount(accountInput);
validatePublicAccount(account);
if (password == null || password.length() < 8) {
throw new ApiException("WEAK_PASSWORD", "密码至少需要 8 位");
}
PasswordPolicy.validate(password);
if (invitationCode == null || invitationCode.isBlank()) {
throw new ApiException("INVITATION_REQUIRED", "第一版注册需要邀请码");
}
@@ -177,6 +205,7 @@ public class AuthService {
}
UUID userId = UUID.randomUUID();
String name = displayName == null || displayName.isBlank() ? defaultDisplayName(account) : displayName.trim();
if (name.length() > 80) throw new ApiException("INVALID_NAME", "显示名称最多 80 字符", 400);
jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'user', 'active', ?, ?)",
userId, account, accountKind(account), passwordHasher.hash(password), name, now, now
@@ -242,22 +271,23 @@ public class AuthService {
String newPassword,
RequestMeta meta
) {
UserRow user = requireUserRow(token);
UserRow authenticated = requireUserRow(token);
jdbc.queryForList("SELECT id FROM users WHERE id=? FOR UPDATE", authenticated.id());
UserRow user = requireUserRow(token); // Recheck after any concurrent password change revoked this session.
String displayName = displayNameInput == null ? user.displayName() : displayNameInput.trim();
if (displayName.isBlank() || displayName.length() > 80) {
throw new ApiException("INVALID_NAME", "显示名称不能为空且最多 80 字符", 400);
}
boolean changingPassword = newPassword != null && !newPassword.isBlank();
boolean changingPassword = newPassword != null;
if (changingPassword) {
if (currentPassword == null || currentPassword.isBlank() || !passwordHasher.matches(currentPassword, user.passwordHash())) {
throw new ApiException("INVALID_CURRENT_PASSWORD", "当前密码错误", 403);
}
if (newPassword.length() > 256 || (!"super_admin".equals(user.role()) && newPassword.length() < 8)) {
throw new ApiException("WEAK_PASSWORD", "普通用户新密码长度为 8 至 256 位", 400);
}
PasswordPolicy.validate(newPassword);
}
if (changingPassword) {
jdbc.update("UPDATE users SET display_name = ?, password_hash = ?, updated_at = ? WHERE id = ?", displayName, passwordHasher.hash(newPassword), now(), user.id());
jdbc.update("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", now(), user.id());
} else {
jdbc.update("UPDATE users SET display_name = ?, updated_at = ? WHERE id = ?", displayName, now(), user.id());
}
@@ -268,14 +298,11 @@ public class AuthService {
@Transactional
public void resetPassword(String accountInput, String newPassword, RequestMeta meta) {
String account = normalizeAccount(accountInput);
UserRow user = findUserByAccount(account);
UserRow user = findUserByAccountLocked(account);
if (user == null || !"active".equals(user.status())) {
throw new ApiException("ACCOUNT_NOT_FOUND", "账号不存在或已停用", 404);
}
if (newPassword == null || newPassword.isBlank() || newPassword.length() > 256
|| (!"super_admin".equals(user.role()) && newPassword.length() < 8)) {
throw new ApiException("WEAK_PASSWORD", "普通用户新密码长度为 8 至 256 位", 400);
}
PasswordPolicy.validate(newPassword);
OffsetDateTime changedAt = now();
jdbc.update("UPDATE users SET password_hash=?, updated_at=? WHERE id=?", passwordHasher.hash(newPassword), changedAt, user.id());
jdbc.update("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", changedAt, user.id());
@@ -312,7 +339,7 @@ public class AuthService {
UserView actor=requireAdmin(token);
String account=normalizeAccount(accountInput);
if(account.isBlank() || account.length()>254 || (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches() && !account.matches("[a-z0-9_]{3,64}"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱、手机号或 3 至 64 位字母数字下划线用户名");
if(password==null || password.length()<8 || password.length()>256) throw new ApiException("WEAK_PASSWORD","普通用户密码长度为 8 至 256 位");
PasswordPolicy.validate(password);
if(findUserByAccount(account)!=null) throw new ApiException("ACCOUNT_EXISTS","账号已存在",409);
String name=displayName==null || displayName.isBlank()?defaultDisplayName(account):displayName.trim();
if(name.length()>80) throw new ApiException("INVALID_NAME","显示名称最多 80 字符");
@@ -446,6 +473,11 @@ public class AuthService {
}
}
private UserRow findUserByAccountLocked(String account) {
try { return jdbc.queryForObject("SELECT * FROM users WHERE account=? FOR UPDATE", this::mapUser, account); }
catch (EmptyResultDataAccessException exception) { return null; }
}
private UserRow findUserById(UUID id) {
return jdbc.queryForObject("SELECT * FROM users WHERE id = ?", this::mapUser, id);
}
@@ -511,13 +543,13 @@ public class AuthService {
}
private void validatePublicAccount(String account) {
if (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches()) {
if (account.length() > 254 || (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches())) {
throw new ApiException("INVALID_ACCOUNT", "请输入有效的邮箱或手机号");
}
}
private String normalizeAccount(String account) {
String normalized = account == null ? "" : account.trim().toLowerCase();
String normalized = account == null ? "" : account.trim().toLowerCase(Locale.ROOT);
return normalized.contains("@") ? normalized : normalized.replaceAll("[\\s-]", "");
}