From a8cdf33a24df362cba5e8540c20a7c2f17713b4c Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 20:48:05 +0800 Subject: [PATCH] feat(mobile-api): admin roles API (list, create, rename, module grants) Member and ROLE_ADMIN roles are hidden; super admin grants are not editable; removing your own last BO_ROLES grant is refused. Renaming keeps child roles intact. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/tasks.md | 2 +- .../api/RestApiSystemServiceConstants.java | 4 + .../controller/admin/AdminRoleController.java | 61 +++++ .../api/dto/admin/AdminGrantsRequest.java | 8 + .../api/dto/admin/AdminModuleGrant.java | 4 + .../api/dto/admin/AdminRoleRequest.java | 7 + .../mobile/api/service/AdminAclService.java | 106 ++++++++ .../mobile/api/service/AdminRoleService.java | 161 ++++++++++++ .../admin/AdminRoleControllerTest.java | 137 ++++++++++ .../api/service/AdminAclServiceTest.java | 242 ++++++++++++++++++ .../api/service/AdminRoleServiceTest.java | 233 +++++++++++++++++ 11 files changed, 964 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 4ac3be7..a929a79 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -26,7 +26,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t - [x] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 -- [ ] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 ## 6. Admin portal diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index f01e012..4ac5e88 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -10,6 +10,10 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable"; public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll"; + public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save"; + public static final String API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA = "/module/findAllByArea/{area}"; + public static final String API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE = "/module/addModuleRole/{moduleId}/{roleId}"; + public static final String API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE = "/module/deleteModuleRole/{moduleId}/{roleId}"; public static final String API_REST_SYSTEM_USER_SAVE = "/user/save"; public static final String API_REST_SYSTEM_USER_UPDATE_USER_PASSWORD = "/user/updateUserPassword"; public static final String API_REST_SYSTEM_USER_FIND_EXIST_BY_USERNAME = "/user/findExistByUsername/{username}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java new file mode 100644 index 0000000..ebe40b5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java @@ -0,0 +1,61 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGrantsRequest; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.service.AdminAclService; +import com.solvway.mobile.api.service.AdminRoleService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** Admin roles and their back-office module grants. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminRoleController { + private final AdminRoleService adminRoleService; + private final AdminAclService adminAclService; + + @AppAuth + @AdminModule({"BO_ROLES", "BO_USERS"}) + @GetMapping("/roles") + public ResponseEntity>> list() { + return ResponseEntity.ok(adminRoleService.list()); + } + @AppAuth + @AdminModule({"BO_ROLES", "BO_USERS"}) + @GetMapping("/roles/{id}") + public ResponseEntity> getById(@PathVariable Long id) { + return ResponseEntity.ok(adminRoleService.get(id)); + } + @AppAuth + @AdminModule("BO_ROLES") + @PostMapping("/roles") + public ResponseEntity> create(@RequestBody AdminRoleRequest request) { + return ResponseEntity.ok(adminRoleService.create(request)); + } + @AppAuth + @AdminModule("BO_ROLES") + @PutMapping("/roles/{id}") + public ResponseEntity> update(@PathVariable Long id, @RequestBody AdminRoleRequest request) { + return ResponseEntity.ok(adminRoleService.update(id, request)); + } + @AppAuth + @AdminModule("BO_ROLES") + @GetMapping("/roles/{id}/modules") + public ResponseEntity> getModules(@PathVariable Long id) { + return ResponseEntity.ok(adminAclService.getGrantTree(id)); + } + @AppAuth + @AdminModule("BO_ROLES") + @PutMapping("/roles/{id}/modules") + public ResponseEntity> putModules(@PathVariable Long id, @RequestBody AdminGrantsRequest request) { + return ResponseEntity.ok(adminAclService.updateGrants(id, request.moduleIds())); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java new file mode 100644 index 0000000..f3c9217 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java @@ -0,0 +1,8 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminGrantsRequest(List moduleIds) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java new file mode 100644 index 0000000..fc208fb --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.admin; + +/** One BO module row of a role's grant tree; the portal builds the checkbox tree from parentId. */ +public record AdminModuleGrant(Long id, String name, Long parentId, boolean granted) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java new file mode 100644 index 0000000..4b48a69 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java @@ -0,0 +1,7 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** Create/rename body. The portal may also send level and parent; the parent is always ROLE_SUPER_ADMIN, so they are ignored. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminRoleRequest(String name) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java new file mode 100644 index 0000000..9ff6823 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java @@ -0,0 +1,106 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Back-office module grants per role. Reads and writes the BO module tree through services-system. */ +@Service +@RequiredArgsConstructor +public class AdminAclService { + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final String AREA = "BO"; + private static final String ROLES_MODULE = "BO_ROLES"; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final long ROLE_ADMIN_ID = 2L; + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + private final AdminRoleService adminRoleService; + + public List getGrantTree(Long roleId) { + requireVisibleRole(roleId); + return modules().stream().filter(AdminAclService::isGrantable).map(m -> new AdminModuleGrant(AdminRoleService.idOf(m), (String) m.get("name"), + AdminRoleService.idOf(m.get("parent")), grantedTo(m, roleId))).toList(); + } + + public List updateGrants(Long roleId, List moduleIds) { + requireVisibleRole(roleId); + if (roleId == SUPER_ADMIN_ROLE_ID || roleId == ROLE_ADMIN_ID) { + throw error(HttpStatus.BAD_REQUEST, "This role's grants cannot be edited", "ROLE_NOT_EDITABLE"); + } + if (moduleIds == null) throw error(HttpStatus.BAD_REQUEST, "moduleIds is required", "REQUIRED_FIELD"); + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + + List> modules = modules(); + Set known = new HashSet<>(); + Set current = new HashSet<>(); + for (Map m : modules) { + if (isGrantable(m)) known.add(AdminRoleService.idOf(m)); + if (isGrantable(m) && grantedTo(m, roleId)) current.add(AdminRoleService.idOf(m)); + } + Set wanted = new HashSet<>(moduleIds); + if (!known.containsAll(wanted)) throw error(HttpStatus.BAD_REQUEST, "Unknown back-office module", "UNKNOWN_MODULE"); + requireNoLockout(caller, roleId, wanted, modules); + + // ponytail: not atomic, adds run before deletes and a failure midway leaves a partial grant; a repeated PUT converges. Upgrade: one services-system endpoint that replaces grants in a transaction. + for (Long id : wanted) if (!current.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE, id, roleId); + for (Long id : current) if (!wanted.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE, id, roleId); + return getGrantTree(roleId); + } + + /** A non-super caller must still reach BO_ROLES through one of their roles (role 2 is on every admin and grants nothing). */ + private static void requireNoLockout(User caller, Long roleId, Set wanted, List> modules) { + if (caller.getRoles() == null || caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID)) return; + Set held = new HashSet<>(); + caller.getRoles().stream().map(r -> r.getId()).filter(i -> i != null && i != ROLE_ADMIN_ID).forEach(held::add); + if (!held.contains(roleId)) return; + Map rolesModule = modules.stream().filter(m -> ROLES_MODULE.equals(m.get("name"))).findFirst().orElse(null); + if (rolesModule == null) return; + boolean stillGranted = held.stream().anyMatch(r -> r.equals(roleId) ? wanted.contains(AdminRoleService.idOf(rolesModule)) : grantedTo(rolesModule, r)); + if (!stillGranted) throw error(HttpStatus.BAD_REQUEST, "This change would remove your own access to role management", "ACL_LOCKOUT"); + } + + /** Hidden roles (ROLE_MEMBER, ROLE_ADMIN) look absent, as in the role list. */ + private void requireVisibleRole(Long roleId) { + if (AdminRoleService.isHidden(adminRoleService.find(roleId))) { + throw error(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND"); + } + } + + /** Only leaf modules (type M) are granted; the type R root is just a container. */ + private static boolean isGrantable(Map module) { + return "M".equals(module.get("type")); + } + + private static boolean grantedTo(Map module, Long roleId) { + return module.get("roles") instanceof List l && l.stream().anyMatch(r -> roleId.equals(AdminRoleService.idOf(r))); + } + + private List> modules() { + List> body = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA), MAP_LIST, AREA).getBody(); + return body == null ? List.of() : body; + } + + private void call(String api, Long moduleId, Long roleId) { + restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(api), Integer.class, moduleId, roleId); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code) { + return new CodedResponseStatusException(status, reason, code); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java new file mode 100644 index 0000000..b1cd4ba --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java @@ -0,0 +1,161 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Admin roles for the portal. Roles travel as maps. services-system's /role/save swallows errors and recomputes + * level and tracekey from the parent, and /role/findById throws on a missing id, so this reads with findAll and + * verifies a rename by re-reading. + */ +@Service +@RequiredArgsConstructor +public class AdminRoleService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final List HIDDEN = List.of("ROLE_MEMBER", "ROLE_ADMIN"); + private static final List PROTECTED = List.of("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER"); + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + public List> list() { + return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList(); + } + + public Map get(Long id) { + Map role = find(id); + if (isHidden(role)) throw notFound(); + return clean(role); + } + + /** Any stored role, hidden ones included; 404 when absent. */ + public Map find(Long id) { + return all().stream().filter(r -> id != null && id.equals(idOf(r))).findFirst().orElseThrow(AdminRoleService::notFound); + } + + public Map create(AdminRoleRequest r) { + String name = requireName(r); + User caller = caller(); + requireFree(name, null); + Map role = new HashMap<>(); + role.put("name", name); + role.put("parent", Map.of("id", SUPER_ADMIN_ROLE_ID)); + role.put("children", List.of()); + role.put("createBy", caller.getUsername()); + role.put("doneBy", caller.getUsername()); + role.put("createDate", System.currentTimeMillis()); + return clean(save(role)); + } + + public Map update(Long id, AdminRoleRequest r) { + User caller = caller(); + Map stored = find(id); + if (isProtected(stored)) throw error(HttpStatus.BAD_REQUEST, "This role cannot be edited", "ROLE_NOT_EDITABLE"); + String name = requireName(r); + requireFree(name, id); + // Send every persisted field back: /role/save recomputes level and tracekey from the parent, and a merge + // without the children would orphan them. + Map role = new HashMap<>(); + for (String k : List.of("id", "level", "tracekey", "createBy", "createDate")) role.put(k, stored.get(k)); + role.put("id", id); + role.put("name", name); + Long parent = idOf(stored.get("parent")); + if (parent != null) role.put("parent", Map.of("id", parent)); + // children go back exactly as stored: services-system re-saves each one from this payload, and a changed list would null their parentid + role.put("children", stored.get("children") instanceof List l ? l : List.of()); + role.put("doneBy", caller.getUsername()); + save(role); + // ponytail: ignore-case match, so a case-only rename failure goes unnoticed; /role/save gives no error signal. + Map reread = find(id); + if (!name.equalsIgnoreCase(String.valueOf(reread.get("name")))) { + throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED"); + } + return clean(reread); + } + + public static boolean isProtected(Map role) { + return PROTECTED.contains(role.get("name")); + } + + static Long idOf(Object ref) { + if (ref instanceof Number n) return n.longValue(); + if (ref instanceof Map m && m.get("id") instanceof Number n) return n.longValue(); + return null; + } + + static boolean isHidden(Map role) { + return HIDDEN.contains(role.get("name")); + } + + private String requireName(AdminRoleRequest r) { + if (r == null || !StringUtils.hasText(r.name())) throw error(HttpStatus.BAD_REQUEST, "Role name is required", "REQUIRED_FIELD"); + return r.name().trim(); + } + + /** ponytail: check-then-save is not atomic; the DB unique key on name is the backstop. */ + private void requireFree(String name, Long ownId) { + if (all().stream().anyMatch(x -> name.equalsIgnoreCase(String.valueOf(x.get("name"))) && !(ownId != null && ownId.equals(idOf(x))))) { + throw error(HttpStatus.CONFLICT, "Role name is already taken", "ROLE_NAME_TAKEN"); + } + } + + private List> all() { + List> body = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_FIND_ALL), MAP_LIST).getBody(); + return body == null ? List.of() : body; + } + + private Map save(Map role) { + ResponseEntity> ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role); + // services-system swallows save errors and returns the unsaved entity, so a missing id means it failed. + if (ent.getBody() == null || ent.getBody().get("id") == null) { + throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED"); + } + return ent.getBody(); + } + + private static Map clean(Map role) { + Map out = new LinkedHashMap<>(); + out.put("id", idOf(role.get("id"))); + out.put("name", role.get("name")); + out.put("level", role.get("level")); + Long parent = idOf(role.get("parent")); + out.put("parent", parent == null ? null : Map.of("id", parent)); + return out; + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + return caller; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + private static CodedResponseStatusException notFound() { + return error(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND"); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code) { + return new CodedResponseStatusException(status, reason, code); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java new file mode 100644 index 0000000..b701687 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java @@ -0,0 +1,137 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGrantsRequest; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.service.AdminAclService; +import com.solvway.mobile.api.service.AdminRoleService; +import com.solvway.mobile.api.useraccess.AdminModule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminRoleControllerTest { + + @Mock private AdminRoleService roles; + @Mock private AdminAclService acl; + @InjectMocks private AdminRoleController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void everyHandlerIsAuthenticatedAndGuardedByTheRightModule() { + for (Method m : AdminRoleController.class.getDeclaredMethods()) { + if (m.getDeclaringClass() != AdminRoleController.class || m.isSynthetic()) continue; + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + List modules = Arrays.asList(m.getAnnotation(AdminModule.class).value()); + if (m.getName().equals("list") || m.getName().equals("getById")) { + assertThat(modules).as(m.getName()).containsExactlyInAnyOrder("BO_ROLES", "BO_USERS"); + } else { + assertThat(modules).as(m.getName()).containsExactly("BO_ROLES"); + } + } + } + + @Test + void list_returnsRoles() throws Exception { + when(roles.list()).thenReturn(List.of(Map.of("id", 4, "name", "ROLE_SALES"))); + mvc.perform(get("/api/admin/roles")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value("ROLE_SALES")); + } + + @Test + void getById_returnsRole() throws Exception { + when(roles.get(4L)).thenReturn(Map.of("id", 4, "name", "ROLE_SALES")); + mvc.perform(get("/api/admin/roles/4")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(4)); + } + + @Test + void getById_unknownRoleAnswers404() throws Exception { + when(roles.get(99L)).thenThrow(new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND")); + mvc.perform(get("/api/admin/roles/99")).andExpect(status().isNotFound()); + } + + @Test + void create_ignoresPortalExtrasAndPassesName() throws Exception { + when(roles.create(any())).thenReturn(Map.of("id", 9, "name", "ROLE_SALES")); + mvc.perform(post("/api/admin/roles").contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"ROLE_SALES\",\"parent\":{\"id\":1},\"level\":2}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9)); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminRoleRequest.class); + verify(roles).create(c.capture()); + assertThat(c.getValue().name()).isEqualTo("ROLE_SALES"); + } + + @Test + void create_duplicateAnswers409() throws Exception { + when(roles.create(any())).thenThrow(new CodedResponseStatusException(HttpStatus.CONFLICT, "Role name is already taken", "ROLE_NAME_TAKEN")); + mvc.perform(post("/api/admin/roles").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"ROLE_SALES\"}")) + .andExpect(status().isConflict()); + } + + @Test + void update_passesIdAndName() throws Exception { + when(roles.update(eq(4L), any())).thenReturn(Map.of("id", 4, "name", "ROLE_OPS")); + mvc.perform(put("/api/admin/roles/4").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"ROLE_OPS\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.name").value("ROLE_OPS")); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminRoleRequest.class); + verify(roles).update(eq(4L), c.capture()); + assertThat(c.getValue().name()).isEqualTo("ROLE_OPS"); + } + + @Test + void getModules_returnsGrantTree() throws Exception { + when(acl.getGrantTree(4L)).thenReturn(List.of(new AdminModuleGrant(40700000L, "BO_USERS", 40000000L, true))); + mvc.perform(get("/api/admin/roles/4/modules")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(40700000)) + .andExpect(jsonPath("$[0].parentId").value(40000000)) + .andExpect(jsonPath("$[0].granted").value(true)); + } + + @Test + void putModules_passesModuleIdsAndReturnsTree() throws Exception { + when(acl.updateGrants(eq(4L), any())).thenReturn(List.of(new AdminModuleGrant(40700000L, "BO_USERS", null, true))); + mvc.perform(put("/api/admin/roles/4/modules").contentType(MediaType.APPLICATION_JSON) + .content("{\"moduleIds\":[40700000,40800000]}")) + .andExpect(status().isOk()).andExpect(jsonPath("$[0].granted").value(true)); + verify(acl).updateGrants(4L, List.of(40700000L, 40800000L)); + } + + @Test + void putModules_lockoutAnswers400() throws Exception { + when(acl.updateGrants(eq(4L), any())).thenThrow(new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "lockout", "ACL_LOCKOUT")); + mvc.perform(put("/api/admin/roles/4/modules").contentType(MediaType.APPLICATION_JSON).content("{\"moduleIds\":[]}")) + .andExpect(status().isBadRequest()); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java new file mode 100644 index 0000000..ddca84a --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java @@ -0,0 +1,242 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminAclServiceTest { + + private static final String MODULES = "/module/findAllByArea/{area}"; + private static final String ADD = "/module/addModuleRole/{moduleId}/{roleId}"; + private static final String DEL = "/module/deleteModuleRole/{moduleId}/{roleId}"; + private static final long ROOT = 40000000L, USERS = 40700000L, ROLES = 40800000L; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminRoleService roles; + private AdminAclService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + roles = mock(AdminRoleService.class); + service = new AdminAclService(rest, auth, roles); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + when(roles.find(1L)).thenReturn(Map.of("id", 1L, "name", "ROLE_SUPER_ADMIN")); + when(roles.find(2L)).thenReturn(Map.of("id", 2L, "name", "ROLE_ADMIN")); + when(roles.find(4L)).thenReturn(Map.of("id", 4L, "name", "ROLE_SALES")); + when(roles.find(5L)).thenReturn(Map.of("id", 5L, "name", "ROLE_OPS")); + when(roles.find(99L)).thenThrow(new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND")); + // BO_USERS held by 1 and 4; BO_ROLES held by 1 and 5. Root's role list comes first, so later modules see bare parent ids. + stubModules( + module(ROOT, "BO_ROOT", null, 1), + module(USERS, "BO_USERS", ROOT, 1, 4), + module(ROLES, "BO_ROLES", Map.of("id", ROOT, "name", "BO_ROOT"), 1, 5)); + caller(5); + } + + @AfterEach + void close() { http.close(); } + + private static Map module(long id, String name, Object parent, long... roleIds) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("parent", parent); + m.put("type", parent == null ? "R" : "M"); + List rs = new ArrayList<>(); + for (long r : roleIds) rs.add(Map.of("id", r, "name", "R" + r)); + m.put("roles", rs); + return m; + } + + private void stubModules(Map... modules) { + when(rest.getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"))).thenReturn(ResponseEntity.ok(List.of(modules))); + } + + private void caller(long... roleIds) { + User u = new User(); + u.setId(50L); + List rs = new ArrayList<>(); + for (long id : roleIds) { + Role r = new Role(); + r.setId(id); + rs.add(r); + } + u.setRoles(rs); + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + private void verifyNothingChanged() { + verify(rest, never()).getForEntity(eq(ADD), eq(Integer.class), any(), any()); + verify(rest, never()).getForEntity(eq(DEL), eq(Integer.class), any(), any()); + } + + @Test + void grantTree_listsBoModulesWithGrantedFlagAndParentIds() { + List tree = service.getGrantTree(4L); + // the type R root is not grantable, so it is not listed + assertThat(tree).containsExactly( + new AdminModuleGrant(USERS, "BO_USERS", ROOT, true), // parent came as a bare id + new AdminModuleGrant(ROLES, "BO_ROLES", ROOT, false)); // parent came as an object + } + + @Test + void grantTree_unknownRoleIs404() { + assertCoded(() -> service.getGrantTree(99L), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void grantTree_ofAHiddenRoleIs404() { + when(roles.find(3L)).thenReturn(Map.of("id", 3L, "name", "ROLE_MEMBER")); + assertCoded(() -> service.getGrantTree(2L), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + assertCoded(() -> service.getGrantTree(3L), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void update_rootModuleIsRefused() { + assertCoded(() -> service.updateGrants(4L, List.of(ROOT)), HttpStatus.BAD_REQUEST, "UNKNOWN_MODULE"); + verifyNothingChanged(); + } + + @Test + void update_addsOnlyMissingGrants() { + // 4 holds BO_USERS; wanting BO_USERS + BO_ROLES must add BO_ROLES only + service.updateGrants(4L, List.of(USERS, ROLES)); + verify(rest).getForEntity(eq(ADD), eq(Integer.class), eq(ROLES), eq(4L)); + verify(rest, never()).getForEntity(eq(ADD), eq(Integer.class), eq(USERS), any()); + verify(rest, never()).getForEntity(eq(DEL), eq(Integer.class), any(), any()); + } + + @Test + void update_removesOnlyDroppedGrants() { + service.updateGrants(4L, List.of()); + verify(rest).getForEntity(eq(DEL), eq(Integer.class), eq(USERS), eq(4L)); + verify(rest, never()).getForEntity(eq(ADD), eq(Integer.class), any(), any()); + } + + @Test + void update_sameSetChangesNothing() { + service.updateGrants(4L, List.of(USERS)); + verifyNothingChanged(); + } + + @Test + void update_returnsTheTreeAfterTheChange() { + assertThat(service.updateGrants(4L, List.of(USERS))).hasSize(2); + } + + @Test + void update_nonBoModuleIsRefused() { + assertCoded(() -> service.updateGrants(4L, List.of(USERS, 7000L)), HttpStatus.BAD_REQUEST, "UNKNOWN_MODULE"); + verifyNothingChanged(); + } + + @Test + void update_missingModuleIdsIsRefused() { + assertCoded(() -> service.updateGrants(4L, null), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + verifyNothingChanged(); + } + + @Test + void update_superAdminGrantsAreNotEditable() { + assertCoded(() -> service.updateGrants(1L, List.of(USERS)), HttpStatus.BAD_REQUEST, "ROLE_NOT_EDITABLE"); + verifyNothingChanged(); + } + + @Test + void update_hiddenRoleIs404() { + assertCoded(() -> service.updateGrants(2L, List.of(USERS)), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + verifyNothingChanged(); + } + + @Test + void update_unknownRoleIs404() { + assertCoded(() -> service.updateGrants(99L, List.of()), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + verifyNothingChanged(); + } + + @Test + void update_removingBoRolesFromTheCallersOnlyGrantingRoleIsALockout() { + caller(5, 2); // role 2 is attached to every admin and does not count + assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.BAD_REQUEST, "ACL_LOCKOUT"); + verifyNothingChanged(); + } + + @Test + void update_removingBoRolesIsFineWhenAnotherCallerRoleStillGrantsIt() { + stubModules( + module(ROOT, "BO_ROOT", null, 1), + module(USERS, "BO_USERS", ROOT, 1, 4), + module(ROLES, "BO_ROLES", ROOT, 1, 5, 6)); + caller(5, 6, 2); + service.updateGrants(5L, List.of()); + verify(rest).getForEntity(eq(DEL), eq(Integer.class), eq(ROLES), eq(5L)); + } + + @Test + void update_keepingBoRolesOnTheCallersRoleIsFine() { + service.updateGrants(5L, List.of(ROLES, USERS)); + verify(rest).getForEntity(eq(ADD), eq(Integer.class), eq(USERS), eq(5L)); + verify(rest, never()).getForEntity(eq(DEL), eq(Integer.class), any(), any()); + } + + @Test + void update_editingAnotherRoleNeverLocksOut() { + service.updateGrants(4L, List.of(ROLES)); + verify(rest).getForEntity(eq(ADD), eq(Integer.class), eq(ROLES), eq(4L)); + } + + @Test + void update_superAdminCallerIsNotSubjectToLockout() { + caller(1); + service.updateGrants(5L, List.of()); + verify(rest).getForEntity(eq(DEL), eq(Integer.class), eq(ROLES), eq(5L)); + } + + @Test + void update_unresolvedCallerIsUnauthorized() { + when(auth.loadUserByToken("tok")).thenReturn(null); + assertCoded(() -> service.updateGrants(4L, List.of()), HttpStatus.UNAUTHORIZED, "UNAUTHORIZED"); + verifyNothingChanged(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java new file mode 100644 index 0000000..5d37194 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java @@ -0,0 +1,233 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminRoleServiceTest { + + private static final String FIND_ALL = "/role/findAll"; + private static final String SAVE = "/role/save"; + + private RestTemplateCustomUtil rest; + private AdminRoleService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminRoleService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setUsername("boss"); + when(auth.loadUserByToken("tok")).thenReturn(caller); + stubRoles(stored()); + } + + @AfterEach + void close() { http.close(); } + + private static Map role(long id, String name, Object parent, int level, String tracekey) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("level", level); + m.put("tracekey", tracekey); + m.put("parent", parent); + m.put("children", List.of()); + m.put("createBy", "sys"); + m.put("createDate", 1700000000000L); + return m; + } + + private static List> stored() { + Map sales = role(4, "ROLE_SALES", Map.of("id", 1, "name", "ROLE_SUPER_ADMIN", "level", 1, "tracekey", "ROLE_SUPER_ADMIN"), + 2, "ROLE_SUPER_ADMIN/ROLE_SALES"); + sales.put("children", List.of(Map.of("id", 9L, "name", "ROLE_SALES_JR", "createBy", "sys", "createDate", 1L, "parent", 4L))); + return List.of( + role(1, "ROLE_SUPER_ADMIN", null, 1, "ROLE_SUPER_ADMIN"), + role(2, "ROLE_ADMIN", Map.of("id", 1), 2, "ROLE_SUPER_ADMIN/ROLE_ADMIN"), + role(3, "ROLE_MEMBER", null, 1, "ROLE_MEMBER"), + sales); + } + + private void stubRoles(List> first, List>... later) { + var stub = when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(first)); + for (var l : later) stub = stub.thenReturn(ResponseEntity.ok(l)); + } + + private void stubSave(Map saved) { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(saved)); + } + + private Map savedBody() { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + @Test + void list_hidesMemberAndAdminRoles() { + assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("ROLE_SUPER_ADMIN", "ROLE_SALES"); + } + + @Test + void list_returnsOnlyPortalFields() { + Map sales = service.list().get(1); + assertThat(sales).containsOnlyKeys("id", "name", "level", "parent"); + assertThat(sales.get("parent")).isEqualTo(Map.of("id", 1L)); + } + + @Test + void get_returnsVisibleRole() { + assertThat(service.get(4L).get("name")).isEqualTo("ROLE_SALES"); + } + + @ParameterizedTest + @ValueSource(longs = {2, 3, 99}) + void get_hiddenOrUnknownRoleIs404(long id) { + assertCoded(() -> service.get(id), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void create_savesUnderSuperAdminWithActor() { + Map created = role(10, "ROLE_OPS", Map.of("id", 1), 2, "ROLE_SUPER_ADMIN/ROLE_OPS"); + stubSave(created); + List> after = new java.util.ArrayList<>(stored()); + after.add(created); + stubRoles(stored(), after); + + Map out = service.create(new AdminRoleRequest(" ROLE_OPS ")); + + Map body = savedBody(); + assertThat(body.get("name")).isEqualTo("ROLE_OPS"); + assertThat(body.get("parent")).isEqualTo(Map.of("id", 1L)); + assertThat(body.get("children")).isEqualTo(List.of()); + assertThat(body.get("createBy")).isEqualTo("boss"); + assertThat(body.get("doneBy")).isEqualTo("boss"); + assertThat(body.get("createDate")).isInstanceOf(Long.class); + assertThat(body).doesNotContainKey("id"); + assertThat(out.get("id")).isEqualTo(10L); + assertThat(out.get("name")).isEqualTo("ROLE_OPS"); + } + + @Test + void create_nameIsRequired() { + assertCoded(() -> service.create(new AdminRoleRequest(" ")), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(new AdminRoleRequest(null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @ParameterizedTest + @ValueSource(strings = {"ROLE_SALES", "role_sales", "ROLE_ADMIN", "ROLE_MEMBER"}) + void create_duplicateNameIsRefusedCaseInsensitively(String name) { + assertCoded(() -> service.create(new AdminRoleRequest(name)), HttpStatus.CONFLICT, "ROLE_NAME_TAKEN"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_failedSaveIsReported() { + // services-system swallows save errors and returns the unsaved entity (no id) + stubSave(new HashMap<>(Map.of("name", "ROLE_OPS"))); + assertCoded(() -> service.create(new AdminRoleRequest("ROLE_OPS")), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED"); + } + + @Test + void rename_keepsStoredLevelParentTracekeyChildrenAndCreateFields() { + Map renamed = role(4, "ROLE_REVENUE", Map.of("id", 1), 2, "ROLE_SUPER_ADMIN/ROLE_REVENUE"); + stubSave(renamed); + List> after = List.of(stored().get(0), renamed); + stubRoles(stored(), after); + + Map out = service.update(4L, new AdminRoleRequest("ROLE_REVENUE")); + + Map body = savedBody(); + assertThat(body.get("id")).isEqualTo(4L); + assertThat(body.get("name")).isEqualTo("ROLE_REVENUE"); + assertThat(body.get("level")).isEqualTo(2); + assertThat(body.get("tracekey")).isEqualTo("ROLE_SUPER_ADMIN/ROLE_SALES"); + assertThat(body.get("parent")).isEqualTo(Map.of("id", 1L)); + // full nested objects pass through: services-system parseChild re-saves each child from them + assertThat(body.get("children")).isEqualTo(stored().get(3).get("children")); + assertThat(body.get("createBy")).isEqualTo("sys"); + assertThat(body.get("createDate")).isEqualTo(1700000000000L); + assertThat(body.get("doneBy")).isEqualTo("boss"); + assertThat(out.get("name")).isEqualTo("ROLE_REVENUE"); + } + + @Test + void rename_toItsOwnNameIsAllowed() { + stubSave(stored().get(3)); + assertThat(service.update(4L, new AdminRoleRequest("role_sales")).get("id")).isEqualTo(4L); + } + + @Test + void rename_toAnotherRolesNameIsRefused() { + assertCoded(() -> service.update(4L, new AdminRoleRequest("role_admin")), HttpStatus.CONFLICT, "ROLE_NAME_TAKEN"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @ParameterizedTest + @ValueSource(longs = {1, 2, 3}) + void rename_builtInRolesAreNotEditable(long id) { + assertCoded(() -> service.update(id, new AdminRoleRequest("ROLE_X")), HttpStatus.BAD_REQUEST, "ROLE_NOT_EDITABLE"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @Test + void rename_unknownRoleIs404() { + assertCoded(() -> service.update(99L, new AdminRoleRequest("ROLE_X")), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void rename_silentlyFailedSaveIsReported() { + // /role/save swallows errors; the reread still shows the old name + stubSave(stored().get(3)); + assertCoded(() -> service.update(4L, new AdminRoleRequest("ROLE_REVENUE")), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED"); + } + + @Test + void isProtected_matchesBuiltInRoleNames() { + assertThat(AdminRoleService.isProtected(stored().get(0))).isTrue(); + assertThat(AdminRoleService.isProtected(stored().get(1))).isTrue(); + assertThat(AdminRoleService.isProtected(stored().get(2))).isTrue(); + assertThat(AdminRoleService.isProtected(stored().get(3))).isFalse(); + } +}