feat: add unique super administrator and role management

This commit is contained in:
wlx committed 2026-09-17 19:03:51 +08:00
1 parent 9e731e47b9
commit 386d15cde2
16 files changed
+455 -24

No files matched your search

@@ -45,6 +45,8 @@ public class AuthController {
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
public record RoleRequest(String role) {}
@PostMapping("/auth/login")
public Map<String, Object> login(
@RequestBody LoginRequest input,
@@ -86,6 +88,15 @@ public class AuthController {
return Map.of("users", authService.listUsers(sessionToken(request)));
}
@PostMapping("/admin/users/{id}/role")
public Map<String, Object> changeRole(
@PathVariable UUID id,
@RequestBody RoleRequest input,
HttpServletRequest request
) {
return Map.of("user", authService.changeRole(sessionToken(request), id, input.role(), meta(request)));
}
@GetMapping("/admin/invitations")
public Map<String, Object> invitations(HttpServletRequest request) {
return Map.of("invitations", authService.listInvitations(sessionToken(request)));
@@ -13,6 +13,7 @@ import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
@@ -73,17 +74,31 @@ public class AuthService {
@Transactional
public void ensureAdmin(String accountInput, String password, String displayName) {
String account = normalizeAccount(accountInput);
if (account.isBlank() || password.isBlank()) {
if (account.isBlank() || password == null || password.isBlank()) {
throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500);
}
if (findUserByAccount(account) != null) {
// Serialize bootstrap across replicas, including the first creation.
jdbc.execute("LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE");
List<String> owners = jdbc.queryForList("SELECT account FROM users WHERE role = 'super_admin'", String.class);
if (!owners.isEmpty()) {
if (!owners.getFirst().equals(account)) {
throw new IllegalStateException("ADMIN_ACCOUNT differs from the existing super administrator; refusing to create another owner.");
}
return;
}
UserRow existing = findUserByAccount(account);
if (existing != null) {
if (!"admin".equals(existing.role()) || !"active".equals(existing.status())) {
throw new IllegalStateException("Bootstrap account must be an active administrator; refusing to promote an ordinary or disabled user.");
}
jdbc.update("UPDATE users SET role = 'super_admin', updated_at = ? WHERE id = ?", now(), existing.id());
return;
}
OffsetDateTime now = now();
jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'admin', 'active', ?, ?)",
"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),
displayName == null || displayName.isBlank() ? "平台管理员" : displayName.trim(), now, now
displayName == null || displayName.isBlank() ? "超级管理员" : displayName.trim(), now, now
);
}
@@ -155,12 +170,49 @@ public class AuthService {
public UserView requireAdmin(String token) {
UserRow user = requireUserRow(token);
if (!"admin".equals(user.role())) {
if (!isAdminRole(user.role())) {
throw new ApiException("FORBIDDEN", "需要管理员权限", 403);
}
return toView(user, null);
}
public UserView requireSuperAdmin(String token) {
UserRow user = requireUserRow(token);
if (!"super_admin".equals(user.role())) {
throw new ApiException("FORBIDDEN", "需要超级管理员权限", 403);
}
return toView(user, null);
}
@Transactional
public UserView changeRole(String token, UUID userId, String requestedRole, RequestMeta meta) {
UserView actor = requireSuperAdmin(token);
String role = requestedRole == null ? "" : requestedRole.trim().toLowerCase(Locale.ROOT);
if (!role.equals("user") && !role.equals("admin")) {
throw new ApiException("INVALID_ROLE", "只能授予普通用户或管理员角色", 400);
}
if (actor.id().equals(userId)) {
throw new ApiException("SELF_ROLE_CHANGE", "超级管理员不能修改自己的角色", 400);
}
List<UserRow> targets = jdbc.query("SELECT * FROM users WHERE id = ? FOR UPDATE", this::mapUser, userId);
if (targets.isEmpty()) {
throw new ApiException("USER_NOT_FOUND", "用户不存在", 404);
}
UserRow target = targets.getFirst();
if ("super_admin".equals(target.role())) {
throw new ApiException("SUPER_ADMIN_PROTECTED", "超级管理员账号不可通过此接口降级", 403);
}
if (!role.equals(target.role())) {
jdbc.update("UPDATE users SET role = ?, updated_at = ? WHERE id = ?", role, now(), userId);
audit("user.role_changed", actor.id(), meta, Map.of("targetUserId", userId, "fromRole", target.role(), "role", role));
}
return toView(findUserById(userId), null);
}
private boolean isAdminRole(String role) {
return "admin".equals(role) || "super_admin".equals(role);
}
public void logout(String token, RequestMeta meta) {
if (token == null || token.isBlank()) {
return;
@@ -0,0 +1,8 @@
-- Keep one protected platform owner while retaining a lower-privilege operator role.
ALTER TABLE users DROP CONSTRAINT IF EXISTS users_role_check;
ALTER TABLE users
ADD CONSTRAINT users_role_check CHECK (role IN ('user', 'admin', 'super_admin'));
CREATE UNIQUE INDEX IF NOT EXISTS users_single_super_admin_idx
ON users (role)
WHERE role = 'super_admin';
@@ -0,0 +1,112 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiExceptionHandler;
import jakarta.servlet.http.Cookie;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
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.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 static org.junit.jupiter.api.Assertions.*;
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 AuthPostgresTest {
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
static class Transactions {}
@Test
void migrationBootstrapRegistrationAndLiveRoleChanges() throws Exception {
String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL");
String schema = "auth_test_" + UUID.randomUUID().toString().replace("-", "");
DriverManagerDataSource base = new DriverManagerDataSource(url, "moyi_role_test", "");
DriverManagerDataSource source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", "");
JdbcTemplate jdbc = new JdbcTemplate(source);
PasswordHasher hasher = new PasswordHasher("isolated-test-pepper");
ObjectMapper json = new ObjectMapper().findAndRegisterModules();
UUID ownerId = UUID.randomUUID();
UUID operatorId = UUID.randomUUID();
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).target("8").load().migrate();
String insert = "INSERT INTO users (id, account, account_kind, password_hash, display_name, role) VALUES (?, ?, 'username', ?, ?, 'admin')";
jdbc.update(insert, ownerId, "adimin", hasher.hash("test-password"), "Owner");
jdbc.update(insert, operatorId, "operator", hasher.hash("test-password"), "Operator");
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
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.refresh();
AuthService auth = context.getBean(AuthService.class);
try (var threads = Executors.newFixedThreadPool(2)) {
var first = threads.submit(() -> auth.ensureAdmin("adimin", "ignored-new-password", "Owner"));
var second = threads.submit(() -> auth.ensureAdmin("adimin", "ignored-new-password", "Owner"));
first.get(15, TimeUnit.SECONDS);
second.get(15, TimeUnit.SECONDS);
}
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM users WHERE role = 'super_admin'", Integer.class));
assertEquals("admin", jdbc.queryForObject("SELECT role FROM users WHERE id = ?", String.class, operatorId));
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, 168, true))
.setControllerAdvice(new ApiExceptionHandler()).build();
var ownerCookie = login(http, "adimin", "super_admin");
var operatorCookie = login(http, "operator", "admin");
String inviteResponse = http.perform(post("/api/admin/invitations").cookie(ownerCookie).contentType("application/json").content("{}"))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsString();
String code = json.readTree(inviteResponse).get("code").asText();
Map<String, String> registration = Map.of("invitationCode", code, "account", "member@example.test", "password", "test-password", "role", "super_admin");
var registered = http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(registration)))
.andExpect(status().isCreated()).andExpect(jsonPath("$.user.role").value("user"))
.andExpect(cookie().httpOnly("moyi_session", true)).andExpect(cookie().secure("moyi_session", true))
.andReturn().getResponse();
UUID memberId = UUID.fromString(json.readTree(registered.getContentAsString()).get("user").get("id").asText());
Cookie memberCookie = registered.getCookie("moyi_session");
http.perform(get("/api/auth/me").cookie(memberCookie)).andExpect(status().isOk()).andExpect(jsonPath("$.user.role").value("user"));
http.perform(get("/api/admin/users").cookie(memberCookie)).andExpect(status().isForbidden());
http.perform(get("/api/admin/users")).andExpect(status().isUnauthorized());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(operatorCookie).contentType("application/json").content("{\"role\":\"admin\"}"))
.andExpect(status().isForbidden());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"super_admin\"}"))
.andExpect(status().isBadRequest());
http.perform(post("/api/admin/users/" + ownerId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"user\"}"))
.andExpect(status().isBadRequest());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"admin\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.user.role").value("admin"));
http.perform(get("/api/admin/users").cookie(memberCookie)).andExpect(status().isOk());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"user\"}"))
.andExpect(status().isOk());
http.perform(get("/api/admin/users").cookie(memberCookie)).andExpect(status().isForbidden());
assertEquals(2, jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type = 'user.role_changed'", Integer.class));
registration = Map.of("invitationCode", code, "account", "another@example.test", "password", "test-password");
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(registration)))
.andExpect(status().isForbidden());
} finally {
// Only remove the randomly named schema created by this test, never application data.
new JdbcTemplate(base).execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE");
}
}
private Cookie login(MockMvc http, String account, String role) throws Exception {
return http.perform(post("/api/auth/login").contentType("application/json")
.content("{\"account\":\"" + account + "\",\"password\":\"test-password\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.user.role").value(role))
.andReturn().getResponse().getCookie("moyi_session");
}
}
@@ -0,0 +1,139 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import java.sql.ResultSet;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class AuthRolesTest {
private final JdbcTemplate jdbc = mock(JdbcTemplate.class);
private final PasswordHasher hasher = mock(PasswordHasher.class);
private final AuthService auth = new AuthService(jdbc, hasher, new ObjectMapper(), 168);
private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "test");
private final UUID ownerId = UUID.randomUUID();
private final UUID userId = UUID.randomUUID();
@Test
void bootstrapCreatesOneOwnerAndHashesPassword() {
doThrow(new EmptyResultDataAccessException(1)).when(jdbc).queryForObject(anyString(), any(RowMapper.class), any(Object[].class));
when(hasher.hash("test-password")).thenReturn("hashed-test-password");
auth.ensureAdmin("adimin", "test-password", "Owner");
verify(jdbc).execute("LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE");
verify(jdbc).update(contains("'super_admin', 'active'"), any(Object[].class));
verify(hasher).hash("test-password");
}
@Test
void bootstrapPromotesLegacyAdminWithoutReplacingPassword() throws Exception {
lookupUser(ownerId, "admin");
auth.ensureAdmin("adimin", "test-password", "Owner");
verify(jdbc).update(contains("SET role = 'super_admin'"), any(Object[].class));
verifyNoInteractions(hasher);
}
@Test
void repeatedBootstrapDoesNotResetPassword() {
when(jdbc.queryForList(contains("role = 'super_admin'"), eq(String.class))).thenReturn(List.of("adimin"));
auth.ensureAdmin("adimin", "different-password", "Owner");
verify(jdbc, never()).update(anyString(), any(Object[].class));
verifyNoInteractions(hasher);
}
@Test
void changingBootstrapAccountCannotCreateAnotherOwner() {
when(jdbc.queryForList(contains("role = 'super_admin'"), eq(String.class))).thenReturn(List.of("adimin"));
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("other", "test-password", "Owner"));
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void bootstrapCannotPromoteOrdinaryRegisteredUser() throws Exception {
lookupUser(userId, "user");
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("adimin", "test-password", "Owner"));
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void ownerAndAdminCanAccessOperationsButUserCannot() throws Exception {
sessionUser(ownerId, "super_admin");
assertEquals("super_admin", auth.requireAdmin("session").role());
sessionUser(userId, "admin");
assertEquals("admin", auth.requireAdmin("session").role());
sessionUser(userId, "user");
assertEquals(403, assertThrows(ApiException.class, () -> auth.requireAdmin("session")).getStatus());
}
@Test
void adminCannotChangeRolesEvenWithForgedRequest() throws Exception {
sessionUser(userId, "admin");
assertEquals(403, assertThrows(ApiException.class, () -> auth.changeRole("session", ownerId, "user", meta)).getStatus());
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void ownerCannotAssignAnotherOwnerOrDemoteSelf() throws Exception {
sessionUser(ownerId, "super_admin");
assertEquals("INVALID_ROLE", assertThrows(ApiException.class, () -> auth.changeRole("session", userId, "super_admin", meta)).getCode());
assertEquals("SELF_ROLE_CHANGE", assertThrows(ApiException.class, () -> auth.changeRole("session", ownerId, "user", meta)).getCode());
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void missingUserReturns404() throws Exception {
sessionUser(ownerId, "super_admin");
assertEquals(404, assertThrows(ApiException.class, () -> auth.changeRole("session", userId, "admin", meta)).getStatus());
}
@Test
void ownerCanPromoteAndDemoteWithAudit() throws Exception {
sessionUser(ownerId, "super_admin");
targetUser(userId, "user");
lookupUser(userId, "admin");
assertEquals("admin", auth.changeRole("session", userId, "admin", meta).role());
targetUser(userId, "admin");
lookupUser(userId, "user");
assertEquals("user", auth.changeRole("session", userId, "user", meta).role());
verify(jdbc, times(2)).update(startsWith("UPDATE users SET role = ?"), any(Object[].class));
verify(jdbc, times(2)).update(startsWith("INSERT INTO auth_audit_log"), any(Object[].class));
}
private void sessionUser(UUID id, String role) throws Exception {
ResultSet row = row(id, role);
doAnswer(call -> List.of(((RowMapper<?>) call.getArgument(1)).mapRow(row, 0)))
.when(jdbc).query(contains("JOIN users"), any(RowMapper.class), any(Object[].class));
}
private void targetUser(UUID id, String role) throws Exception {
ResultSet row = row(id, role);
doAnswer(call -> List.of(((RowMapper<?>) call.getArgument(1)).mapRow(row, 0)))
.when(jdbc).query(contains("FOR UPDATE"), any(RowMapper.class), any(Object[].class));
}
private void lookupUser(UUID id, String role) throws Exception {
ResultSet row = row(id, role);
doAnswer(call -> ((RowMapper<?>) call.getArgument(1)).mapRow(row, 0))
.when(jdbc).queryForObject(anyString(), any(RowMapper.class), any(Object[].class));
}
private ResultSet row(UUID id, String role) throws Exception {
ResultSet result = mock(ResultSet.class);
when(result.getObject("id", UUID.class)).thenReturn(id);
when(result.getString("account")).thenReturn("adimin");
when(result.getString("account_kind")).thenReturn("username");
when(result.getString("password_hash")).thenReturn("existing-hash");
when(result.getString("display_name")).thenReturn("Test");
when(result.getString("role")).thenReturn(role);
when(result.getString("status")).thenReturn("active");
when(result.getObject("created_at", OffsetDateTime.class)).thenReturn(OffsetDateTime.now());
return result;
}
}