feat(open): 服务身份免登录分页查询(REQ-20260921-0004)

- agent_scope 新增 service_enabled 标记(Flyway V7 + 回滚),服务 Token 签发
  由 sync 硬编码改为标记驱动,管理后台作用域 CRUD/前端支持该标记
- PermissionService 全部行过滤入口加 tenant_service 分支:服务主体总部视角
  全量可见不做行过滤,用户身份行为不变;非服务主体的 null user 显式拒绝
- warehouse.todo.list.query 按当前登录人统计,服务身份返回 PERMISSION_DENIED
- RateLimitService 新增 SERVICE-QUERY 独立限流档(默认 300/分钟)
- seed-dev.sql 新增 ops-query 作用域并绑定全部在线查询工具
- 文档:tools-reference §0.3、README Open API 服务 Token 段
This commit is contained in:
my_local_kimi_dev2
2026-09-21 15:58:08 +08:00
parent 47886fed3e
commit 3f46b64218
20 changed files with 377 additions and 38 deletions
@@ -214,7 +214,8 @@ public class AdminConsoleController {
.eq(ScopeTool::getSoftDelete, 0)).stream()
.collect(Collectors.groupingBy(ScopeTool::getScopeId, Collectors.counting()));
return scopes.stream().map(scope -> new ScopeView(scope.getId(), scope.getName(), scope.getCode(),
scope.getMemo(), scope.getStatus(), scope.getModifyTime(), counts.getOrDefault(scope.getId(), 0L))).toList();
scope.getMemo(), scope.getStatus(), scope.getServiceEnabled(), scope.getModifyTime(),
counts.getOrDefault(scope.getId(), 0L))).toList();
}
@PostMapping("/scopes")
@@ -228,7 +229,7 @@ public class AdminConsoleController {
scope.setSoftDelete((byte) 0);
scopeMapper.insert(scope);
return new ScopeView(scope.getId(), scope.getName(), scope.getCode(), scope.getMemo(),
scope.getStatus(), scope.getModifyTime(), 0);
scope.getStatus(), scope.getServiceEnabled(), scope.getModifyTime(), 0);
}
@PutMapping("/scopes/{id}")
@@ -372,6 +373,7 @@ public class AdminConsoleController {
scope.setName(body.name().trim());
scope.setCode(body.code().trim());
scope.setMemo(body.memo() == null ? null : body.memo().trim());
scope.setServiceEnabled(body.serviceEnabled() != null && body.serviceEnabled() ? (byte) 1 : (byte) 0);
scope.setModifyId(adminId);
}
@@ -407,8 +409,8 @@ public class AdminConsoleController {
public record ToolView(Long id, String name, String category, String description, String kind,
Byte status, Date modifyTime, List<String> scopeNames) {}
public record ToolPageView(long total, int page, int pageSize, List<ToolView> records) {}
public record ScopeRequest(String name, String code, String memo) {}
public record ScopeView(Long id, String name, String code, String memo, Byte status,
public record ScopeRequest(String name, String code, String memo, Boolean serviceEnabled) {}
public record ScopeView(Long id, String name, String code, String memo, Byte status, Byte serviceEnabled,
Date modifyTime, long toolCount) {}
public record ToolIdsRequest(List<Long> toolIds) {}
public record AuditView(Long id, Date createTime, Long userId, String userName, String tokenPrefix,
@@ -52,6 +52,11 @@ public class AgentScope implements Serializable {
*/
private Byte status;
/**
* 1=允许服务主体(tenant_service)Token 绑定签发(REQ-20260921-0004)
*/
private Byte serviceEnabled;
/**
* 创建人
*/
@@ -82,7 +82,7 @@ public class GuardedToolCallback implements ToolCallback {
throw denied;
}
try {
rateLimitService.check(ctx.getTokenId(), toolName);
rateLimitService.check(ctx, toolName);
rejectForbiddenSyncParams(toolName, toolInput);
String result = toolContext == null ? delegate.call(toolInput) : delegate.call(toolInput, toolContext);
auditService.record(ctx, toolName, toolInput, "success", null, System.currentTimeMillis() - start);
@@ -1,5 +1,7 @@
package me.iiv.agent.mcp;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.security.AuthContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
@@ -12,7 +14,8 @@ import java.time.Instant;
/**
* 工具调用限流(REQ-20260911-0013 资源隔离):按 Token 分档计数——
* 后台数据工具走 SYNC 档位,其余走 QUERY 档位,互不占配额。
* 后台数据工具走 SYNC 档位,tenant_service 服务主体的在线查询走 SERVICE-QUERY 档位
* (REQ-20260921-0004,与用户查询隔离),其余走 QUERY 档位,互不占配额。
* Redis 固定窗口(分钟),超额抛 RATE_LIMITED;Redis 不可用时放行并告警
* (限流是保护措施,不应成为可用性单点)。
* 配额 0 或负数 = 关闭该档位。
@@ -25,25 +28,31 @@ public class RateLimitService {
private final StringRedisTemplate redisTemplate;
private final int queryPerMinute;
private final int syncPerMinute;
private final int serviceQueryPerMinute;
public RateLimitService(StringRedisTemplate redisTemplate,
@Value("${app.rate-limit.query-per-minute:600}") int queryPerMinute,
@Value("${app.rate-limit.sync-per-minute:120}") int syncPerMinute) {
@Value("${app.rate-limit.sync-per-minute:120}") int syncPerMinute,
@Value("${app.rate-limit.service-query-per-minute:300}") int serviceQueryPerMinute) {
this.redisTemplate = redisTemplate;
this.queryPerMinute = queryPerMinute;
this.syncPerMinute = syncPerMinute;
this.serviceQueryPerMinute = serviceQueryPerMinute;
}
public void check(Long tokenId, String toolName) {
if (tokenId == null) {
public void check(AuthContext ctx, String toolName) {
if (ctx == null || ctx.getTokenId() == null) {
return;
}
Long tokenId = ctx.getTokenId();
boolean sync = IntegrationContextService.isSyncDataTool(toolName);
int limit = sync ? syncPerMinute : queryPerMinute;
boolean service = !sync && ctx.getToken() != null
&& AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(ctx.getToken().getPrincipalType());
String tier = sync ? "sync" : service ? "service-query" : "query";
int limit = sync ? syncPerMinute : service ? serviceQueryPerMinute : queryPerMinute;
if (limit <= 0) {
return;
}
String tier = sync ? "sync" : "query";
String key = "xq:rl:" + tier + ":" + tokenId + ":" + Instant.now().getEpochSecond() / 60;
try {
Long count = redisTemplate.opsForValue().increment(key);
@@ -8,6 +8,8 @@ import me.iiv.agent.entity.m2.WarehouseOutProcess;
import me.iiv.agent.mapper.m2.WarehouseAllocationProcessMapper;
import me.iiv.agent.mapper.m2.WarehouseInProcessMapper;
import me.iiv.agent.mapper.m2.WarehouseOutProcessMapper;
import me.iiv.agent.mcp.McpErrorCode;
import me.iiv.agent.mcp.ToolCallException;
import me.iiv.agent.mcp.ToolObject;
import me.iiv.agent.mcp.XqTool;
import me.iiv.agent.security.AuthContextHolder;
@@ -84,7 +86,8 @@ public class WarehouseTodoTools implements ToolObject {
+ "todoOnly 默认 true(只返回 schedule_state=1 真待办),false 返回当前用户参与过的全部单据。"
+ "orderState 按单据状态过滤:出库/入库单 0待审核 1被驳回 2待出库/待入库 3已完成 4已撤销 5作废;"
+ "调拨类 0待审核 1被驳回 2待出库 3待入库 4已完成 5已撤销 6作废。"
+ "分页 page 默认1,rows 默认20、上限100,超出截断为 100 并在 notice 提示。")
+ "分页 page 默认1,rows 默认20、上限100,超出截断为 100 并在 notice 提示。"
+ "服务身份(tenant_service)无当前登录人语义,调用返回 PERMISSION_DENIED。")
public Map<String, Object> warehouseTodoListQuery(
@ToolParam(required = false, description = "单据类型:out/in/allocation/all,默认 all。allocation 涵盖调拨/采购/划转") String docType,
@ToolParam(required = false, description = "true=只返回 schedule_state=1 真待办(默认);false=当前用户参与过的全部单据") Boolean todoOnly,
@@ -102,6 +105,10 @@ public class WarehouseTodoTools implements ToolObject {
int pageSize = rows == null || rows < 1 ? DEFAULT_ROWS : Math.min(rows, MAX_ROWS);
User user = AuthContextHolder.get().getUser();
if (user == null) {
throw new ToolCallException(McpErrorCode.PERMISSION_DENIED,
"该工具按当前登录人统计待办,仅支持用户身份 Token 调用");
}
Long userId = user.getId();
List<TodoStub> stubs = new ArrayList<>();
@@ -24,6 +24,7 @@ import java.util.Date;
* 历史数据无密文的 Token 自动轮换(禁用旧把、签发新把);
* 不存在则自动创建永久 Token。两条路径均返回明文。
* service 类型(REQ-20260911-0014):要求服务密钥已在后台或配置中绑定该作用域,
* 且作用域标记为允许服务主体(agent_scope.service_enabled=1,REQ-20260921-0004 取代 sync 硬编码),
* 旧版不限域密钥(app.open.api-key)不可签发服务 Token。
*/
@Service
@@ -32,7 +33,7 @@ public class OpenTokenService {
/** 系统签发(Open API 自动创建)的 createId 约定值 */
static final long SYSTEM_CREATOR_ID = 0L;
static final String AUDIT_TOOL = "open.token.ensure";
/** SYNC 作用域编码:服务 Token 只能绑定该作用域,用户 Token 不能绑定(REQ-20260911-0014) */
/** SYNC 作用域编码:用户 Token 不能绑定(服务侧放行由 service_enabled 标记驱动) */
static final String SYNC_SCOPE_CODE = "sync";
private final UserMapper userMapper;
@@ -70,8 +71,8 @@ public class OpenTokenService {
bad(HttpStatus.BAD_REQUEST, "作用域不存在或已停用");
}
checkScopeBinding(client, scope, service);
if (service && !SYNC_SCOPE_CODE.equals(scope.getCode())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "服务 Token 只能绑定 SYNC 作用域");
if (service && !Byte.valueOf((byte) 1).equals(scope.getServiceEnabled())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "服务 Token 只能绑定允许服务主体的作用域");
}
if (!service && SYNC_SCOPE_CODE.equals(scope.getCode())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "SYNC 作用域仅允许服务 Token");
@@ -19,11 +19,14 @@ import me.iiv.agent.entity.m2.WithdrawOrder;
import me.iiv.agent.entity.m2.WarehouseIn;
import me.iiv.agent.entity.m2.WarehouseOut;
import me.iiv.agent.entity.m2.WarehouseStockManage;
import me.iiv.agent.entity.svc.AgentApiKey;
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 me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.AuthContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
@@ -40,6 +43,8 @@ import java.util.stream.Collectors;
* 行级数据权限引擎:移植老系统 WrapperUtils.getByIsAgent 系列语义
* (xiaoqu-franchisee utils/WrapperUtils.java :652-731 及 :382-427)。
* 输出中性的 id 集合,调用方自行拼 wrapper.in("agent_id", ids);不做跨库 JOIN。
* REQ-20260921-0004:tenant_service 服务主体(user==null)按总部视角全量可见,
* 各公开入口首行统一走 servicePrincipalNoFilter 分支;用户身份行为不变。
*/
@Component
public class PermissionService {
@@ -70,6 +75,23 @@ public class PermissionService {
this.redisTemplate = redisTemplate;
}
/**
* tenant_service 服务主体判定(REQ-20260921-0004):服务 Token 无用户上下文(user==null),
* 按总部视角全量可见、不做行过滤,返回 true。user 非 null 返回 false 走既有用户语义。
* user==null 且非服务主体说明鉴权上下文丢失,拒绝访问(不放行)。
*/
private boolean servicePrincipalNoFilter(User user) {
if (user != null) {
return false;
}
AuthContext ctx = AuthContextHolder.get();
if (ctx != null && ctx.getToken() != null
&& AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(ctx.getToken().getPrincipalType())) {
return true;
}
throw new IllegalStateException("缺少用户身份上下文,拒绝访问业务数据");
}
/** 权限组 isagent=1 → 代理商视角;未知或已删除的权限组拒绝访问。 */
public boolean isAgentAuthority(Long authorityId) {
if (authorityId == null) {
@@ -93,10 +115,13 @@ public class PermissionService {
* 未传 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 (servicePrincipalNoFilter(user)) {
return;
}
boolean agentAuthority = isAgentAuthority(user.getAuthorityId());
if (!agentAuthority) {
return;
}
@@ -112,11 +137,14 @@ public class PermissionService {
}
/**
* 可见 agent id 集合。返回 null 表示不过滤(isagent != 1,总部/管理员看全部)。
* 可见 agent id 集合。返回 null 表示不过滤(isagent != 1 总部/管理员,或 tenant_service 服务主体,看全部)。
* isagent=1 时:自己 agentId + 直属下级代理(agent.supervisor_id=自己,只取一层)
* + m2 warehouse_agent_auth 中该用户被授权的 manager_agent_id(代管扩展)。
*/
public List<Long> visibleAgentIds(User user) {
if (servicePrincipalNoFilter(user)) {
return null;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return null;
}
@@ -205,6 +233,9 @@ public class PermissionService {
* 列表和详情必须复用本方法,避免详情绕过行权限。
*/
public void applyDeliveryOrderRowFilter(LambdaQueryWrapper<DeliveryOrder> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -255,6 +286,9 @@ public class PermissionService {
* 列表和详情复用本方法,防止详情接口绕过行权限。
*/
public void applyPickupOrderRowFilter(LambdaQueryWrapper<PickupOrder> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -306,6 +340,9 @@ public class PermissionService {
* 销售非负责人按自己创建和代管代理物业过滤。流程参与者及 type=2 的移机/协同人员始终可见。
*/
public void applyRelocationOrderRowFilter(LambdaQueryWrapper<RelocationOrder> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -366,6 +403,9 @@ public class PermissionService {
* 空集塞 0。列表和详情必须复用本方法,老系统 lookDetails 无权限校验,MCP 侧必须补齐。
*/
public void applyWithdrawOrderRowFilter(LambdaQueryWrapper<WithdrawOrder> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -419,6 +459,9 @@ public class PermissionService {
* 与通用物业权限不同,本规则不包含直属下级代理。
*/
public void applyInstallOrderRowFilter(LambdaQueryWrapper<InstallOrder> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -481,6 +524,9 @@ public class PermissionService {
* 代理可看本公司及 warehouse_agent_auth 授权代管公司作为管理公司或所属公司的库存。
*/
public void applyWarehouseStockRowFilter(LambdaQueryWrapper<WarehouseStockManage> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -578,6 +624,9 @@ public class PermissionService {
* 销售非负责人规则 2026-09-03 用户决策:1:1 复刻老代码(不再按 §3.3 收窄为 AND create_id=自己)。
*/
public void applyPropertyRowFilter(LambdaQueryWrapper<Properyt> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -636,6 +685,9 @@ public class PermissionService {
* </ol>
*/
public void applyOrderRowFilter(LambdaQueryWrapper<MallGoodsOrder> wrapper, User user) {
if (servicePrincipalNoFilter(user)) {
return;
}
if (!isAgentAuthority(user.getAuthorityId())) {
return;
}
@@ -697,6 +749,10 @@ public class PermissionService {
*/
private RowScope resolveRowScope(User user) {
RowScope scope = new RowScope();
if (servicePrincipalNoFilter(user)) {
scope.headquarters = true;
return scope;
}
if (!isAgentAuthority(user.getAuthorityId())) {
scope.headquarters = true;
return scope;