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, org.mockito.Mockito.mock(VerificationService.class), 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 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"); } }