fix(security): 收紧 MCP 数据权限并移除默认凭据

This commit is contained in:
xqzp2026
2026-09-03 16:00:19 +09:30
parent ddd4b3b4ed
commit e501afe292
11 changed files with 470 additions and 86 deletions
@@ -26,8 +26,8 @@ public class CodeGenerator {
private static final String BASE_URL = "jdbc:mysql://192.168.1.181:3306/";
private static final String URL_PARAMS = "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
private static final String USERNAME = "root";
private static final String PASSWORD = System.getenv().getOrDefault("CODEGEN_DB_PASSWORD", "kaixinjiuhao");
private static final String USERNAME = requiredEnv("CODEGEN_DB_USERNAME");
private static final String PASSWORD = requiredEnv("CODEGEN_DB_PASSWORD");
private static final String OUTPUT_DIR = System.getProperty("user.dir") + "/src/main/java";
public static void main(String[] args) {
@@ -39,6 +39,14 @@ public class CodeGenerator {
"agent_api_key", "agent_scope", "tool", "scope_tool", "token_scope", "audit_log", "admin_user");
}
private static String requiredEnv(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) {
throw new IllegalStateException("缺少环境变量 " + name);
}
return value;
}
private static void generate(String schema, String module, String... tables) {
FastAutoGenerator.create(BASE_URL + schema + URL_PARAMS, USERNAME, PASSWORD)
.globalConfig(builder -> builder
@@ -0,0 +1,158 @@
package me.iiv.agent.permission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import me.iiv.agent.entity.m0.Agent;
import me.iiv.agent.entity.m0.Authority;
import me.iiv.agent.entity.m0.Properyt;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.mapper.m0.AgentManageDistrictAuthMapper;
import me.iiv.agent.mapper.m0.AgentMapper;
import me.iiv.agent.mapper.m0.AuthorityMapper;
import me.iiv.agent.mapper.m0.ProperytMapper;
import me.iiv.agent.mapper.m2.WarehouseAgentAuthMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Collection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class PermissionServiceTest {
@Mock
AuthorityMapper authorityMapper;
@Mock
AgentMapper agentMapper;
@Mock
WarehouseAgentAuthMapper warehouseAgentAuthMapper;
@Mock
AgentManageDistrictAuthMapper agentManageDistrictAuthMapper;
@Mock
ProperytMapper properytMapper;
@Mock
StringRedisTemplate redisTemplate;
@Mock
HashOperations<String, Object, Object> hashOperations;
PermissionService permissionService;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), Agent.class);
permissionService = new PermissionService(authorityMapper, agentMapper,
warehouseAgentAuthMapper, agentManageDistrictAuthMapper, properytMapper, redisTemplate);
}
@Test
void agentExactQueryKeepsSelfOrDirectSubordinateBoundary() {
User user = user(1000L, 108L, 1L);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
LambdaQueryWrapper<Agent> wrapper = new LambdaQueryWrapper<>();
permissionService.applyAgentListRowFilter(wrapper, user, 79L);
String sql = wrapper.getSqlSegment();
Collection<Object> values = wrapper.getParamNameValuePairs().values();
assertTrue(sql.contains("id ="));
assertTrue(sql.contains("supervisor_id ="));
assertTrue(values.contains(79L));
assertTrue(values.contains(1L));
}
@Test
void headquartersExactQueryDoesNotAddAgentBoundary() {
User user = user(46L, 1L, 0L);
when(authorityMapper.selectById(1L)).thenReturn(authority(1L, 0));
LambdaQueryWrapper<Agent> wrapper = new LambdaQueryWrapper<>();
permissionService.applyAgentListRowFilter(wrapper, user, 79L);
assertTrue(wrapper.getSqlSegment().contains("id ="));
assertFalse(wrapper.getSqlSegment().contains("supervisor_id ="));
}
@Test
void missingAuthorityIsDeniedInsteadOfTreatedAsHeadquarters() {
when(authorityMapper.selectById(999L)).thenReturn(null);
assertThrows(IllegalStateException.class,
() -> permissionService.isAgentAuthority(999L));
}
@Test
void deletedAuthorityIsDeniedInsteadOfTreatedAsHeadquarters() {
Authority authority = authority(108L, 1);
authority.setSoftDelete(1);
when(authorityMapper.selectById(108L)).thenReturn(authority);
assertThrows(IllegalStateException.class,
() -> permissionService.isAgentAuthority(108L));
}
@Test
void unknownAuthorityModeIsDeniedInsteadOfTreatedAsHeadquarters() {
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 2));
assertThrows(IllegalStateException.class,
() -> permissionService.isAgentAuthority(108L));
}
@Test
void agentUserWithoutAgentIdIsDenied() {
User user = user(1000L, 108L, null);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
assertThrows(IllegalStateException.class,
() -> permissionService.applyAgentListRowFilter(new LambdaQueryWrapper<>(), user, 79L));
}
@Test
void agentUserWithoutAgentIdIsDeniedForPropertyList() {
User user = user(1000L, 108L, null);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
assertThrows(IllegalStateException.class,
() -> permissionService.applyPropertyRowFilter(new LambdaQueryWrapper<Properyt>(), user));
}
@Test
void missingSalesDictionaryIsDeniedInsteadOfDisablingFilter() {
User user = user(1000L, 108L, 1L);
user.setDeptId(5L);
user.setPostId(7L);
when(redisTemplate.opsForHash()).thenReturn(hashOperations);
when(hashOperations.get("Dictionary", "authDeptId")).thenReturn(null);
when(hashOperations.get("Dictionary", "authDeptPostId")).thenReturn(null);
assertThrows(IllegalStateException.class,
() -> permissionService.isSalesNonLeader(user));
}
private static Authority authority(Long id, int isAgent) {
Authority authority = new Authority();
authority.setId(id);
authority.setIsagent(isAgent);
authority.setSoftDelete(0);
return authority;
}
private static User user(Long id, Long authorityId, Long agentId) {
User user = new User();
user.setId(id);
user.setAuthorityId(authorityId);
user.setAgentId(agentId);
return user;
}
}
@@ -0,0 +1,66 @@
package me.iiv.agent.security;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.svc.AgentApiKey;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AkAuthFilterTest {
@Mock
AuthService authService;
@AfterEach
void clearContext() {
AuthContextHolder.clear();
}
@Test
void missingBearerTokenReturnsUnauthorized() throws Exception {
AkAuthFilter filter = new AkAuthFilter(authService);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/mcp");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertEquals(401, response.getStatus());
assertNull(chain.getRequest());
verify(authService, never()).resolve(org.mockito.ArgumentMatchers.anyString());
}
@Test
void validBearerTokenSetsAndClearsContext() throws Exception {
AgentApiKey token = new AgentApiKey();
token.setId(7L);
User user = new User();
user.setId(1000L);
AuthContext context = new AuthContext(token, user);
when(authService.resolve("valid-ak")).thenReturn(context);
AkAuthFilter filter = new AkAuthFilter(authService);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/mcp");
request.addHeader("Authorization", "Bearer valid-ak");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertSame(request, chain.getRequest());
assertNull(AuthContextHolder.get());
}
}
@@ -0,0 +1,40 @@
package me.iiv.agent.security;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertFalse;
class ConfigurationSecurityTest {
private static final Pattern PASSWORD_WITH_DEFAULT =
Pattern.compile("password:\\s*\\$\\{[^}:]+:[^}]+}");
private static final Pattern COMMITTED_AK =
Pattern.compile("xqak_[0-9a-f]{20,}");
@Test
void applicationDoesNotActivateDevByDefault() throws IOException {
String application = Files.readString(Path.of("src/main/resources/application.yml"));
assertFalse(application.contains("active: dev"));
}
@Test
void devConfigurationHasNoRootUserOrPasswordDefaults() throws IOException {
String application = Files.readString(Path.of("src/main/resources/application-dev.yml"));
assertFalse(application.contains("username: root"));
assertFalse(PASSWORD_WITH_DEFAULT.matcher(application).find());
}
@Test
void devSeedContainsNoReusablePlaintextAk() throws IOException {
String seed = Files.readString(Path.of("sql/seed-dev.sql"));
assertFalse(COMMITTED_AK.matcher(seed).find());
}
}
@@ -0,0 +1,100 @@
package me.iiv.agent.security;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.entity.svc.ScopeTool;
import me.iiv.agent.entity.svc.TokenScope;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.mapper.svc.ScopeToolMapper;
import me.iiv.agent.mapper.svc.TokenScopeMapper;
import me.iiv.agent.mapper.svc.ToolMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@SuppressWarnings("unchecked")
class ToolGuardTest {
@Mock
TokenScopeMapper tokenScopeMapper;
@Mock
ScopeToolMapper scopeToolMapper;
@Mock
ToolMapper toolMapper;
@Mock
AgentScopeMapper agentScopeMapper;
@Test
void tokenWithoutScopeIsDenied() {
when(tokenScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
ToolGuard guard = guard();
assertFalse(guard.isAllowed(7L, "agent.list.query"));
verify(scopeToolMapper, never()).selectList(any());
}
@Test
void disabledScopeIsDenied() {
when(tokenScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(tokenScope(3L)));
when(agentScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
ToolGuard guard = guard();
assertFalse(guard.isAllowed(7L, "agent.list.query"));
verify(scopeToolMapper, never()).selectList(any());
}
@Test
void enabledScopeAndToolAreAllowed() {
when(tokenScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(tokenScope(3L)));
when(agentScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(scope(3L)));
when(scopeToolMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(scopeTool(9L)));
when(toolMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(1L);
ToolGuard guard = guard();
assertTrue(guard.isAllowed(7L, "agent.list.query"));
}
@Test
void disabledToolIsDenied() {
when(tokenScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(tokenScope(3L)));
when(agentScopeMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(scope(3L)));
when(scopeToolMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(scopeTool(9L)));
when(toolMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
ToolGuard guard = guard();
assertFalse(guard.isAllowed(7L, "agent.list.query"));
}
private ToolGuard guard() {
return new ToolGuard(tokenScopeMapper, scopeToolMapper, toolMapper, agentScopeMapper);
}
private static TokenScope tokenScope(Long scopeId) {
TokenScope tokenScope = new TokenScope();
tokenScope.setScopeId(scopeId);
return tokenScope;
}
private static AgentScope scope(Long id) {
AgentScope scope = new AgentScope();
scope.setId(id);
return scope;
}
private static ScopeTool scopeTool(Long toolId) {
ScopeTool scopeTool = new ScopeTool();
scopeTool.setToolId(toolId);
return scopeTool;
}
}