fix:"保证验证码消费与账号变更原子提交"
This commit is contained in:
1 parent
32f6f67b9f
commit
02c21e5c19
9 files changed
+345
-14
No files matched your search
@@ -65,7 +65,9 @@ class AuthPostgresTest {
|
||||
assertThrows(DataIntegrityViolationException.class, () -> jdbc.update("UPDATE users SET role = 'super_admin' WHERE id = ?", operatorId));
|
||||
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("operator", "test-password", "Other"));
|
||||
|
||||
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, org.mockito.Mockito.mock(VerificationService.class), 168, true))
|
||||
var verification = org.mockito.Mockito.mock(VerificationService.class);
|
||||
var verifiedAccounts = new VerifiedAccountService(auth, verification, context.getBean(DataSourceTransactionManager.class));
|
||||
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, verification, verifiedAccounts, 168, true))
|
||||
.setControllerAdvice(new ApiExceptionHandler()).build();
|
||||
var ownerCookie = login(http, "adimin", "super_admin");
|
||||
var operatorCookie = login(http, "operator", "admin");
|
||||
|
||||
+3
-1
@@ -60,7 +60,9 @@ class AuthSecurityPostgresTest {
|
||||
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();
|
||||
var verification = mock(VerificationService.class);
|
||||
var verifiedAccounts = new VerifiedAccountService(auth, verification, context.getBean(DataSourceTransactionManager.class));
|
||||
http = MockMvcBuilders.standaloneSetup(new AuthController(auth, verification, verifiedAccounts, 168, true)).setControllerAdvice(new ApiExceptionHandler()).build();
|
||||
}
|
||||
|
||||
@AfterEach void cleanup() {
|
||||
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
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.Map;
|
||||
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.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
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 VerifiedAccountPostgresTest {
|
||||
@Configuration @EnableTransactionManagement(proxyTargetClass=true) static class Transactions {}
|
||||
private static final String ACCOUNT = "verified@example.test", CODE = "123456", PASSWORD = "synthetic-original-password";
|
||||
private final UUID invitationCreator = UUID.randomUUID();
|
||||
private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "isolated-verified-workflow");
|
||||
private final ObjectMapper json = new ObjectMapper().findAndRegisterModules();
|
||||
private DriverManagerDataSource base;
|
||||
private String schema;
|
||||
private JdbcTemplate jdbc;
|
||||
private AnnotationConfigApplicationContext context;
|
||||
private AuthService auth;
|
||||
private VerifiedAccountService verified;
|
||||
private VerificationService verification;
|
||||
private PasswordHasher hasher;
|
||||
private MockMvc http;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL");
|
||||
schema = "verified_account_" + UUID.randomUUID().toString().replace("-", "");
|
||||
base = new DriverManagerDataSource(url, "moyi_role_test", "");
|
||||
var source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", "");
|
||||
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
|
||||
jdbc = new JdbcTemplate(source); hasher = new PasswordHasher("isolated-verified-pepper");
|
||||
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role) VALUES (?,'invitation_creator','username','not-a-login-hash','Synthetic Creator','admin')", invitationCreator);
|
||||
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-totp")));
|
||||
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, mock(VerificationSender.class), "isolated-verified-pepper"));
|
||||
context.registerBean(VerifiedAccountService.class); context.refresh();
|
||||
auth = context.getBean(AuthService.class); verification = context.getBean(VerificationService.class); verified = context.getBean(VerifiedAccountService.class);
|
||||
http = MockMvcBuilders.standaloneSetup(new AuthController(auth, verification, verified, 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 invitation() {
|
||||
String value = "synthetic-invite-" + UUID.randomUUID();
|
||||
jdbc.update("INSERT INTO invitation_codes(id,code_hash,code_prefix,label,max_uses,used_count,created_by) VALUES (?,?,?,'test',1,0,?)", UUID.randomUUID(), AuthService.hashSecret(value), "synthetic", invitationCreator);
|
||||
return value;
|
||||
}
|
||||
private UUID user() {
|
||||
UUID id = UUID.randomUUID();
|
||||
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name) VALUES (?,?,'email',?,'Test')", id, ACCOUNT, hasher.hash(PASSWORD));
|
||||
return id;
|
||||
}
|
||||
private void code(boolean reset) {
|
||||
String table = reset ? "password_reset_codes" : "registration_codes";
|
||||
String purpose = reset ? "password-reset" : "registration";
|
||||
jdbc.update("INSERT INTO " + table + "(account,code_hash,expires_at) VALUES (?,?,clock_timestamp()+interval '5 minutes')",
|
||||
ACCOUNT, AuthService.hashSecret("isolated-verified-pepper:" + purpose + ":" + ACCOUNT + ":" + CODE));
|
||||
}
|
||||
private void assertUnconsumed(boolean reset, int attempts) {
|
||||
var row = jdbc.queryForMap("SELECT consumed,attempts FROM " + (reset ? "password_reset_codes" : "registration_codes") + " WHERE account=?", ACCOUNT);
|
||||
assertEquals(false, row.get("consumed")); assertEquals(attempts, ((Number)row.get("attempts")).intValue());
|
||||
}
|
||||
private void rejectAudit(String event) {
|
||||
// Constraint is isolated to this random test schema; only synthetic event types are supplied.
|
||||
jdbc.execute("ALTER TABLE auth_audit_log ADD CONSTRAINT injected_audit_failure CHECK (event_type <> '" + event + "') NOT VALID");
|
||||
}
|
||||
|
||||
@Test void invalidInvitationKeepsTheCodeUsableForTheSameAccount() {
|
||||
code(false); String invite = invitation();
|
||||
assertEquals("INVITATION_INVALID", assertThrows(ApiException.class, () -> verified.register("invalid", ACCOUNT, PASSWORD, "Test", CODE, meta)).getCode());
|
||||
assertUnconsumed(false, 0);
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM users WHERE account=?", Integer.class, ACCOUNT));
|
||||
assertEquals(0, jdbc.queryForObject("SELECT sum(used_count) FROM invitation_codes", Integer.class));
|
||||
var result = verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta);
|
||||
assertEquals(ACCOUNT, result.user().account()); assertNotNull(auth.requireUser(result.token()));
|
||||
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM invitation_redemptions", Integer.class));
|
||||
assertEquals("VERIFICATION_EXPIRED", assertThrows(ApiException.class, () -> verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta)).getCode());
|
||||
}
|
||||
|
||||
@Test void invalidDisplayNameAndDuplicateAccountDoNotBurnAValidCode() {
|
||||
code(false); String invite = invitation();
|
||||
assertEquals("INVALID_NAME", assertThrows(ApiException.class, () -> verified.register(invite, ACCOUNT, PASSWORD, "x".repeat(81), CODE, meta)).getCode());
|
||||
assertUnconsumed(false, 0);
|
||||
user();
|
||||
assertEquals("ACCOUNT_EXISTS", assertThrows(ApiException.class, () -> verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta)).getCode());
|
||||
assertUnconsumed(false, 0);
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM invitation_redemptions", Integer.class));
|
||||
}
|
||||
|
||||
@Test void registrationAuditFailureRollsBackCodeInvitationUserAndSessionTogether() {
|
||||
code(false); String invite = invitation(); rejectAudit("user.registered");
|
||||
assertThrows(DataIntegrityViolationException.class, () -> verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta));
|
||||
assertUnconsumed(false, 0);
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM users WHERE account=?", Integer.class, ACCOUNT));
|
||||
for (String table : java.util.List.of("auth_sessions", "invitation_redemptions", "auth_audit_log")) {
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM " + table, Integer.class), table);
|
||||
}
|
||||
assertEquals(0, jdbc.queryForObject("SELECT sum(used_count) FROM invitation_codes", Integer.class));
|
||||
jdbc.execute("ALTER TABLE auth_audit_log DROP CONSTRAINT injected_audit_failure");
|
||||
assertNotNull(verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta).token());
|
||||
}
|
||||
|
||||
@Test void resetAuditFailureRollsBackCodeHashAndSessionRevocations() {
|
||||
UUID id = user(); code(true);
|
||||
String first = auth.login(ACCOUNT, PASSWORD, meta).token(), second = auth.login(ACCOUNT, PASSWORD, meta).token();
|
||||
String original = jdbc.queryForObject("SELECT password_hash FROM users WHERE id=?", String.class, id);
|
||||
rejectAudit("user.password_reset");
|
||||
assertThrows(DataIntegrityViolationException.class, () -> verified.resetPassword(ACCOUNT, CODE, "replacement-password", meta));
|
||||
assertUnconsumed(true, 0);
|
||||
assertEquals(original, jdbc.queryForObject("SELECT password_hash FROM users WHERE id=?", String.class, id));
|
||||
assertNotNull(auth.requireUser(first)); assertNotNull(auth.requireUser(second));
|
||||
jdbc.execute("ALTER TABLE auth_audit_log DROP CONSTRAINT injected_audit_failure");
|
||||
verified.resetPassword(ACCOUNT, CODE, "replacement-password", meta);
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(first)).getStatus());
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(second)).getStatus());
|
||||
assertNotNull(auth.login(ACCOUNT, "replacement-password", meta).token());
|
||||
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type='user.password_reset'", Integer.class));
|
||||
}
|
||||
|
||||
@ParameterizedTest @ValueSource(booleans = {false, true})
|
||||
void wrongCodeAttemptsCommitEvenWhenAnOuterCallerRollsBack(boolean reset) {
|
||||
if (reset) user(); code(reset); String invite = invitation();
|
||||
var outer = new TransactionTemplate(context.getBean(DataSourceTransactionManager.class));
|
||||
outer.executeWithoutResult(status -> {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
var failure = assertThrows(ApiException.class, () -> {
|
||||
if (reset) verified.resetPassword(ACCOUNT, "000000", "replacement-password", meta);
|
||||
else verified.register(invite, ACCOUNT, PASSWORD, "Test", "000000", meta);
|
||||
});
|
||||
assertEquals("VERIFICATION_INVALID", failure.getCode());
|
||||
}
|
||||
status.setRollbackOnly();
|
||||
});
|
||||
assertUnconsumed(reset, 5);
|
||||
assertEquals("VERIFICATION_EXPIRED", assertThrows(ApiException.class, () -> {
|
||||
if (reset) verified.resetPassword(ACCOUNT, CODE, "replacement-password", meta);
|
||||
else verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta);
|
||||
}).getCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest @ValueSource(booleans = {false, true})
|
||||
void weakNewPasswordsNeverConsumeCodes(boolean reset) {
|
||||
code(reset); String invite = invitation();
|
||||
assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> {
|
||||
if (reset) verified.resetPassword(ACCOUNT, CODE, "short", meta);
|
||||
else verified.register(invite, ACCOUNT, "short", "Test", CODE, meta);
|
||||
}).getCode());
|
||||
assertUnconsumed(reset, 0);
|
||||
}
|
||||
|
||||
@Test void disabledResetAccountLeavesTheValidCodeUnconsumed() {
|
||||
UUID id = user(); code(true); jdbc.update("UPDATE users SET status='disabled' WHERE id=?", id);
|
||||
assertEquals("ACCOUNT_NOT_FOUND", assertThrows(ApiException.class, () -> verified.resetPassword(ACCOUNT, CODE, "replacement-password", meta)).getCode());
|
||||
assertUnconsumed(true, 0);
|
||||
}
|
||||
|
||||
@ParameterizedTest @ValueSource(booleans = {false, true})
|
||||
void concurrentCodeUseCompletesExactlyOneAccountOperation(boolean reset) throws Exception {
|
||||
if (reset) user(); code(reset); String invite = invitation();
|
||||
var start = new CountDownLatch(1); var results = new ArrayList<String>();
|
||||
try (var executor = Executors.newFixedThreadPool(2)) {
|
||||
var futures = new ArrayList<java.util.concurrent.Future<String>>();
|
||||
for (int i = 0; i < 2; i++) futures.add(executor.submit(() -> {
|
||||
assertTrue(start.await(3, TimeUnit.SECONDS));
|
||||
try {
|
||||
if (reset) verified.resetPassword(ACCOUNT, CODE, "replacement-password", meta);
|
||||
else verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta);
|
||||
return "completed";
|
||||
} catch (ApiException error) { return error.getCode(); }
|
||||
}));
|
||||
start.countDown();
|
||||
for (var future : futures) results.add(future.get(15, TimeUnit.SECONDS));
|
||||
}
|
||||
assertEquals(1, results.stream().filter("completed"::equals).count());
|
||||
assertEquals(1, results.stream().filter("VERIFICATION_EXPIRED"::equals).count());
|
||||
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM users WHERE account=?", Integer.class, ACCOUNT));
|
||||
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type=?", Integer.class, reset ? "user.password_reset" : "user.registered"));
|
||||
if (!reset) assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM invitation_redemptions", Integer.class));
|
||||
}
|
||||
|
||||
@Test void publicResetClearsTheCookieAndRevokesTheServerSessionOnlyAfterSuccess() throws Exception {
|
||||
user(); code(true); String token = auth.login(ACCOUNT, PASSWORD, meta).token();
|
||||
http.perform(post("/api/auth/password-reset").cookie(new Cookie("moyi_session", token)).contentType("application/json")
|
||||
.content(json.writeValueAsBytes(Map.of("account", ACCOUNT, "verificationCode", "000000", "newPassword", "replacement-password"))))
|
||||
.andExpect(status().isBadRequest()).andExpect(cookie().doesNotExist("moyi_session"));
|
||||
assertNotNull(auth.requireUser(token)); assertUnconsumed(true, 1);
|
||||
http.perform(post("/api/auth/password-reset").cookie(new Cookie("moyi_session", token)).contentType("application/json")
|
||||
.content(json.writeValueAsBytes(Map.of("account", ACCOUNT, "verificationCode", CODE, "newPassword", "replacement-password"))))
|
||||
.andExpect(status().isNoContent()).andExpect(cookie().maxAge("moyi_session", 0))
|
||||
.andExpect(cookie().httpOnly("moyi_session", true)).andExpect(cookie().secure("moyi_session", true));
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(token)).getStatus());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user