refactor(系统设置): 用户组接口增加权限校验测试用例

--story=1012250 --user=陈建星 系统设置-用户组管理 https://www.tapd.cn/55049933/s/1390501
This commit is contained in:
jianxing 2023-07-11 10:06:25 +08:00 committed by fit2-zhao
parent 56f2b63eb6
commit 01a8a95088
10 changed files with 248 additions and 458 deletions

View File

@ -12,13 +12,6 @@ public class PermissionConstants {
public static final String SYSTEM_USER_ROLE_DELETE = "SYSTEM_USER_ROLE:READ+DELETE";
/*------ end: SYSTEM_USER_ROLE ------*/
/*------ start: SYSTEM_USER_ROLE_RELATION ------*/
public static final String SYSTEM_USER_ROLE_RELATION_READ = "SYSTEM_USER_ROLE_RELATION_READ:READ";
public static final String SYSTEM_USER_ROLE_RELATION_ADD = "SYSTEM_USER_ROLE_RELATION_READ:READ+ADD";
public static final String SYSTEM_USER_ROLE_RELATION_UPDATE = "SYSTEM_USER_ROLE_RELATION_READ:READ+UPDATE";
public static final String SYSTEM_USER_ROLE_RELATION_DELETE = "SYSTEM_USER_ROLE_RELATION_READ:READ+DELETE";
/*------ end: SYSTEM_USER_ROLE_RELATION ------*/
public static final String SYSTEM_USER_READ = "SYSTEM_USER:READ";
public static final String SYSTEM_USER_READ_ADD = "SYSTEM_USER:READ+ADD";
public static final String SYSTEM_USER_READ_IMPORT = "SYSTEM_USER:READ+IMPORT";

View File

@ -2,6 +2,7 @@ package io.metersphere.sdk.util;
import io.metersphere.sdk.constants.InternalUserRole;
import io.metersphere.sdk.dto.SessionUser;
import io.metersphere.sdk.service.BaseUserRoleService;
import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRolePermission;
import jakarta.servlet.http.HttpServletRequest;
@ -167,8 +168,8 @@ public class SessionUtils {
private static Set<String> getSystemPermissions(Map<String, List<UserRolePermission>> userRolePermissions, Map<String, UserRole> role, SessionUser user) {
return user.getUserRoleRelations().stream()
.filter(ug -> role.get(ug.getId()) != null && StringUtils.equals(role.get(ug.getId()).getType(), "SYSTEM"))
.filter(ug -> StringUtils.equals(ug.getSourceId(), "system") || StringUtils.equals(ug.getSourceId(), "'adminSourceId'"))
.filter(ug -> role.get(ug.getId()) != null && StringUtils.equals(role.get(ug.getId()).getType(), BaseUserRoleService.SYSTEM_TYPE))
.filter(ug -> StringUtils.equals(ug.getSourceId(), BaseUserRoleService.SYSTEM_TYPE) || StringUtils.equals(ug.getSourceId(), "'adminSourceId'"))
.flatMap(ug -> userRolePermissions.get(ug.getId()).stream())
.map(UserRolePermission::getPermissionId)
.collect(Collectors.toSet());

View File

@ -4,15 +4,20 @@ import base.param.InvalidateParamInfo;
import base.param.ParamGeneratorFactory;
import com.jayway.jsonpath.JsonPath;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.constants.UserRoleType;
import io.metersphere.sdk.controller.handler.result.IResultCode;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Pager;
import io.metersphere.sdk.domain.OperationLogExample;
import io.metersphere.sdk.mapper.OperationLogMapper;
import io.metersphere.system.domain.UserRolePermission;
import io.metersphere.system.mapper.UserRolePermissionMapper;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import jakarta.annotation.Resource;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@ -20,6 +25,7 @@ import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@ -27,8 +33,11 @@ import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Supplier;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ -37,11 +46,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public abstract class BaseTest {
@Resource
private MockMvc mockMvc;
protected MockMvc mockMvc;
protected static String sessionId;
protected static String csrfToken;
protected static AuthInfo adminAuthInfo;
protected static Map<String, AuthInfo> permissionAuthInfoMap = new HashMap(3);
@Resource
private OperationLogMapper operationLogMapper;
@Resource
private UserRolePermissionMapper userRolePermissionMapper;
/**
* 可以重写该方法定义 BASE_PATH
@ -52,30 +65,45 @@ public abstract class BaseTest {
@BeforeEach
public void login() throws Exception {
if (StringUtils.isAnyBlank(sessionId, csrfToken)) {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login")
.content("{\"username\":\"admin\",\"password\":\"metersphere\"}")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId");
csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken");
if (this.adminAuthInfo == null) {
this.adminAuthInfo = initAuthInfo("admin", "metersphere");
this.sessionId = this.adminAuthInfo.getSessionId();
this.csrfToken = this.adminAuthInfo.getCsrfToken();
}
if (permissionAuthInfoMap.isEmpty()) {
// 获取系统组织项目对应的权限测试用户的认证信息
// 暂时只支持 SYSTEM
// todo 补充 ORGANIZATION PROJECT
String permissionType = UserRoleType.SYSTEM.name();
AuthInfo authInfo = initAuthInfo(permissionType, "metersphere");
permissionAuthInfoMap.put(permissionType, authInfo);
}
}
protected MockHttpServletRequestBuilder getPostRequestBuilder(String url, Object param, Object... uriVariables) {
private AuthInfo initAuthInfo(String username, String password) throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login")
.content(String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
String sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId");
String csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken");
return new AuthInfo(sessionId, csrfToken);
}
private MockHttpServletRequestBuilder getPostRequestBuilder(String url, Object param, Object... uriVariables) {
return MockMvcRequestBuilders.post(getBasePath() + url, uriVariables)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.header(SessionConstants.HEADER_TOKEN, adminAuthInfo.getSessionId())
.header(SessionConstants.CSRF_TOKEN, adminAuthInfo.getCsrfToken())
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON);
}
protected MockHttpServletRequestBuilder getRequestBuilder(String url, Object... uriVariables) {
private MockHttpServletRequestBuilder getRequestBuilder(String url, Object... uriVariables) {
return MockMvcRequestBuilders.get(getBasePath() + url, uriVariables)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken);
.header(SessionConstants.HEADER_TOKEN, adminAuthInfo.getSessionId())
.header(SessionConstants.CSRF_TOKEN, adminAuthInfo.getCsrfToken());
}
protected ResultActions requestPost(String url, Object param, Object... uriVariables) throws Exception {
@ -208,4 +236,136 @@ public abstract class BaseTest {
}
System.out.println("paramValidateTest-end: ====================================");
}
protected void requestPostPermissionTest(String permissionId, String url, Object param, Object... uriVariables) throws Exception {
requestPermissionTest(permissionId, url, () -> getPermissionPostRequestBuilder(permissionId, url, param, uriVariables));
}
/**
* 校验权限
* 实现步骤
* 1. application.properties 配置权限的初始化 sql
* spring.sql.init.mode=always
* spring.sql.init.schema-locations=classpath*:dml/init_permission_test.sql
* 2. init_permission_test.sql 中配置权限
* 初始化名称为 permissionId 前缀SYSTEM, ORGANIZATION, PROJECT的用户组和用户并关联
* 3. 向该用户组中添加权限测试是否生效删除权限测试是否可以访问
* @param permissionId
* @param url
* @param requestBuilderGetFunc 请求构造器一个 builder 只能使用一次需要重新生成
* @throws Exception
*/
private void requestPermissionTest(String permissionId, String url, Supplier<MockHttpServletRequestBuilder> requestBuilderGetFunc) throws Exception {
String roleId = permissionId.split("_")[0];
// 先给初始化的用户组添加权限
UserRolePermission userRolePermission = initUserRolePermission(roleId, permissionId);
// 添加后刷新下权限
refreshUserPermission(permissionId);
int status = mockMvc.perform(requestBuilderGetFunc.get())
.andReturn()
.getResponse()
.getStatus();
// 校验是否有权限
if (status == HttpStatus.FORBIDDEN.value()) {
throw new MSException(String.format("接口 %s 权限校验失败 %s", getBasePath() + url, permissionId));
}
// 删除权限
userRolePermissionMapper.deleteByPrimaryKey(userRolePermission.getId());
// 删除后刷新下权限
refreshUserPermission(permissionId);
// 删除权限后调用接口校验是否没有权限
status = mockMvc.perform(requestBuilderGetFunc.get())
.andReturn()
.getResponse()
.getStatus();
if (status != HttpStatus.FORBIDDEN.value()) {
throw new MSException(String.format("接口 %s 没有设置权限 %s", getBasePath() + url, permissionId));
}
}
/**
* 调用 is-login 接口刷新权限
* @param permissionId
* @throws Exception
*/
private void refreshUserPermission(String permissionId) throws Exception {
AuthInfo authInfo = getPermissionAuthInfo(permissionId);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/is-login")
.header(SessionConstants.HEADER_TOKEN, authInfo.getSessionId())
.header(SessionConstants.CSRF_TOKEN, authInfo.getCsrfToken());
mockMvc.perform(requestBuilder);
}
protected void requestGetPermissionTest(String permissionId, String url, Object... uriVariables) throws Exception {
requestPermissionTest(permissionId, url, () -> getPermissionRequestBuilder(permissionId, url, uriVariables));
}
/**
* 给用户组绑定对应权限
* @param roleId
* @param permissionId
* @return
*/
private UserRolePermission initUserRolePermission(String roleId, String permissionId) {
UserRolePermission userRolePermission = new UserRolePermission();
userRolePermission.setRoleId(roleId);
userRolePermission.setId(UUID.randomUUID().toString());
userRolePermission.setPermissionId(permissionId);
userRolePermissionMapper.insert(userRolePermission);
return userRolePermission;
}
private MockHttpServletRequestBuilder getPermissionPostRequestBuilder(String permissionId, String url, Object param, Object... uriVariables) {
AuthInfo authInfo = getPermissionAuthInfo(permissionId);
return MockMvcRequestBuilders.post(getBasePath() + url, uriVariables)
.header(SessionConstants.HEADER_TOKEN, authInfo.getSessionId())
.header(SessionConstants.CSRF_TOKEN, authInfo.getCsrfToken())
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON);
}
private AuthInfo getPermissionAuthInfo(String permissionId) {
return permissionAuthInfoMap.get(permissionId.split("_")[0]);
}
private MockHttpServletRequestBuilder getPermissionRequestBuilder(String permissionId, String url, Object... uriVariables) {
AuthInfo authInfo = getPermissionAuthInfo(permissionId);
return MockMvcRequestBuilders.get(getBasePath() + url, uriVariables)
.header(SessionConstants.HEADER_TOKEN, authInfo.getSessionId())
.header(SessionConstants.CSRF_TOKEN, authInfo.getCsrfToken());
}
public String getSessionId() {
return adminAuthInfo.getSessionId();
}
public String getCsrfToken() {
return adminAuthInfo.getCsrfToken();
}
@Data
class AuthInfo {
private String sessionId;
private String csrfToken;
public AuthInfo(String sessionId, String csrfToken) {
this.sessionId = sessionId;
this.csrfToken = csrfToken;
}
public String getSessionId() {
return sessionId;
}
public String getCsrfToken() {
return csrfToken;
}
}
}

View File

@ -39,7 +39,7 @@ public class GlobalUserRoleRelationController {
@PostMapping("/list")
@Operation(summary = "获取全局用户组对应的用户列表")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_RELATION_READ)
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_READ)
public Pager<List<UserRoleRelationUserDTO>> list(@Validated @RequestBody GlobalUserRoleRelationQueryRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(), true);
return PageUtils.setPageInfo(page, globalUserRoleRelationService.list(request));
@ -47,7 +47,7 @@ public class GlobalUserRoleRelationController {
@PostMapping("/add")
@Operation(summary = "创建全局用户组和用户的关联关系")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_RELATION_ADD)
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_UPDATE)
@Log(type = OperationLogType.ADD, expression = "#msClass.addLog(#request)", msClass = GlobalUserRoleRelationLogService.class)
public UserRoleRelation add(@Validated({Created.class}) @RequestBody GlobalUserRoleRelationUpdateRequest request) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
@ -58,7 +58,7 @@ public class GlobalUserRoleRelationController {
@GetMapping("/delete/{id}")
@Operation(summary = "删除全局用户组和用户的关联关系")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_RELATION_DELETE)
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_UPDATE)
@Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#id)", msClass = GlobalUserRoleRelationLogService.class)
public void delete(@PathVariable String id) {
globalUserRoleRelationService.delete(id);

View File

@ -1,6 +1,7 @@
package io.metersphere.system.controller;
import com.jayway.jsonpath.JsonPath;
import base.BaseTest;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.dto.BasePageRequest;
@ -9,12 +10,13 @@ import io.metersphere.sdk.util.Pager;
import io.metersphere.system.domain.AuthSource;
import io.metersphere.system.request.AuthSourceRequest;
import io.metersphere.utils.JsonUtils;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -29,17 +31,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class AuthSourceControllerTest {
@Resource
private MockMvc mockMvc;
private static String sessionId;
private static String csrfToken;
public class AuthSourceControllerTest extends BaseTest {
public static final String AUTH_SOURCE_ADD = "/system/authsource/add";
public static final String AUTH_SOURCE_List = "/system/authsource/list";
public static final String AUTH_SOURCE_LIST = "/system/authsource/list";
public static final String AUTH_SOURCE_UPDATE = "/system/authsource/update";
@ -49,19 +45,6 @@ public class AuthSourceControllerTest {
private static final ResultMatcher CLIENT_ERROR_MATCHER = status().is4xxClientError();
@BeforeEach
public void login() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login")
.content("{\"username\":\"admin\",\"password\":\"metersphere\"}")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId");
csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken");
}
@Test
@Order(1)
public void testAddSource() throws Exception {
@ -71,6 +54,8 @@ public class AuthSourceControllerTest {
authSource.setType("CAS");
this.requestPost(AUTH_SOURCE_ADD, authSource);
// @@校验权限
requestPostPermissionTest(PermissionConstants.SYSTEM_SETTING_READ_CREAT, AUTH_SOURCE_ADD, authSource);
}
@Test
@ -79,7 +64,9 @@ public class AuthSourceControllerTest {
BasePageRequest basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1);
basePageRequest.setPageSize(10);
this.requestPost(AUTH_SOURCE_List, basePageRequest);
this.requestPost(AUTH_SOURCE_LIST, basePageRequest);
requestPostPermissionTest(PermissionConstants.SYSTEM_SETTING_READ, AUTH_SOURCE_LIST, basePageRequest);
}
@ -93,13 +80,18 @@ public class AuthSourceControllerTest {
authSource.setName("更新");
authSource.setType("CAS");
this.requestPost(AUTH_SOURCE_UPDATE, authSource);
requestPostPermissionTest(PermissionConstants.SYSTEM_SETTING_READ_UPDATE, AUTH_SOURCE_UPDATE, authSource);
}
@Test
@Order(4)
public void testUpdateStatus() throws Exception {
List<AuthSourceRequest> authSourceList = this.getAuthSourceList();
this.requestGet(AUTH_SOURCE_UPDATE + "/" + authSourceList.get(0).getId() + "/status/false");
String url = AUTH_SOURCE_UPDATE + "/" + authSourceList.get(0).getId() + "/status/false";
this.requestGet(url);
requestGetPermissionTest(PermissionConstants.SYSTEM_SETTING_READ_UPDATE, url);
}
@ -107,7 +99,10 @@ public class AuthSourceControllerTest {
@Order(5)
public void testGetSourceById() throws Exception {
List<AuthSourceRequest> authSourceList = this.getAuthSourceList();
this.requestGet(AUTH_SOURCE_GET + authSourceList.get(0).getId());
String url = AUTH_SOURCE_GET + authSourceList.get(0).getId();
this.requestGet(url);
requestGetPermissionTest(PermissionConstants.SYSTEM_SETTING_READ, url);
}
@ -115,7 +110,10 @@ public class AuthSourceControllerTest {
@Order(6)
public void testDelSourceById() throws Exception {
List<AuthSourceRequest> authSourceList = this.getAuthSourceList();
this.requestGet(AUTH_SOURCE_DELETE + authSourceList.get(0).getId());
String url = AUTH_SOURCE_DELETE + authSourceList.get(0).getId();
this.requestGet(url);
requestGetPermissionTest(PermissionConstants.SYSTEM_SETTING_READ_DELETE, url);
}
@ -151,7 +149,7 @@ public class AuthSourceControllerTest {
BasePageRequest basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1);
basePageRequest.setPageSize(10);
MvcResult mvcResult = this.requestPost(AUTH_SOURCE_List, basePageRequest);
MvcResult mvcResult = this.requestPost(AUTH_SOURCE_LIST, basePageRequest);
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class);
Pager<?> returnPager = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), Pager.class);

View File

@ -1,393 +0,0 @@
package io.metersphere.system.controller;
import com.jayway.jsonpath.JsonPath;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.domain.SystemParameter;
import io.metersphere.system.domain.UserRolePermission;
import io.metersphere.system.mapper.UserRolePermissionMapper;
import io.metersphere.system.request.AuthSourceRequest;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class AuthSourceNonePermissionTest {
@Resource
private MockMvc mockMvc;
private static String sessionId;
private static String csrfToken;
private static final String NONE_ROLE_USERNAME = "permission@fit2cloud.com";
private static final String NONE_ROLE_PASSWORD = "permission@fit2cloud.com";
private static final String ROLE_ID = "org_admin";
public static final String AUTH_SOURCE_ADD = "/system/authsource/add";
public static final String AUTH_SOURCE_List = "/system/authsource/list";
public static final String AUTH_SOURCE_UPDATE = "/system/authsource/update";
public static final String AUTH_SOURCE_GET = "/system/authsource/get/";
public static final String AUTH_SOURCE_DELETE = "/system/authsource/delete/";
private static final ResultMatcher CHECK_RESULT_MATHER = status().isForbidden();
private static final ResultMatcher CHECK_RESULT_OK = status().isOk();
public static final String BASE_INFO_SAVE_URL = "/system/parameter/save/base-info";
public static final String BASE_INFO_URL = "/system/parameter/get/base-info";
public static final String EMAIL_INFO_URL = "/system/parameter/get/email-info";
public static final String EMAIL_INFO_SAVE_URL = "/system/parameter/edit/email-info";
public static final String EMAIL_INFO_TEST_CONNECT_URL = "/system/parameter/test/email";
private static final ResultMatcher ERROR_REQUEST_MATCHER = status().is5xxServerError();
@Resource
private UserRolePermissionMapper userRolePermissionMapper;
@BeforeEach
public void login() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login")
.content("{\"username\":\"" + NONE_ROLE_USERNAME + "\",\"password\":\"" + NONE_ROLE_PASSWORD + "\"}")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId");
csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken");
}
public AuthSourceRequest getAuthSource() {
AuthSourceRequest authSource = new AuthSourceRequest();
authSource.setId(UUID.randomUUID().toString());
authSource.setConfiguration("123");
authSource.setName("测试CAS_" + UUID.randomUUID().toString());
authSource.setType("CAS");
return authSource;
}
/**
* 无权限
*
* @throws Exception
*/
@Test
@Order(1)
@Sql(scripts = {"/dml/init_permission_test.sql"},
config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED),
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public void testNoPermission() throws Exception {
//认证配置
AuthSourceRequest authSource = this.getAuthSource();
//校验权限: 添加认证权限
this.requestPost(AUTH_SOURCE_ADD, authSource, CHECK_RESULT_MATHER);
//权限校验: 查询认证权限
this.testGetSourceList(CHECK_RESULT_MATHER);
//权限校验: 修改认证权限
authSource.setName("测试CAS修改");
this.testUpdateSource(authSource, CHECK_RESULT_MATHER);
//权限校验: 修改认证权限状态
this.testUpdateStatus(authSource, CHECK_RESULT_MATHER);
//权限校验: 查询认证权限详情
this.testGetSourceById(authSource, CHECK_RESULT_MATHER);
//权限校验: 删除认证权限
this.testDelSourceById(authSource, CHECK_RESULT_MATHER);
//基本配置
List<SystemParameter> systemParameters = getSystemParameters();
//403
//权限校验: 保存+编辑基础信息
this.testSaveBaseInfo(systemParameters, CHECK_RESULT_MATHER);
//权限校验: 获取用户信息
this.testGetBaseInfo(CHECK_RESULT_MATHER);
//权限校验: 保存+编辑邮件设置
this.testEditEmailInfo(CHECK_RESULT_MATHER);
//权限校验: 获取邮件设置
this.testGetEmailInfo(CHECK_RESULT_MATHER);
//权限校验: 测试邮件连接
this.testEmailConnect(CHECK_RESULT_MATHER);
}
/**
* 只读权限
*
* @throws Exception
*/
@Test
@Order(2)
public void testReadPermission() throws Exception {
//添加读权限
addPermission(PermissionConstants.SYSTEM_SETTING_READ);
//获取最新权限
this.requestGet("/is-login", CHECK_RESULT_OK);
//认证配置
AuthSourceRequest authSource = this.getAuthSource();
//403
this.testAddSource(authSource, CHECK_RESULT_MATHER);
//200
this.testGetSourceList(CHECK_RESULT_OK);
this.testGetSourceById(authSource, CHECK_RESULT_OK);
//403
authSource.setName("测试CAS修改");
this.testUpdateSource(authSource, CHECK_RESULT_MATHER);
this.testUpdateStatus(authSource, CHECK_RESULT_MATHER);
this.testDelSourceById(authSource, CHECK_RESULT_MATHER);
//基本配置
List<SystemParameter> systemParameters = getSystemParameters();
//403
this.testSaveBaseInfo(systemParameters, CHECK_RESULT_MATHER);
//200
this.testGetBaseInfo(CHECK_RESULT_OK);
//403
this.testEditEmailInfo(CHECK_RESULT_MATHER);
//200
this.testGetEmailInfo(CHECK_RESULT_OK);
//有权限 连接不通返回500
this.testEmailConnect(ERROR_REQUEST_MATCHER);
}
@Test
@Order(3)
public void testAddPermission() throws Exception {
addPermission(PermissionConstants.SYSTEM_SETTING_READ_CREAT);
//获取最新权限
this.requestGet("/is-login", CHECK_RESULT_OK);
AuthSourceRequest authSource = this.getAuthSource();
//200
this.testAddSource(authSource, CHECK_RESULT_OK);
this.testGetSourceList(CHECK_RESULT_OK);
this.testGetSourceById(authSource, CHECK_RESULT_OK);
//403
authSource.setName("测试CAS修改");
this.testUpdateSource(authSource, CHECK_RESULT_MATHER);
this.testUpdateStatus(authSource, CHECK_RESULT_MATHER);
this.testDelSourceById(authSource, CHECK_RESULT_MATHER);
//基本配置
List<SystemParameter> systemParameters = getSystemParameters();
//200
this.testSaveBaseInfo(systemParameters, CHECK_RESULT_OK);
this.testGetBaseInfo(CHECK_RESULT_OK);
this.testEditEmailInfo(CHECK_RESULT_OK);
this.testGetEmailInfo(CHECK_RESULT_OK);
this.testEmailConnect(ERROR_REQUEST_MATCHER);
}
@Test
@Order(4)
public void testUpdatePermission() throws Exception {
addPermission(PermissionConstants.SYSTEM_SETTING_READ_UPDATE);
//获取最新权限
this.requestGet("/is-login", CHECK_RESULT_OK);
//认证配置
AuthSourceRequest authSource = this.getAuthSource();
//200
this.testAddSource(authSource, CHECK_RESULT_OK);
this.testGetSourceList(CHECK_RESULT_OK);
this.testGetSourceById(authSource, CHECK_RESULT_OK);
authSource.setName("测试CAS修改");
this.testUpdateSource(authSource, CHECK_RESULT_OK);
this.testUpdateStatus(authSource, CHECK_RESULT_OK);
//403
this.testDelSourceById(authSource, CHECK_RESULT_MATHER);
}
@Test
@Order(5)
public void testDeletePermission() throws Exception {
addPermission(PermissionConstants.SYSTEM_SETTING_READ_DELETE);
//获取最新权限
this.requestGet("/is-login", CHECK_RESULT_OK);
AuthSourceRequest authSource = this.getAuthSource();
//200
this.testAddSource(authSource, CHECK_RESULT_OK);
this.testGetSourceList(CHECK_RESULT_OK);
this.testGetSourceById(authSource, CHECK_RESULT_OK);
authSource.setName("测试CAS修改");
this.testUpdateSource(authSource, CHECK_RESULT_OK);
this.testUpdateStatus(authSource, CHECK_RESULT_OK);
this.testDelSourceById(authSource, CHECK_RESULT_OK);
}
private void addPermission(String permissionId) {
UserRolePermission permission = new UserRolePermission();
permission.setId(UUID.randomUUID().toString());
permission.setRoleId(ROLE_ID);
permission.setPermissionId(permissionId);
userRolePermissionMapper.insert(permission);
}
private void testSaveBaseInfo(List<SystemParameter> systemParameters, ResultMatcher resultMatcher) throws Exception {
this.requestPost(BASE_INFO_SAVE_URL, systemParameters, resultMatcher);
}
public void testGetBaseInfo(ResultMatcher resultMatcher) throws Exception {
this.requestGet(BASE_INFO_URL, resultMatcher);
}
public void testGetEmailInfo(ResultMatcher resultMatcher) throws Exception {
this.requestGet(EMAIL_INFO_URL, resultMatcher);
}
public void testEditEmailInfo(ResultMatcher resultMatcher) throws Exception {
List<SystemParameter> systemParameters = new ArrayList<>() {{
add(new SystemParameter() {{
setParamKey("smtp.host");
setParamValue("https://baidu.com");
setType("text");
}});
add(new SystemParameter() {{
setParamKey("smtp.port");
setParamValue("8080");
setType("text");
}});
add(new SystemParameter() {{
setParamKey("smtp.account");
setParamValue("aaa@fit2cloud.com");
setType("text");
}});
add(new SystemParameter() {{
setParamKey("smtp.ssl");
setParamValue("true");
setType("text");
}});
}};
this.requestPost(EMAIL_INFO_SAVE_URL, systemParameters, resultMatcher);
}
public void testEmailConnect(ResultMatcher resultMatcher) throws Exception {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("smtp.host", "https://baidu.com");
hashMap.put("smtp.port", "80");
hashMap.put("smtp.account", "aaa@fit2cloud.com");
hashMap.put("smtp.password", "test");
hashMap.put("smtp.from", "aaa@fit2cloud.com");
hashMap.put("smtp.recipient", "aaa@fit2cloud.com");
hashMap.put("smtp.ssl", "ture");
hashMap.put("smtp.tls", "false");
this.requestPost(EMAIL_INFO_TEST_CONNECT_URL, hashMap, resultMatcher);
}
private List<SystemParameter> getSystemParameters() {
List<SystemParameter> systemParameters = new ArrayList<>() {{
add(new SystemParameter() {{
setParamKey("base.url");
setParamValue("https://baidu.com");
setType("text");
}});
add(new SystemParameter() {{
setParamKey("base.prometheus.host");
setParamValue("http://127.0.0.1:1111");
setType("text");
}});
}};
return systemParameters;
}
private void testAddSource(AuthSourceRequest authSource, ResultMatcher resultMatcher) throws Exception {
this.requestPost(AUTH_SOURCE_ADD, authSource, resultMatcher);
}
public void testGetSourceList(ResultMatcher resultMatcher) throws Exception {
BasePageRequest basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1);
basePageRequest.setPageSize(10);
this.requestPost(AUTH_SOURCE_List, basePageRequest, resultMatcher);
}
public void testUpdateSource(AuthSourceRequest authSource, ResultMatcher resultMatcher) throws Exception {
this.requestPost(AUTH_SOURCE_UPDATE, authSource, resultMatcher);
}
public void testUpdateStatus(AuthSourceRequest authSource, ResultMatcher resultMatcher) throws Exception {
this.requestGet(AUTH_SOURCE_UPDATE + "/" + authSource.getId() + "/status/false", resultMatcher);
}
public void testGetSourceById(AuthSourceRequest authSource, ResultMatcher resultMatcher) throws Exception {
this.requestGet(AUTH_SOURCE_GET + authSource.getId(), resultMatcher);
}
public void testDelSourceById(AuthSourceRequest authSource, ResultMatcher resultMatcher) throws Exception {
this.requestGet(AUTH_SOURCE_DELETE + authSource.getId(), resultMatcher);
}
private MvcResult requestGet(String url, ResultMatcher resultMatcher) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(resultMatcher).andDo(print()).andReturn();
}
private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}

View File

@ -73,6 +73,9 @@ class GlobalUserRoleControllerTest extends BaseTest {
.map(InternalUserRole::getValue)
.toList();
Assertions.assertTrue(CollectionUtils.isSubCollection(internalUserRoleIds, userRoleIds));
// @@校验权限
requestGetPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_READ, LIST);
}
@Test
@ -99,6 +102,9 @@ class GlobalUserRoleControllerTest extends BaseTest {
// @@异常参数校验
createdGroupParamValidateTest(UserRoleUpdateRequestDefinition.class, ADD);
// @@校验权限
requestPostPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_ADD, ADD, request);
}
@Test
@ -136,6 +142,9 @@ class GlobalUserRoleControllerTest extends BaseTest {
// @@异常参数校验
updatedGroupParamValidateTest(UserRoleUpdateRequestDefinition.class, UPDATE);
// @@校验权限
requestPostPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_UPDATE, UPDATE, request);
}
@Test
@ -183,6 +192,8 @@ class GlobalUserRoleControllerTest extends BaseTest {
// @@操作非全局用户组异常
assertErrorCode(this.requestGet(PERMISSION_SETTING, getNonGlobalUserRole().getId()), GLOBAL_USER_ROLE_PERMISSION);
// @@校验权限
requestGetPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_READ, PERMISSION_SETTING, ADMIN.getValue());
}
@Test
@ -198,7 +209,7 @@ class GlobalUserRoleControllerTest extends BaseTest {
PermissionSettingUpdateRequest.PermissionUpdateRequest permission2
= new PermissionSettingUpdateRequest.PermissionUpdateRequest();
permission2.setEnable(false);
permission2.setId(PermissionConstants.SYSTEM_USER_ROLE_RELATION_READ);
permission2.setId(PermissionConstants.SYSTEM_USER_ROLE_READ);
add(permission2);
}});
@ -227,6 +238,9 @@ class GlobalUserRoleControllerTest extends BaseTest {
// @@异常参数校验
paramValidateTest(PermissionSettingUpdateRequestDefinition.class, PERMISSION_UPDATE);
// @@校验权限
requestPostPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_UPDATE, PERMISSION_UPDATE, request);
}
@Test
@ -249,6 +263,9 @@ class GlobalUserRoleControllerTest extends BaseTest {
// @@操作内置用户组异常
assertErrorCode(this.requestGet(DELETE, ADMIN.getValue()), INTERNAL_USER_ROLE_PERMISSION);
// @@校验权限
requestGetPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_DELETE, DELETE, addUserRole.getId());
}
/**

View File

@ -1,6 +1,7 @@
package io.metersphere.system.controller;
import base.BaseTest;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.dto.UserRoleRelationUserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.log.constants.OperationLogType;
@ -85,6 +86,9 @@ class GlobalUserRoleRelationControllerTest extends BaseTest {
// @@异常参数校验
paramValidateTest(GlobalUserRoleRelationQueryRequestDefinition.class, LIST);
// @@校验权限
requestPostPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_READ, LIST, request);
}
@Test
@ -127,6 +131,9 @@ class GlobalUserRoleRelationControllerTest extends BaseTest {
// @@异常参数校验
createdGroupParamValidateTest(GlobalUserRoleRelationUpdateRequestDefinition.class, ADD);
// @@校验权限
requestPostPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_UPDATE, ADD, request);
}
@Test
@ -155,6 +162,9 @@ class GlobalUserRoleRelationControllerTest extends BaseTest {
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
assertErrorCode(this.requestGet(DELETE, userRoleRelations.get(0).getId()),
USER_ROLE_RELATION_REMOVE_ADMIN_USER_PERMISSION);
// @@校验权限
requestGetPermissionTest(PermissionConstants.SYSTEM_USER_ROLE_UPDATE, DELETE, addUserRoleRelation.getId());
}
/**

View File

@ -26,6 +26,10 @@ spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
# 单元测试初始化权限 sql
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath*:dml/init_permission_test.sql
#
# spring.kafka
spring.kafka.bootstrap-servers=${embedded.kafka.brokerList}

View File

@ -1,14 +1,14 @@
-- 初始化一个没有任何权限的用户
-- 初始化用于权限测试的用户
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source,
last_project_id, create_user, update_user, deleted)
VALUES ('permission1', 'permission_test', 'permission@fit2cloud.com', MD5('permission@fit2cloud.com'), UNIX_TIMESTAMP() * 1000,
VALUES ('SYSTEM', 'SYSTEM', 'SYSTEM@fit2cloud.com', MD5('metersphere'),
UNIX_TIMESTAMP() * 1000,
UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin', false);
-- 初始化一个没有任何权限的用户组
-- 初始化一个用于权限测试的用户组,这里默认使用 SYSTEM 作为ID如果是组织和项目级别类似便于根据权限的前缀找到对应测试的用户组
INSERT INTO user_role (id, name, description, internal, type, create_time, update_time, create_user, scope_id)
VALUES ('permission_member', '权限测试账号', '权限测试账号', 1, 'SYSTEM', 1620674220005, 1620674220000, 'admin',
'GLOBAL');
VALUES ('SYSTEM', '系统级别权限校验', '', 1, 'SYSTEM', 1620674220005, 1620674220000, 'admin', 'GLOBAL');
-- 初始化用户和组的关系
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, create_user)
VALUES (uuid(), 'permission1', 'org_admin', 'SYSTEM', 1684747668375, 'admin');
VALUES ('SYSTEM', 'SYSTEM', 'SYSTEM', 'SYSTEM', 1684747668375, 'admin');