fix(security): 收紧 MCP 数据权限并移除默认凭据
This commit is contained in:
@@ -51,18 +51,18 @@ public class AgentTools implements ToolObject {
|
||||
/**
|
||||
* 查询代理商列表。行权限照搬老系统 AgentController.listByPage:
|
||||
* 权限组 isagent=1 时只查直属下级(supervisor_id = 用户 agentId);isagent=0 不过滤。
|
||||
* 入参传 id 时精确查询(可查到自身,此时不加 supervisor 限制)。
|
||||
* 入参传 id 时精确查询;代理商只能查询自己或直属下级。
|
||||
* supervisorName 批量 IN 查询富化,无 N+1。
|
||||
*/
|
||||
@XqTool(category = "customer", kind = "read")
|
||||
@Tool(name = "agent.list.query", description = "查询代理商列表(分页)。"
|
||||
+ "行级权限:代理商身份的用户(权限组 isagent=1)只能查到自己名下的直属下级代理;总部身份(isagent=0)可看全部。"
|
||||
+ "传 id 时为精确查询、可查到自身,其余过滤条件失效。"
|
||||
+ "传 id 时为精确查询;代理商只能查询自己或直属下级,总部可查询任意合法 id,其余过滤条件失效。"
|
||||
+ "level 含义:0=总部 1=一级 2=二级;channelNo 含义:Z=总部 F=分公司 D=代理。"
|
||||
+ "分页:page 从 1 开始,rows 默认 20、上限 100,超出自动截断为 100 并在返回的 notice 字段提示。"
|
||||
+ "返回 total(符合条件的总数)、records(本页记录)。")
|
||||
public Map<String, Object> agentListQuery(
|
||||
@ToolParam(required = false, description = "代理商 id,精确查询(可查到自身);传入后忽略其他过滤条件") Long id,
|
||||
@ToolParam(required = false, description = "代理商 id,精确查询;代理商仅限自己或直属下级;传入后忽略其他过滤条件") Long id,
|
||||
@ToolParam(required = false, description = "代理商名称,模糊匹配") String name,
|
||||
@ToolParam(required = false, description = "级别:0=总部 1=一级 2=二级") Integer level,
|
||||
@ToolParam(required = false, description = "渠道编号:Z=总部 F=分公司 D=代理") String channelNo,
|
||||
@@ -78,9 +78,7 @@ public class AgentTools implements ToolObject {
|
||||
|
||||
LambdaQueryWrapper<Agent> wrapper = new LambdaQueryWrapper<Agent>()
|
||||
.eq(Agent::getSoftDelete, 0);
|
||||
if (id != null) {
|
||||
wrapper.eq(Agent::getId, id);
|
||||
} else {
|
||||
if (id == null) {
|
||||
if (StringUtils.hasText(name)) {
|
||||
wrapper.like(Agent::getName, name);
|
||||
}
|
||||
@@ -99,10 +97,8 @@ public class AgentTools implements ToolObject {
|
||||
if (StringUtils.hasText(serialnumber)) {
|
||||
wrapper.eq(Agent::getSerialnumber, serialnumber);
|
||||
}
|
||||
if (permissionService.isAgentAuthority(user.getAuthorityId())) {
|
||||
wrapper.eq(Agent::getSupervisorId, user.getAgentId());
|
||||
}
|
||||
}
|
||||
permissionService.applyAgentListRowFilter(wrapper, user, id);
|
||||
|
||||
Long total = agentMapper.selectCount(wrapper);
|
||||
wrapper.select(Agent::getId, Agent::getName, Agent::getLevel, Agent::getChannelNo,
|
||||
|
||||
@@ -57,13 +57,45 @@ public class PermissionService {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/** 权限组 isagent=1 → 代理商视角(对应 AuthorityServiceImpl.checkAuthorityIsagent) */
|
||||
/** 权限组 isagent=1 → 代理商视角;未知或已删除的权限组拒绝访问。 */
|
||||
public boolean isAgentAuthority(Long authorityId) {
|
||||
if (authorityId == null) {
|
||||
return false;
|
||||
throw new IllegalStateException("用户未配置权限组,拒绝访问业务数据");
|
||||
}
|
||||
Authority authority = authorityMapper.selectById(authorityId);
|
||||
return authority != null && authority.getIsagent() != null && authority.getIsagent() == 1;
|
||||
if (authority == null || !Integer.valueOf(0).equals(authority.getSoftDelete())) {
|
||||
throw new IllegalStateException("用户权限组不存在或已删除,拒绝访问业务数据");
|
||||
}
|
||||
if (Integer.valueOf(1).equals(authority.getIsagent())) {
|
||||
return true;
|
||||
}
|
||||
if (Integer.valueOf(0).equals(authority.getIsagent())) {
|
||||
return false;
|
||||
}
|
||||
throw new IllegalStateException("用户权限组缺少有效的行权限配置,拒绝访问业务数据");
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理商列表权限:总部可按任意 id 查询;代理商只能查询自己或直属下级。
|
||||
* 未传 id 时保持老页面语义,只列直属下级。
|
||||
*/
|
||||
public void applyAgentListRowFilter(LambdaQueryWrapper<Agent> wrapper, User user, Long id) {
|
||||
boolean agentAuthority = isAgentAuthority(user.getAuthorityId());
|
||||
if (id != null) {
|
||||
wrapper.eq(Agent::getId, id);
|
||||
}
|
||||
if (!agentAuthority) {
|
||||
return;
|
||||
}
|
||||
if (user.getAgentId() == null) {
|
||||
throw new IllegalStateException("代理商用户未关联代理商,拒绝访问业务数据");
|
||||
}
|
||||
if (id == null) {
|
||||
wrapper.eq(Agent::getSupervisorId, user.getAgentId());
|
||||
return;
|
||||
}
|
||||
wrapper.and(w -> w.eq(Agent::getId, user.getAgentId())
|
||||
.or().eq(Agent::getSupervisorId, user.getAgentId()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,6 +107,9 @@ public class PermissionService {
|
||||
if (!isAgentAuthority(user.getAuthorityId())) {
|
||||
return null;
|
||||
}
|
||||
if (user.getAgentId() == null) {
|
||||
throw new IllegalStateException("代理商用户未关联代理商,拒绝访问业务数据");
|
||||
}
|
||||
Set<Long> ids = new LinkedHashSet<>();
|
||||
ids.addAll(subordinateAndSelfIds(user));
|
||||
ids.addAll(managedAuths(user.getId()).stream()
|
||||
@@ -105,7 +140,7 @@ public class PermissionService {
|
||||
/**
|
||||
* 销售部门非负责人判定(老系统 getByIsAgent 内 saleFlag 逻辑,:703-710):
|
||||
* Redis db5 Dictionary hash 的 authDeptId 命中 ",deptId," 且 authDeptPostId 不命中 "postId,"。
|
||||
* 字典缺失时按"不限制"处理并告警(与老系统 NPE 直接报错的行为不同,属于有意收敛)。
|
||||
* 字典缺失时拒绝访问,避免权限配置异常导致数据范围放宽。
|
||||
*/
|
||||
public boolean isSalesNonLeader(User user) {
|
||||
if (user.getDeptId() == null || user.getPostId() == null) {
|
||||
@@ -114,8 +149,8 @@ public class PermissionService {
|
||||
Object authDeptId = redisTemplate.opsForHash().get(DICTIONARY_KEY, DICT_FIELD_AUTH_DEPT_ID);
|
||||
Object authDeptPostId = redisTemplate.opsForHash().get(DICTIONARY_KEY, DICT_FIELD_AUTH_DEPT_POST_ID);
|
||||
if (authDeptId == null || authDeptPostId == null) {
|
||||
log.warn("Redis Dictionary 缺少 {}/{} 字段,销售部门限制未生效", DICT_FIELD_AUTH_DEPT_ID, DICT_FIELD_AUTH_DEPT_POST_ID);
|
||||
return false;
|
||||
log.error("Redis Dictionary 缺少 {}/{} 字段,拒绝访问业务数据", DICT_FIELD_AUTH_DEPT_ID, DICT_FIELD_AUTH_DEPT_POST_ID);
|
||||
throw new IllegalStateException("销售数据权限配置不可用,拒绝访问业务数据");
|
||||
}
|
||||
return authDeptId.toString().contains("," + user.getDeptId() + ",")
|
||||
&& !authDeptPostId.toString().contains(user.getPostId() + ",");
|
||||
@@ -167,6 +202,9 @@ public class PermissionService {
|
||||
if (!isAgentAuthority(user.getAuthorityId())) {
|
||||
return;
|
||||
}
|
||||
if (user.getAgentId() == null) {
|
||||
throw new IllegalStateException("代理商用户未关联代理商,拒绝访问业务数据");
|
||||
}
|
||||
// ids 组装:下级 + 自己 + 代管(老 :682-702)
|
||||
List<Long> ids = new ArrayList<>(subordinateAndSelfIds(user));
|
||||
List<WarehouseAgentAuth> agentlist = managedAuths(user.getId());
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
# dev 环境:内网 192.168.1.181(沿用 xiaoqu-franchisee pom.xml dev profile)
|
||||
# 密码走环境变量占位符,默认值仅供本地 dev 使用
|
||||
# 账号和密码必须由环境变量提供;m0/m1/m2 应使用数据库只读账号
|
||||
app:
|
||||
datasource:
|
||||
m0: # 权限库 xiaoqu_comples_d(user/agent/authority/propery/agent_manage_district_auth)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
jdbc-url: jdbc:mysql://192.168.1.181:3306/xiaoqu_comples_d?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
|
||||
username: root
|
||||
password: ${M0_DB_PASSWORD:kaixinjiuhao}
|
||||
username: ${M0_DB_USERNAME}
|
||||
password: ${M0_DB_PASSWORD}
|
||||
m1: # 商城库 xiaoqu_mall_d(按需启用)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
jdbc-url: jdbc:mysql://192.168.1.181:3306/xiaoqu_mall_d?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
|
||||
username: root
|
||||
password: ${M1_DB_PASSWORD:kaixinjiuhao}
|
||||
username: ${M1_DB_USERNAME}
|
||||
password: ${M1_DB_PASSWORD}
|
||||
m2: # 业务库 xiaoqu_franchisee_d(warehouse_agent_auth 等)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
jdbc-url: jdbc:mysql://192.168.1.181:3306/xiaoqu_franchisee_d?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
|
||||
username: root
|
||||
password: ${M2_DB_PASSWORD:kaixinjiuhao}
|
||||
username: ${M2_DB_USERNAME}
|
||||
password: ${M2_DB_PASSWORD}
|
||||
svc: # 自有库 xiaoqu_agent_svc_d(token/scope/tool/audit,读写)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
jdbc-url: jdbc:mysql://192.168.1.181:3306/xiaoqu_agent_svc_d?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
|
||||
username: root
|
||||
password: ${SVC_DB_PASSWORD:kaixinjiuhao}
|
||||
username: ${SVC_DB_USERNAME}
|
||||
password: ${SVC_DB_PASSWORD}
|
||||
|
||||
spring:
|
||||
data:
|
||||
redis:
|
||||
host: 192.168.1.181
|
||||
port: 6379
|
||||
password: ${REDIS_PASSWORD:kaixinjiuhao}
|
||||
password: ${REDIS_PASSWORD}
|
||||
database: 5
|
||||
timeout: 5s
|
||||
|
||||
@@ -4,8 +4,6 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: xiaoqu-agent-service
|
||||
profiles:
|
||||
active: dev
|
||||
ai:
|
||||
mcp:
|
||||
server:
|
||||
|
||||
@@ -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
|
||||
|
||||
+158
@@ -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());
|
||||
}
|
||||
}
|
||||
+40
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user