diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java index 2c07148..6fbaf76 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java @@ -67,6 +67,7 @@ public class AuthController { @PostMapping("/auth/password-reset") public ResponseEntity 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 updateAccount(@RequestBody AccountSettingsRequest input, HttpServletRequest request) { - return Map.of("user", authService.updateAccount( + public Map 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") diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java index 2e09582..0e1d4f1 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java @@ -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-]", ""); } diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/LoginAttemptLimiter.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/LoginAttemptLimiter.java new file mode 100644 index 0000000..35256bc --- /dev/null +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/LoginAttemptLimiter.java @@ -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 0) throw new GatewayLimitException("AUTH_RATE_LIMITED", "登录尝试过于频繁,请稍后重试", 429, retry); + } +} diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordHasher.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordHasher.java index b13363f..f081481 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordHasher.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordHasher.java @@ -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) { diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordPolicy.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordPolicy.java new file mode 100644 index 0000000..4fbd11a --- /dev/null +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/PasswordPolicy.java @@ -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); + } + } +} diff --git a/control-plane-java/src/main/resources/application.yml b/control-plane-java/src/main/resources/application.yml index 00e5aee..7da0b26 100644 --- a/control-plane-java/src/main/resources/application.yml +++ b/control-plane-java/src/main/resources/application.yml @@ -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:} diff --git a/control-plane-java/src/main/resources/db/migration/V49__authentication_attempt_limits.sql b/control-plane-java/src/main/resources/db/migration/V49__authentication_attempt_limits.sql new file mode 100644 index 0000000..52a719a --- /dev/null +++ b/control-plane-java/src/main/resources/db/migration/V49__authentication_attempt_limits.sql @@ -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); diff --git a/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthRolesTest.java b/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthRolesTest.java index 4d166ee..a0698ac 100644 --- a/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthRolesTest.java +++ b/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthRolesTest.java @@ -32,6 +32,15 @@ class AuthRolesTest { verify(hasher).hash("test-password"); } + @Test + void firstBootstrapCannotUsePublishedDefaultsOrExamplePlaceholders() { + for (String password : List.of("admin123", "GENERATE_ADMIN_PASSWORD", "replace-with-a-strong-initial-password")) { + assertEquals("INVALID_ADMIN_CONFIG", assertThrows(ApiException.class, () -> auth.ensureAdmin("adimin", password, "Owner")).getCode()); + } + verify(jdbc, never()).update(anyString(), any(Object[].class)); + verifyNoInteractions(hasher); + } + @Test void bootstrapPromotesLegacyAdminWithoutReplacingPassword() throws Exception { lookupUser(ownerId, "admin"); diff --git a/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthSecurityPostgresTest.java b/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthSecurityPostgresTest.java new file mode 100644 index 0000000..e689b43 --- /dev/null +++ b/control-plane-java/src/test/java/com/moyi/controlplane/auth/AuthSecurityPostgresTest.java @@ -0,0 +1,178 @@ +package com.moyi.controlplane.auth; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.moyi.controlplane.common.ApiException; +import com.moyi.controlplane.common.ApiExceptionHandler; +import com.moyi.controlplane.security.SecretCipher; +import jakarta.servlet.http.Cookie; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@EnabledIfEnvironmentVariable(named="MOYI_AUTH_TEST_JDBC_URL", matches="jdbc:postgresql://127\\.0\\.0\\.1:[0-9]+/.+") +class AuthSecurityPostgresTest { + @Configuration @EnableTransactionManagement(proxyTargetClass=true) static class Transactions {} + private final UUID userId = UUID.randomUUID(); + private final ObjectMapper json = new ObjectMapper().findAndRegisterModules(); + private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "isolated-security-test"); + private DriverManagerDataSource base, source; + private String schema; + private JdbcTemplate jdbc; + private AnnotationConfigApplicationContext context; + private AuthService auth; + private PasswordHasher hasher; + private MockMvc http; + + @BeforeEach void setup() { + String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL"); + schema = "auth_security_" + UUID.randomUUID().toString().replace("-", ""); + base = new DriverManagerDataSource(url, "moyi_role_test", ""); + source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", ""); + Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate(); + jdbc = new JdbcTemplate(source); hasher = spy(new PasswordHasher("isolated-pepper")); + jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role) VALUES (?,'security_member','username',?,'Test','super_admin')", userId, hasher.hash("original-password")); + context = new AnnotationConfigApplicationContext(); + context.register(Transactions.class); + context.registerBean(DataSource.class, () -> source); + context.registerBean(DataSourceTransactionManager.class, () -> new DataSourceTransactionManager(source)); + context.registerBean(AuthService.class, () -> new AuthService(jdbc, hasher, json, 168)); + context.registerBean(TotpService.class, () -> new TotpService(jdbc, new SecretCipher("isolated-mfa-key"))); + context.refresh(); auth = context.getBean(AuthService.class); + http = MockMvcBuilders.standaloneSetup(new AuthController(auth, mock(VerificationService.class), 168, true)).setControllerAdvice(new ApiExceptionHandler()).build(); + } + + @AfterEach void cleanup() { + if (context != null) context.close(); + if (base != null && schema != null) new JdbcTemplate(base).execute("DROP SCHEMA " + schema + " CASCADE"); + } + private String session() { return auth.login("security_member", "original-password", meta).token(); } + + @Test void passwordChangeRevokesEverySessionAndClearsTheBrowserCookie() throws Exception { + String first = session(), second = session(); + http.perform(patch("/api/auth/account").cookie(new Cookie("moyi_session", first)).contentType("application/json") + .content("{\"displayName\":\"Test\",\"currentPassword\":\"original-password\",\"newPassword\":\"replacement-password\"}")) + .andExpect(status().isOk()).andExpect(cookie().maxAge("moyi_session", 0)); + assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(first)).getStatus()); + assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(second)).getStatus()); + assertEquals(401, assertThrows(ApiException.class, () -> session()).getStatus()); + assertNotNull(auth.login("security_member", "replacement-password", meta).token()); + } + + @Test void allRolesHaveTheSamePasswordBoundsAndProfileOnlySaveKeepsSessions() { + String token = session(); + assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> auth.updateAccount(token, "Test", "original-password", "x", meta)).getCode()); + assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> auth.resetPassword("security_member", "short", meta)).getCode()); + assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> auth.register("unused", "new@example.test", "x".repeat(257), "New", meta)).getCode()); + auth.updateAccount(token, "Renamed", null, null, meta); + assertEquals("Renamed", auth.requireUser(token).displayName()); + assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM auth_sessions WHERE revoked_at IS NOT NULL", Integer.class)); + } + + @Test void failedLoginBudgetIsCommittedAndHttpReturnsRetryAfter() throws Exception { + for (int i = 0; i < 10; i++) assertEquals(401, assertThrows(ApiException.class, () -> auth.login("missing_member", "wrong-password", meta)).getStatus()); + http.perform(post("/api/auth/login").contentType("application/json").content("{\"account\":\"missing_member\",\"password\":\"wrong-password\"}")) + .andExpect(status().isTooManyRequests()).andExpect(header().exists("Retry-After")); + assertEquals(2, jdbc.queryForObject("SELECT count(*) FROM auth_login_windows", Integer.class)); + assertFalse(jdbc.queryForObject("SELECT string_agg(bucket_hash,',') FROM auth_login_windows", String.class).contains("missing_member")); + jdbc.update("UPDATE auth_login_windows SET expires_at=clock_timestamp()-interval '1 second'"); + assertEquals(401, assertThrows(ApiException.class, () -> auth.login("missing_member", "wrong-password", meta)).getStatus()); + } + + @Test void concurrentLoginBudgetCannotExceedTheAccountLimit() throws Exception { + var start = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(12)) { + var results = new ArrayList>(); + for (int i = 0; i < 20; i++) results.add(executor.submit(() -> { + assertTrue(start.await(10, TimeUnit.SECONDS)); + try { auth.login("missing_member", "wrong-password", meta); return 200; } + catch (ApiException error) { return error.getStatus(); } + })); + start.countDown(); + var codes = new ArrayList(); + for (var result : results) codes.add(result.get(30, TimeUnit.SECONDS)); + assertEquals(10, codes.stream().filter(code -> code == 401).count()); + assertEquals(10, codes.stream().filter(code -> code == 429).count()); + } + } + + @Test void sourceBudgetAlsoLimitsChangingUnknownAccounts() { + var limiter = new LoginAttemptLimiter(jdbc); + for (int i = 0; i < 50; i++) limiter.check("different-" + i, "127.0.0.1"); + assertEquals(429, assertThrows(ApiException.class, () -> limiter.check("yet-another", "127.0.0.1")).getStatus()); + assertDoesNotThrow(() -> limiter.check("yet-another", "127.0.0.2")); + } + + @Test void passwordResetWinningTheUserLockPreventsOldPasswordSessionIssuance() throws Exception { + try (var executor = Executors.newSingleThreadExecutor()) { + var started = new CountDownLatch(1); + var future = new java.util.concurrent.atomic.AtomicReference>(); + new TransactionTemplate(new DataSourceTransactionManager(source)).execute(status -> { + jdbc.queryForList("SELECT id FROM users WHERE id=? FOR UPDATE", userId); + future.set(executor.submit(() -> { + started.countDown(); + try { session(); return 200; } catch (ApiException error) { return error.getStatus(); } + })); + try { assertTrue(started.await(10, TimeUnit.SECONDS)); } catch (InterruptedException error) { throw new AssertionError(error); } + auth.resetPassword("security_member", "replacement-password", meta); + return null; + }); + assertEquals(401, future.get().get(20, TimeUnit.SECONDS)); + assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM auth_sessions WHERE revoked_at IS NULL", Integer.class)); + } + } + + @Test void loginWinningTheLockStillGetsRevokedByFollowingPasswordReset() throws Exception { + var verified = new CountDownLatch(1); var allow = new CountDownLatch(1); + doAnswer(call -> { + verified.countDown(); assertTrue(allow.await(15, TimeUnit.SECONDS)); return call.callRealMethod(); + }).when(hasher).matches(eq("original-password"), anyString()); + try (var executor = Executors.newFixedThreadPool(2)) { + var login = executor.submit(this::session); + assertTrue(verified.await(10, TimeUnit.SECONDS)); + var reset = executor.submit(() -> auth.resetPassword("security_member", "replacement-password", meta)); + allow.countDown(); + String token = login.get(20, TimeUnit.SECONDS); reset.get(20, TimeUnit.SECONDS); + assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(token)).getStatus()); + } finally { allow.countDown(); } + } + + @Test void mfaFailuresRemainCommittedInsideTheLoginTransaction() { + var cipher = new SecretCipher("isolated-mfa-key"); + jdbc.update("INSERT INTO user_totp(user_id,secret_ciphertext,enabled) VALUES (?,?,true)", userId, cipher.encrypt("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); + for (int i = 0; i < 5; i++) assertEquals("INVALID_MFA_CODE", assertThrows(ApiException.class, () -> auth.login("security_member", "original-password", "not-a-code", meta)).getCode()); + assertEquals("MFA_RATE_LIMITED", assertThrows(ApiException.class, () -> auth.login("security_member", "original-password", "not-a-code", meta)).getCode()); + assertEquals(5, jdbc.queryForObject("SELECT attempts FROM user_totp WHERE user_id=?", Integer.class, userId)); + assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM auth_sessions", Integer.class)); + } + + @Test void auditFailureRollsBackPasswordAndRevocationsTogether() { + String token = session(); + jdbc.execute("CREATE FUNCTION reject_password_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.event_type='user.account_updated' THEN RAISE EXCEPTION 'isolated audit failure'; END IF; RETURN NEW; END $$"); + jdbc.execute("CREATE TRIGGER reject_password_audit BEFORE INSERT ON auth_audit_log FOR EACH ROW EXECUTE FUNCTION reject_password_audit()"); + assertThrows(org.springframework.dao.DataAccessException.class, () -> auth.updateAccount(token, "Test", "original-password", "replacement-password", meta)); + assertNotNull(auth.requireUser(token)); + assertNotNull(session()); + } +} diff --git a/control-plane-java/src/test/java/com/moyi/controlplane/auth/PasswordPolicyTest.java b/control-plane-java/src/test/java/com/moyi/controlplane/auth/PasswordPolicyTest.java new file mode 100644 index 0000000..831fcd1 --- /dev/null +++ b/control-plane-java/src/test/java/com/moyi/controlplane/auth/PasswordPolicyTest.java @@ -0,0 +1,18 @@ +package com.moyi.controlplane.auth; + +import com.moyi.controlplane.common.ApiException; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class PasswordPolicyTest { + @Test void everyNewPasswordHasTheSameBoundsWithoutTrimming() { + for (String value : new String[]{null, "", " ".repeat(12), "short", "x".repeat(257)}) assertThrows(ApiException.class, () -> PasswordPolicy.validate(value)); + assertDoesNotThrow(() -> PasswordPolicy.validate("a".repeat(8))); + assertDoesNotThrow(() -> PasswordPolicy.validate("a".repeat(256))); + } + @Test void malformedHashesCannotSelectUnboundedWorkAndNullIsNeverAPassword() { + var hasher = new PasswordHasher("pepper"); + for (String encoded : new String[]{null, "", "pbkdf2$2147483647$AAECAwQFBgcICQoLDA0ODw$" + "A".repeat(43), "pbkdf2$210000$AA$AA"}) assertFalse(hasher.matches("test-password", encoded)); + assertFalse(hasher.matches(null, hasher.hash("null"))); + } +} diff --git a/prototype/src/App.vue b/prototype/src/App.vue index 4f5d7dd..8528a49 100644 --- a/prototype/src/App.vue +++ b/prototype/src/App.vue @@ -104,6 +104,17 @@ function accountSaved(user: AuthUser) { accountSettingsOpen.value = false } +function passwordChanged() { + accountSettingsOpen.value = false + accountMenuOpen.value = false + availableCredit.value = undefined + authUser.value = undefined + authenticated.value = false + userName.value = '' + portal.value = 'user' + activeView.value = 'overview' +} + function openHelp() { accountMenuOpen.value = false if (portal.value === 'user') { @@ -208,6 +219,7 @@ function openGlobalSearch() { :user="authUser" @close="accountSettingsOpen = false" @saved="accountSaved" + @reauthenticate="passwordChanged" @notify="notify" /> diff --git a/prototype/src/components/AccountSettings.vue b/prototype/src/components/AccountSettings.vue index 22f9106..3da225b 100644 --- a/prototype/src/components/AccountSettings.vue +++ b/prototype/src/components/AccountSettings.vue @@ -5,7 +5,7 @@ import UiModal from './UiModal.vue' import MfaSettings from './MfaSettings.vue' const props = defineProps<{ user: AuthUser }>() -const emit = defineEmits<{ close: []; saved: [user: AuthUser]; notify: [message: string] }>() +const emit = defineEmits<{ close: []; saved: [user: AuthUser]; reauthenticate: []; notify: [message: string] }>() const form = reactive({ displayName: props.user.displayName, currentPassword: '', newPassword: '', confirmPassword: '' }) const saving = ref(false) @@ -24,8 +24,13 @@ async function save() { currentPassword: form.currentPassword || undefined, newPassword: form.newPassword || undefined, }) - emit('saved', user) - emit('notify', '账号设置已保存') + if (form.newPassword) { + emit('reauthenticate') + emit('notify', '密码已修改,全部浏览器会话已撤销,请重新登录') + } else { + emit('saved', user) + emit('notify', '账号设置已保存') + } } catch (error) { emit('notify', error instanceof Error ? error.message : '账号设置保存失败') } finally { @@ -46,7 +51,7 @@ async function save() { -

普通用户新密码至少 8 位;超级管理员按实际设置保存。

+

所有角色新密码均为 8 至 256 位。修改后全部浏览器会话失效,需重新登录;API Key 不自动撤销。