fix: harden authentication and revoke stale sessions
This commit is contained in:
1 parent
c716ec7478
commit
d994ffb9a5
14 files changed
+373
-29
No files matched your search
@@ -67,6 +67,7 @@ public class AuthController {
|
||||
|
||||
@PostMapping("/auth/password-reset")
|
||||
public ResponseEntity<Void> resetPassword(@RequestBody PasswordResetRequest input,HttpServletRequest request) {
|
||||
PasswordPolicy.validate(input.newPassword());
|
||||
String account = verification.consumeReset(input.account(), input.verificationCode());
|
||||
authService.resetPassword(account, input.newPassword(), meta(request));
|
||||
return ResponseEntity.noContent().build();
|
||||
@@ -102,6 +103,7 @@ public class AuthController {
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response
|
||||
) {
|
||||
PasswordPolicy.validate(input.password());
|
||||
verification.consume(input.account(),input.verificationCode());
|
||||
AuthService.AuthResult result = authService.register(
|
||||
input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request)
|
||||
@@ -123,10 +125,12 @@ public class AuthController {
|
||||
}
|
||||
|
||||
@PatchMapping("/auth/account")
|
||||
public Map<String, Object> updateAccount(@RequestBody AccountSettingsRequest input, HttpServletRequest request) {
|
||||
return Map.of("user", authService.updateAccount(
|
||||
public Map<String, Object> updateAccount(@RequestBody AccountSettingsRequest input, HttpServletRequest request, HttpServletResponse response) {
|
||||
var user = authService.updateAccount(
|
||||
sessionToken(request), input.displayName(), input.currentPassword(), input.newPassword(), meta(request)
|
||||
));
|
||||
);
|
||||
if (input.newPassword() != null) response.addHeader(HttpHeaders.SET_COOKIE, sessionCookie("", Duration.ZERO).toString());
|
||||
return Map.of("user", user);
|
||||
}
|
||||
|
||||
@GetMapping("/admin/users")
|
||||
|
||||
@@ -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-]", "");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import com.moyi.controlplane.gateway.GatewayLimitException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
/** Bounds expensive password work for known AND unknown users; counters survive failed-login rollbacks. */
|
||||
final class LoginAttemptLimiter {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate transactions;
|
||||
|
||||
LoginAttemptLimiter(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
if (jdbc.getDataSource() == null) { transactions = null; return; } // Isolated mock-only constructors.
|
||||
transactions = new TransactionTemplate(new DataSourceTransactionManager(jdbc.getDataSource()));
|
||||
transactions.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
}
|
||||
|
||||
void check(String normalizedAccount, String sourceIp) {
|
||||
if (transactions == null) throw new IllegalStateException("Login limiter requires a transactional data source");
|
||||
int retry = transactions.execute(status -> {
|
||||
var limits = Map.of(AuthService.hashSecret("login:account:" + normalizedAccount), 10,
|
||||
AuthService.hashSecret("login:source:" + (sourceIp == null || sourceIp.isBlank() ? "unknown" : sourceIp)), 50);
|
||||
int remaining = 0;
|
||||
// Stable ordering prevents cross-account/source deadlocks on concurrent replicas.
|
||||
for (String bucket : limits.keySet().stream().sorted().toList()) {
|
||||
int limit = limits.get(bucket);
|
||||
var row = jdbc.queryForMap("INSERT INTO auth_login_windows(bucket_hash,attempts) VALUES (?,1) ON CONFLICT(bucket_hash) DO UPDATE SET attempts=CASE WHEN auth_login_windows.expires_at<=clock_timestamp() THEN 1 ELSE LEAST(auth_login_windows.attempts+1,?) END,window_started_at=CASE WHEN auth_login_windows.expires_at<=clock_timestamp() THEN clock_timestamp() ELSE auth_login_windows.window_started_at END,expires_at=CASE WHEN auth_login_windows.expires_at<=clock_timestamp() THEN clock_timestamp()+interval '60 seconds' ELSE auth_login_windows.expires_at END RETURNING attempts,GREATEST(1,CEIL(EXTRACT(EPOCH FROM (expires_at-clock_timestamp()))))::integer AS retry", bucket, limit + 1);
|
||||
if (((Number) row.get("attempts")).intValue() > limit) remaining = Math.max(remaining, ((Number) row.get("retry")).intValue());
|
||||
}
|
||||
jdbc.update("DELETE FROM auth_login_windows WHERE bucket_hash IN (SELECT bucket_hash FROM auth_login_windows WHERE expires_at<clock_timestamp()-interval '5 minutes' LIMIT 500)");
|
||||
return remaining;
|
||||
});
|
||||
if (retry > 0) throw new GatewayLimitException("AUTH_RATE_LIMITED", "登录尝试过于频繁,请稍后重试", 429, retry);
|
||||
}
|
||||
}
|
||||
@@ -30,13 +30,17 @@ public class PasswordHasher {
|
||||
|
||||
public boolean matches(String password, String encoded) {
|
||||
try {
|
||||
// Accept existing bounded legacy passwords, but never let malformed hashes choose unbounded KDF work.
|
||||
if (password == null || password.length() > 4096 || encoded == null || encoded.length() > 1024) return false;
|
||||
String[] parts = encoded.split("\\$");
|
||||
if (parts.length != 4 || !"pbkdf2".equals(parts[0])) {
|
||||
return false;
|
||||
}
|
||||
int iterations = Integer.parseInt(parts[1]);
|
||||
if (iterations < 10_000 || iterations > 1_000_000) return false;
|
||||
byte[] salt = Base64.getUrlDecoder().decode(parts[2]);
|
||||
byte[] expected = Base64.getUrlDecoder().decode(parts[3]);
|
||||
if (salt.length < 16 || salt.length > 64 || expected.length != KEY_LENGTH / 8) return false;
|
||||
byte[] actual = derive(password, salt, iterations, expected.length * 8);
|
||||
return MessageDigest.isEqual(expected, actual);
|
||||
} catch (RuntimeException exception) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
|
||||
/** One issuance policy for every role; do not silently trim or truncate passwords. */
|
||||
public final class PasswordPolicy {
|
||||
private PasswordPolicy() {}
|
||||
public static void validate(String password) {
|
||||
if (password == null || password.isBlank() || password.length() < 8 || password.length() > 256) {
|
||||
throw new ApiException("WEAK_PASSWORD", "所有账号的新密码长度须为 8 至 256 位,不能仅含空白", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ moyi:
|
||||
secure-cookie: ${AUTH_SECURE_COOKIE:false}
|
||||
bootstrap:
|
||||
admin-account: ${ADMIN_ACCOUNT:adimin}
|
||||
admin-password: ${ADMIN_PASSWORD:admin123}
|
||||
admin-password: ${ADMIN_PASSWORD:}
|
||||
admin-display-name: ${ADMIN_DISPLAY_NAME:平台管理员}
|
||||
credentials:
|
||||
encryption-key: ${CREDENTIAL_ENCRYPTION_KEY:}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
-- Shared across replicas. Raw accounts, IPs and passwords are never written here.
|
||||
CREATE TABLE auth_login_windows (
|
||||
bucket_hash varchar(64) PRIMARY KEY CHECK (bucket_hash ~ '^[0-9a-f]{64}$'),
|
||||
window_started_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
expires_at timestamptz NOT NULL DEFAULT (clock_timestamp()+interval '60 seconds'),
|
||||
attempts integer NOT NULL CHECK (attempts BETWEEN 1 AND 1000)
|
||||
);
|
||||
CREATE INDEX auth_login_windows_expiry_idx ON auth_login_windows(expires_at);
|
||||
Reference in new issue
Block a user