diff --git a/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/config/WebConfig.java b/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/config/WebConfig.java index 12f34aa37..29685e034 100644 --- a/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/config/WebConfig.java +++ b/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/config/WebConfig.java @@ -4,6 +4,7 @@ import com.google.common.base.Predicates; import com.xiaojukeji.know.streaming.km.common.constant.ApiPrefix; import com.xiaojukeji.know.streaming.km.common.utils.GitPropUtil; +import com.xiaojukeji.know.streaming.km.rest.interceptor.IdentityAuthorizationInterceptor; import com.xiaojukeji.know.streaming.km.rest.interceptor.PermissionInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -22,6 +23,9 @@ public class WebConfig implements WebMvcConfigurer { @Autowired private PermissionInterceptor permissionInterceptor; + @Autowired + private IdentityAuthorizationInterceptor identityAuthorizationInterceptor; + private static final String FE_INDEX_PAGE_HTML = "layout/index"; @Override @@ -47,6 +51,9 @@ public void addViewControllers(ViewControllerRegistry registry) { public void addInterceptors(InterceptorRegistry registry) { // 会进行拦截的接口 registry.addInterceptor(permissionInterceptor).addPathPatterns(ApiPrefix.API_PREFIX + "**", Constants.API_PREFIX + "/**"); + // 服务端权限校验:在登录校验之后执行(注册顺序即执行顺序), + // see https://github.com/didi/KnowStreaming/issues/1263 + registry.addInterceptor(identityAuthorizationInterceptor).addPathPatterns("/logi-security/**"); } @Override diff --git a/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/interceptor/IdentityAuthorizationInterceptor.java b/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/interceptor/IdentityAuthorizationInterceptor.java new file mode 100644 index 000000000..511919639 --- /dev/null +++ b/km-rest/src/main/java/com/xiaojukeji/know/streaming/km/rest/interceptor/IdentityAuthorizationInterceptor.java @@ -0,0 +1,219 @@ +/* + * Copyright contributors to KnowStreaming. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.xiaojukeji.know.streaming.km.rest.interceptor; + +import com.didiglobal.logi.log.ILog; +import com.didiglobal.logi.log.LogFactory; +import com.didiglobal.logi.security.common.vo.permission.PermissionTreeVO; +import com.didiglobal.logi.security.service.RoleService; +import com.didiglobal.logi.security.service.UserRoleService; +import com.didiglobal.logi.security.service.UserService; +import com.didiglobal.logi.security.util.HttpRequestUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * 服务端权限校验拦截器。 + * + * KnowStreaming 的角色/权限模型原本只被前端 UI 用来决定显示哪些菜单和按钮, + * 服务端唯一的 {@link PermissionInterceptor} 只校验了登录态,从不校验调用方 + * 的角色或权限点。任何已登录用户——哪怕只被授予了一个只读权限点——都可以直接 + * 调用身份管理接口(新增用户、创建角色、分配用户角色等)把自己提升为平台管理员。 + * + * 本拦截器在 {@link PermissionInterceptor} 完成登录校验之后执行,对会改变 + * 平台状态的身份/配置/资源赋权类接口按"HTTP 方法 + URL 后缀 -> 权限点"的映射 + * 做服务端权限校验;权限点 id 与 km-persistence 中 dml-logi.sql 初始化的 + * logi_security_permission 表保持一致。只读接口不受影响。 + * + * @see issue #1263 + */ +@Component +public class IdentityAuthorizationInterceptor implements HandlerInterceptor { + private static final ILog LOGGER = LogFactory.getLog(IdentityAuthorizationInterceptor.class); + + private static final String LOGI_API_PREFIX = "/logi-security/api/v1"; + + private static final int PERMISSION_SYSTEM_MANAGEMENT = 1595; + private static final int PERMISSION_USER_ADD = 1629; + private static final int PERMISSION_USER_EDIT = 1631; + private static final int PERMISSION_USER_DELETE = 1635; + private static final int PERMISSION_ROLE_CREATE = 1637; + private static final int PERMISSION_ROLE_UPDATE = 1639; + private static final int PERMISSION_ROLE_ASSIGN = 1641; + private static final int PERMISSION_ROLE_DELETE = 1643; + private static final int PERMISSION_CONFIG_ADD = 1623; + private static final int PERMISSION_CONFIG_EDIT = 1625; + private static final int PERMISSION_CONFIG_DELETE = 1627; + + /** + * 受保护接口的"HTTP 方法 + URL 后缀 -> 所需权限点"映射,按声明顺序匹配。 + */ + private static final List PROTECTED_ENDPOINTS = Arrays.asList( + // 用户管理 + protectedEndpoint(HttpMethod.PUT, "/user/add", PERMISSION_USER_ADD), + protectedEndpoint(HttpMethod.POST, "/user/edit", PERMISSION_USER_EDIT), + protectedEndpoint(HttpMethod.DELETE, "/user/.*", PERMISSION_USER_DELETE), + // 角色管理(更具体的后缀必须放在前缀规则之前) + protectedEndpoint(HttpMethod.PUT, "/role", PERMISSION_ROLE_UPDATE), + protectedEndpoint(HttpMethod.POST, "/role/assign", PERMISSION_ROLE_ASSIGN), + protectedEndpoint(HttpMethod.POST, "/role", PERMISSION_ROLE_CREATE), + protectedEndpoint(HttpMethod.DELETE, "/role/[^/]+/user/[^/]+", PERMISSION_ROLE_ASSIGN), + protectedEndpoint(HttpMethod.DELETE, "/role/.*", PERMISSION_ROLE_DELETE), + // 配置管理 + protectedEndpoint(HttpMethod.PUT, "/config/add", PERMISSION_CONFIG_ADD), + protectedEndpoint(HttpMethod.POST, "/config/edit", PERMISSION_CONFIG_EDIT), + protectedEndpoint(HttpMethod.POST, "/config/switch", PERMISSION_CONFIG_EDIT), + protectedEndpoint(HttpMethod.DELETE, "/config/del", PERMISSION_CONFIG_DELETE), + // 部门导入 + protectedEndpoint(HttpMethod.POST, "/dept/import", PERMISSION_USER_ADD), + // 资源赋权:把自己授权给自己是另一条提权路径,仅系统管理员可用 + protectedEndpoint(HttpMethod.PUT, "/resource/vpc/switch", PERMISSION_SYSTEM_MANAGEMENT), + protectedEndpoint(HttpMethod.POST, "/resource/permission/.*", PERMISSION_SYSTEM_MANAGEMENT), + protectedEndpoint(HttpMethod.POST, "/resource/type/import", PERMISSION_SYSTEM_MANAGEMENT) + ); + + @Autowired + private UserService userService; + + @Autowired + private UserRoleService userRoleService; + + @Autowired + private RoleService roleService; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws IOException { + if (HttpMethod.GET.matches(request.getMethod()) || HttpMethod.HEAD.matches(request.getMethod())) { + // 只读接口保持原来的登录即可访问的行为,避免影响页面的正常浏览 + return true; + } + + final Integer requiredPermissionId = resolveRequiredPermission(request); + if (requiredPermissionId == null) { + return true; + } + + final Set callerPermissionIds = collectCallerPermissionIds(getOperator(request)); + if (callerPermissionIds.contains(requiredPermissionId)) { + return true; + } + + LOGGER.warn( + "method=preHandle||uri={}||msg=caller has no required permission, requiredPermissionId={}", + request.getRequestURI(), requiredPermissionId); + deny(response); + return false; + } + + /**************************************************** private method ****************************************************/ + + private static ProtectedEndpoint protectedEndpoint(HttpMethod method, String urlSuffix, int permissionId) { + return new ProtectedEndpoint(method, Pattern.compile("^" + urlSuffix + "$"), permissionId); + } + + private Integer resolveRequiredPermission(HttpServletRequest request) { + String uri = request.getRequestURI(); + if (!uri.startsWith(LOGI_API_PREFIX)) { + return null; + } + String suffix = uri.substring(LOGI_API_PREFIX.length()); + for (ProtectedEndpoint endpoint : PROTECTED_ENDPOINTS) { + if (endpoint.method.matches(request.getMethod()) && endpoint.urlSuffixPattern.matcher(suffix).matches()) { + return endpoint.permissionId; + } + } + return null; + } + + /** + * 查询当前登录用户,独立成方法以便单元测试覆写。 + */ + protected String getOperator(HttpServletRequest request) { + return HttpRequestUtil.getOperator(request); + } + + private Set collectCallerPermissionIds(String operator) { + final Set permissionIds = new HashSet<>(); + if (operator == null) { + return permissionIds; + } + final com.didiglobal.logi.security.common.entity.user.User user = userService.getUserByUserName(operator); + if (user == null) { + return permissionIds; + } + final List roleIds = userRoleService.getRoleIdListByUserId(user.getId()); + if (roleIds == null) { + return permissionIds; + } + for (Integer roleId : roleIds) { + if (roleId == null) { + continue; + } + final com.didiglobal.logi.security.common.vo.role.RoleVO role = + roleService.getRoleDetailByRoleId(roleId); + if (role == null) { + continue; + } + collectPermissionIds(role.getPermissionTreeVO(), permissionIds); + } + return permissionIds; + } + + private void collectPermissionIds(PermissionTreeVO node, Set permissionIds) { + if (node == null || node.getId() == null) { + return; + } + permissionIds.add(node.getId()); + if (node.getChildList() != null) { + for (PermissionTreeVO child : node.getChildList()) { + collectPermissionIds(child, permissionIds); + } + } + } + + private void deny(HttpServletResponse response) throws IOException { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType("application/json;charset=UTF-8"); + final String body = "{\"code\":" + HttpServletResponse.SC_FORBIDDEN + + ",\"message\":\"no permission to perform this operation\",\"data\":null,\"success\":false}"; + response.getOutputStream().write(body.getBytes(StandardCharsets.UTF_8)); + } + + private static final class ProtectedEndpoint { + private final HttpMethod method; + private final Pattern urlSuffixPattern; + private final int permissionId; + + private ProtectedEndpoint(HttpMethod method, Pattern urlSuffixPattern, int permissionId) { + this.method = method; + this.urlSuffixPattern = urlSuffixPattern; + this.permissionId = permissionId; + } + } +} diff --git a/km-rest/src/test/java/com/xiaojukeji/know/streaming/km/rest/interceptor/IdentityAuthorizationInterceptorTest.java b/km-rest/src/test/java/com/xiaojukeji/know/streaming/km/rest/interceptor/IdentityAuthorizationInterceptorTest.java new file mode 100644 index 000000000..c82e34a2e --- /dev/null +++ b/km-rest/src/test/java/com/xiaojukeji/know/streaming/km/rest/interceptor/IdentityAuthorizationInterceptorTest.java @@ -0,0 +1,211 @@ +/* + * Copyright contributors to KnowStreaming. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.xiaojukeji.know.streaming.km.rest.interceptor; + +import com.didiglobal.logi.security.common.entity.user.User; +import com.didiglobal.logi.security.common.vo.permission.PermissionTreeVO; +import com.didiglobal.logi.security.common.vo.role.RoleVO; +import com.didiglobal.logi.security.service.RoleService; +import com.didiglobal.logi.security.service.UserRoleService; +import com.didiglobal.logi.security.service.UserService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * 服务端权限校验拦截器单元测试,对应 issue #1263 + * (身份管理接口缺少服务端鉴权导致的自我提权)。 + */ +public class IdentityAuthorizationInterceptorTest { + private static final int PERMISSION_SYSTEM_MANAGEMENT = 1595; + private static final int PERMISSION_USER_ADD = 1629; + private static final int PERMISSION_ROLE_ASSIGN = 1641; + private static final String CALLER = "alice"; + + private UserService userService; + private UserRoleService userRoleService; + private RoleService roleService; + private IdentityAuthorizationInterceptor interceptor; + + @BeforeEach + public void setUp() { + userService = mock(UserService.class); + userRoleService = mock(UserRoleService.class); + roleService = mock(RoleService.class); + interceptor = newInterceptor(CALLER); + ReflectionTestUtils.setField(interceptor, "userService", userService); + ReflectionTestUtils.setField(interceptor, "userRoleService", userRoleService); + ReflectionTestUtils.setField(interceptor, "roleService", roleService); + } + + private IdentityAuthorizationInterceptor newInterceptor(final String operator) { + return new IdentityAuthorizationInterceptor() { + @Override + protected String getOperator(HttpServletRequest request) { + return operator; + } + }; + } + + private void mockCaller(int userId, List roleIds, List permissionIds) { + final User user = mock(User.class); + when(user.getId()).thenReturn(userId); + when(userService.getUserByUserName(CALLER)).thenReturn(user); + when(userRoleService.getRoleIdListByUserId(userId)).thenReturn(roleIds); + final PermissionTreeVO permissionTree = buildPermissionTree(permissionIds); + for (Integer roleId : roleIds) { + final RoleVO role = mock(RoleVO.class); + when(role.getPermissionTreeVO()).thenReturn(permissionTree); + when(roleService.getRoleDetailByRoleId(roleId)).thenReturn(role); + } + } + + private PermissionTreeVO buildPermissionTree(List permissionIds) { + if (permissionIds.isEmpty()) { + return null; + } + final PermissionTreeVO node = mock(PermissionTreeVO.class); + when(node.getId()).thenReturn(permissionIds.get(0)); + when(node.getChildList()).thenReturn(Collections.emptyList()); + return node; + } + + private MockHttpServletRequest request(String method, String uri) { + final MockHttpServletRequest request = new MockHttpServletRequest(method, uri); + request.setRequestURI(uri); + return request; + } + + @Test + public void shouldAllowUserManagementWriteForCallerWithPermission() throws Exception { + mockCaller(7, Arrays.asList(1), Arrays.asList(PERMISSION_USER_ADD)); + + final MockHttpServletRequest request = + request("PUT", "/logi-security/api/v1/user/add"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertTrue(interceptor.preHandle(request, response, new Object())); + Assertions.assertEquals(200, response.getStatus()); + } + + @Test + public void shouldDenyUserManagementWriteForCallerWithoutPermission() throws Exception { + // 仅授予一个与本次操作无关的只读权限点,正是 issue #1263 中的提权场景 + mockCaller(7, Arrays.asList(1), Arrays.asList(3000)); + + final MockHttpServletRequest request = + request("PUT", "/logi-security/api/v1/user/add"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertFalse(interceptor.preHandle(request, response, new Object())); + Assertions.assertEquals(403, response.getStatus()); + Assertions.assertTrue(response.getContentAsString().contains("no permission")); + } + + @Test + public void shouldDenyRoleAssignForCallerWithoutAssignPermission() throws Exception { + mockCaller(7, Arrays.asList(1), Arrays.asList(PERMISSION_USER_ADD)); + + final MockHttpServletRequest request = + request("POST", "/logi-security/api/v1/role/assign"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertFalse(interceptor.preHandle(request, response, new Object())); + Assertions.assertEquals(403, response.getStatus()); + } + + @Test + public void shouldAllowRoleAssignForCallerWithAssignPermission() throws Exception { + mockCaller(7, Arrays.asList(1), Arrays.asList(PERMISSION_ROLE_ASSIGN)); + + final MockHttpServletRequest request = + request("POST", "/logi-security/api/v1/role/assign"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertTrue(interceptor.preHandle(request, response, new Object())); + } + + @Test + public void shouldDenyUnknownUser() throws Exception { + final IdentityAuthorizationInterceptor unknownCallerInterceptor = newInterceptor("ghost"); + ReflectionTestUtils.setField(unknownCallerInterceptor, "userService", userService); + ReflectionTestUtils.setField(unknownCallerInterceptor, "userRoleService", userRoleService); + ReflectionTestUtils.setField(unknownCallerInterceptor, "roleService", roleService); + when(userService.getUserByUserName("ghost")).thenReturn(null); + + final MockHttpServletRequest request = + request("DELETE", "/logi-security/api/v1/role/3"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertFalse(unknownCallerInterceptor.preHandle(request, response, new Object())); + Assertions.assertEquals(403, response.getStatus()); + } + + @Test + public void shouldAllowReadEndpointsRegardlessOfPermissions() throws Exception { + // 只读接口保持登录即可访问 + final MockHttpServletRequest request = + request("GET", "/logi-security/api/v1/role/page"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertTrue(interceptor.preHandle(request, response, new Object())); + } + + @Test + public void shouldAllowNonIdentityEndpoints() throws Exception { + // KM 自身的 /api/v3/** 接口不在本拦截器的职责范围内 + final MockHttpServletRequest request = + request("DELETE", "/api/v3/cluster/1"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertTrue(interceptor.preHandle(request, response, new Object())); + } + + @Test + public void shouldAllowCallerWithSystemManagementPermissionForResourceAssign() throws Exception { + mockCaller(7, Arrays.asList(1), Arrays.asList(PERMISSION_SYSTEM_MANAGEMENT)); + + final MockHttpServletRequest request = + request("POST", "/logi-security/api/v1/resource/permission/mbr/assign"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertTrue(interceptor.preHandle(request, response, new Object())); + } + + @Test + public void shouldDenyResourceAssignForCallerWithoutSystemManagementPermission() throws Exception { + mockCaller(7, Arrays.asList(1), Arrays.asList(PERMISSION_USER_ADD)); + + final MockHttpServletRequest request = + request("POST", "/logi-security/api/v1/resource/permission/mbr/assign"); + final MockHttpServletResponse response = new MockHttpServletResponse(); + + Assertions.assertFalse(interceptor.preHandle(request, response, new Object())); + Assertions.assertEquals(403, response.getStatus()); + } +}