feat: 完善 Skill 管理与发布治理
- 实现标准资源存储、能力绑定及双格式导入导出 - 接入分类、可见范围、审批发布与资源权限校验 - 补充并发、租户隔离、安全边界和迁移契约测试
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package tech.easyflow.ai.permission;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
/**
|
||||
* MCP 查询与使用权限检查器。
|
||||
*
|
||||
* <p>MCP 当前没有独立的资源级 {@code USE} 权限,平台沿用 MCP 管理模块已有的
|
||||
* {@code /api/v1/mcp/query} 权限作为查看、选择和使用 MCP 的授权边界。</p>
|
||||
*/
|
||||
@Component
|
||||
public class McpAccessPermissionChecker {
|
||||
|
||||
/** MCP 模块现有查询权限码。 */
|
||||
public static final String MCP_QUERY_PERMISSION = "/api/v1/mcp/query";
|
||||
|
||||
/**
|
||||
* 判断当前登录用户是否可以查询和使用 MCP。
|
||||
*
|
||||
* @return 已登录且拥有 MCP 查询权限时返回 {@code true}
|
||||
*/
|
||||
public boolean canUseMcp() {
|
||||
return StpUtil.isLogin() && StpUtil.hasPermission(MCP_QUERY_PERMISSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验当前登录用户是否可以查询和使用 MCP。
|
||||
*
|
||||
* @throws BusinessException 未登录或缺少 MCP 查询权限时抛出
|
||||
*/
|
||||
public void assertCanUseMcp() {
|
||||
if (!StpUtil.isLogin()) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
if (!StpUtil.hasPermission(MCP_QUERY_PERMISSION)) {
|
||||
throw new BusinessException(403, 403, "无权限查询或使用 MCP");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,42 @@ public abstract class AbstractAiResourceLifecycleHandler<T> implements ApprovalS
|
||||
protected void validateDelete(T resource, PublishStatus currentStatus) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建删除审批使用的治理快照。
|
||||
*
|
||||
* <p>默认沿用资源快照;包含敏感配置或需要发布级校验的资源可覆盖此方法,
|
||||
* 返回不依赖发布可用性的最小治理信息。</p>
|
||||
*
|
||||
* @param resource 资源
|
||||
* @return 删除审批治理快照
|
||||
*/
|
||||
protected Map<String, Object> buildDeleteResourceSnapshot(T resource) {
|
||||
return buildResourceSnapshot(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean canAccessApprovalDetail(Object identifier) {
|
||||
if (identifier == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
T resource = requireResource(new BigInteger(String.valueOf(identifier)));
|
||||
assertManagePermission(resource);
|
||||
return true;
|
||||
} catch (NumberFormatException exception) {
|
||||
return false;
|
||||
} catch (BusinessException exception) {
|
||||
// 资源不存在或无权管理都按不可见处理;服务端异常仍向上抛出,避免静默掩盖故障。
|
||||
if (exception.getHttpStatus() >= 400 && exception.getHttpStatus() < 500) {
|
||||
return false;
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下线成功后的额外副作用。
|
||||
*
|
||||
@@ -286,7 +322,7 @@ public abstract class AbstractAiResourceLifecycleHandler<T> implements ApprovalS
|
||||
throw new BusinessException("当前" + resourceLabel() + "存在进行中的审批,请先处理完成");
|
||||
}
|
||||
validateDelete(resource, currentStatus);
|
||||
return buildResourceSnapshot(resource);
|
||||
return buildDeleteResourceSnapshot(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package tech.easyflow.ai.permission;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import org.junit.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
|
||||
/**
|
||||
* {@link McpAccessPermissionChecker} 的现有 MCP RBAC 语义回归测试。
|
||||
*/
|
||||
public class McpAccessPermissionCheckerTest {
|
||||
|
||||
/**
|
||||
* 未登录调用方必须收到 401。
|
||||
*/
|
||||
@Test
|
||||
public void unauthenticatedCallerIsRejected() {
|
||||
try (MockedStatic<StpUtil> stpUtil = mockStatic(StpUtil.class)) {
|
||||
stpUtil.when(StpUtil::isLogin).thenReturn(false);
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> new McpAccessPermissionChecker().assertCanUseMcp());
|
||||
|
||||
assertEquals(401, exception.getHttpStatus());
|
||||
assertFalse(new McpAccessPermissionChecker().canUseMcp());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 已登录但缺少 MCP 查询权限的调用方必须收到 403。
|
||||
*/
|
||||
@Test
|
||||
public void callerWithoutMcpQueryPermissionIsRejected() {
|
||||
try (MockedStatic<StpUtil> stpUtil = mockStatic(StpUtil.class)) {
|
||||
stpUtil.when(StpUtil::isLogin).thenReturn(true);
|
||||
stpUtil.when(() -> StpUtil.hasPermission(McpAccessPermissionChecker.MCP_QUERY_PERMISSION))
|
||||
.thenReturn(false);
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> new McpAccessPermissionChecker().assertCanUseMcp());
|
||||
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
assertFalse(new McpAccessPermissionChecker().canUseMcp());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP 查询权限同时授予 MCP 候选查看和绑定使用能力。
|
||||
*/
|
||||
@Test
|
||||
public void mcpQueryPermissionAllowsUse() {
|
||||
try (MockedStatic<StpUtil> stpUtil = mockStatic(StpUtil.class)) {
|
||||
stpUtil.when(StpUtil::isLogin).thenReturn(true);
|
||||
stpUtil.when(() -> StpUtil.hasPermission(McpAccessPermissionChecker.MCP_QUERY_PERMISSION))
|
||||
.thenReturn(true);
|
||||
McpAccessPermissionChecker checker = new McpAccessPermissionChecker();
|
||||
|
||||
checker.assertCanUseMcp();
|
||||
|
||||
assertTrue(checker.canUseMcp());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,5 +39,11 @@
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>5.12.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
@@ -20,6 +20,9 @@ public class ApprovalInstanceBase implements Serializable {
|
||||
@Id(keyType = KeyType.Generator, value = "snowFlakeId", comment = "主键")
|
||||
private BigInteger id;
|
||||
|
||||
@Column(tenantId = true, comment = "租户ID")
|
||||
private BigInteger tenantId;
|
||||
|
||||
@Column(comment = "流程ID")
|
||||
private BigInteger flowId;
|
||||
|
||||
@@ -82,6 +85,14 @@ public class ApprovalInstanceBase implements Serializable {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public BigInteger getTenantId() {
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
public void setTenantId(BigInteger tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
}
|
||||
|
||||
public BigInteger getFlowId() {
|
||||
return flowId;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,16 @@ public class ApprovalInstancePageVo {
|
||||
|
||||
private BigInteger applicantId;
|
||||
|
||||
/**
|
||||
* 申请人展示名称。
|
||||
*/
|
||||
private String applicantName;
|
||||
|
||||
/**
|
||||
* 申请人登录账号。
|
||||
*/
|
||||
private String applicantAccount;
|
||||
|
||||
private Date submittedAt;
|
||||
|
||||
private Date finishedAt;
|
||||
@@ -131,6 +141,42 @@ public class ApprovalInstancePageVo {
|
||||
this.applicantId = applicantId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取申请人展示名称。
|
||||
*
|
||||
* @return 申请人展示名称
|
||||
*/
|
||||
public String getApplicantName() {
|
||||
return applicantName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置申请人展示名称。
|
||||
*
|
||||
* @param applicantName 申请人展示名称
|
||||
*/
|
||||
public void setApplicantName(String applicantName) {
|
||||
this.applicantName = applicantName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取申请人登录账号。
|
||||
*
|
||||
* @return 申请人登录账号
|
||||
*/
|
||||
public String getApplicantAccount() {
|
||||
return applicantAccount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置申请人登录账号。
|
||||
*
|
||||
* @param applicantAccount 申请人登录账号
|
||||
*/
|
||||
public void setApplicantAccount(String applicantAccount) {
|
||||
this.applicantAccount = applicantAccount;
|
||||
}
|
||||
|
||||
public Date getSubmittedAt() {
|
||||
return submittedAt;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,15 @@ public interface ApprovalActionFacade {
|
||||
*/
|
||||
ApprovalActionResult submit(ApprovalSubmitRequest request);
|
||||
|
||||
/**
|
||||
* 判断当前登录用户是否经资源处理器授权查看审批详情。
|
||||
*
|
||||
* @param resourceType 资源类型
|
||||
* @param identifier 资源标识
|
||||
* @return 允许查看时返回 {@code true}
|
||||
*/
|
||||
boolean canAccessApprovalDetail(String resourceType, Object identifier);
|
||||
|
||||
/**
|
||||
* 处理审批通过后的业务回调。
|
||||
*
|
||||
|
||||
@@ -26,6 +26,17 @@ public interface ApprovalSubjectHandler {
|
||||
*/
|
||||
ApprovalSubmitRequest buildSubmitRequest(BigInteger resourceId, String actionType, BigInteger operatorId);
|
||||
|
||||
/**
|
||||
* 判断当前登录用户是否可通过资源权限查看审批详情。
|
||||
*
|
||||
* <p>审批申请人和任务处理人的访问由审批模块统一判断;该方法只负责补充资源自身的
|
||||
* 授权口径,避免审批详情绕过资源权限系统。</p>
|
||||
*
|
||||
* @param identifier 资源标识
|
||||
* @return 允许查看时返回 {@code true}
|
||||
*/
|
||||
boolean canAccessApprovalDetail(Object identifier);
|
||||
|
||||
/**
|
||||
* 校验资源是否已发布。
|
||||
*
|
||||
|
||||
@@ -49,6 +49,15 @@ public class ApprovalActionFacadeImpl implements ApprovalActionFacade {
|
||||
return ApprovalActionResult.required(instanceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean canAccessApprovalDetail(String resourceType, Object identifier) {
|
||||
ApprovalSubjectHandler handler = getHandler(resourceType);
|
||||
return handler.canAccessApprovalDetail(identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
|
||||
@@ -5,6 +5,8 @@ import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.approval.entity.ApprovalInstance;
|
||||
import tech.easyflow.approval.entity.ApprovalFlowStep;
|
||||
@@ -25,6 +27,8 @@ import tech.easyflow.approval.mapper.ApprovalLogMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalTaskMapper;
|
||||
import tech.easyflow.approval.service.ApprovalInstanceService;
|
||||
import tech.easyflow.approval.service.ApprovalMatchService;
|
||||
import tech.easyflow.system.entity.SysAccount;
|
||||
import tech.easyflow.system.service.SysAccountService;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigInteger;
|
||||
@@ -61,6 +65,9 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
@Resource
|
||||
private ApprovalAssigneeService approvalAssigneeService;
|
||||
|
||||
@Resource
|
||||
private SysAccountService sysAccountService;
|
||||
|
||||
@Lazy
|
||||
@Resource
|
||||
private ApprovalActionFacade approvalActionFacade;
|
||||
@@ -71,13 +78,24 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public BigInteger submitApproval(ApprovalSubmitRequest request) {
|
||||
ApprovalFlowDetailVo flow = approvalMatchService.matchFlow(request);
|
||||
if (CollectionUtil.isEmpty(flow.getSteps())) {
|
||||
throw new BusinessException("审批流程未配置步骤");
|
||||
if (request == null) {
|
||||
throw new BusinessException("审批请求不能为空");
|
||||
}
|
||||
if (request.getApplicantId() == null) {
|
||||
throw new BusinessException("申请人不能为空");
|
||||
}
|
||||
LoginAccount loginAccount = requireCurrentLoginAccount();
|
||||
if (!loginAccount.getId().equals(request.getApplicantId())) {
|
||||
throw new BusinessException(403, 403, "不允许以其他账号身份提交审批");
|
||||
}
|
||||
SysAccount applicant = requireTenantAccount(request.getApplicantId(), "申请人");
|
||||
if (!loginAccount.getTenantId().equals(applicant.getTenantId())) {
|
||||
throw new BusinessException(403, 403, "申请人租户信息与当前登录态不一致");
|
||||
}
|
||||
ApprovalFlowDetailVo flow = approvalMatchService.matchFlow(request);
|
||||
if (CollectionUtil.isEmpty(flow.getSteps())) {
|
||||
throw new BusinessException("审批流程未配置步骤");
|
||||
}
|
||||
|
||||
List<ApprovalFlowStepVo> steps = new ArrayList<>(flow.getSteps());
|
||||
steps.sort(Comparator.comparing(ApprovalFlowStepVo::getStepNo));
|
||||
@@ -85,6 +103,7 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
Date now = new Date();
|
||||
|
||||
ApprovalInstance instance = new ApprovalInstance();
|
||||
instance.setTenantId(applicant.getTenantId());
|
||||
instance.setFlowId(flow.getId());
|
||||
instance.setFlowVersion(flow.getVersion());
|
||||
instance.setResourceType(flow.getResourceType());
|
||||
@@ -124,7 +143,7 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void approve(BigInteger instanceId, String comment, BigInteger operatorId) {
|
||||
ApprovalInstance instance = requireActiveInstance(instanceId);
|
||||
ApprovalInstance instance = requireActiveInstance(instanceId, operatorId);
|
||||
ApprovalTask currentTask = requireCurrentTask(instanceId, instance.getCurrentStepNo());
|
||||
assertTaskOperable(currentTask, operatorId);
|
||||
List<ApprovalFlowStepVo> steps = resolveFrozenSteps(instance);
|
||||
@@ -161,7 +180,7 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void reject(BigInteger instanceId, String comment, BigInteger operatorId) {
|
||||
ApprovalInstance instance = requireActiveInstance(instanceId);
|
||||
ApprovalInstance instance = requireActiveInstance(instanceId, operatorId);
|
||||
ApprovalTask currentTask = requireCurrentTask(instanceId, instance.getCurrentStepNo());
|
||||
assertTaskOperable(currentTask, operatorId);
|
||||
Date now = new Date();
|
||||
@@ -184,7 +203,7 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void revoke(BigInteger instanceId, String comment, BigInteger operatorId) {
|
||||
ApprovalInstance instance = requireActiveInstance(instanceId);
|
||||
ApprovalInstance instance = requireActiveInstance(instanceId, operatorId);
|
||||
// 撤回属于发起人的自助操作,不能沿用审批任务处理人的授权口径。
|
||||
if (!Objects.equals(instance.getApplicantId(), operatorId)) {
|
||||
throw new BusinessException(403, 403, "仅审批申请人可以撤回该请求");
|
||||
@@ -209,7 +228,9 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
*/
|
||||
@Override
|
||||
public boolean existsActiveInstance(String resourceType, BigInteger resourceId) {
|
||||
BigInteger tenantId = requireCurrentTenantId();
|
||||
QueryWrapper queryWrapper = QueryWrapper.create()
|
||||
.eq(ApprovalInstance::getTenantId, tenantId)
|
||||
.eq(ApprovalInstance::getResourceType, resourceType)
|
||||
.eq(ApprovalInstance::getResourceId, resourceId)
|
||||
.notIn(ApprovalInstance::getStatus,
|
||||
@@ -224,7 +245,9 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
*/
|
||||
@Override
|
||||
public ApprovalInstance getById(BigInteger instanceId) {
|
||||
return approvalInstanceMapper.selectOneById(instanceId);
|
||||
return approvalInstanceMapper.selectOneByQuery(QueryWrapper.create()
|
||||
.eq(ApprovalInstance::getId, instanceId)
|
||||
.eq(ApprovalInstance::getTenantId, requireCurrentTenantId()));
|
||||
}
|
||||
|
||||
private Map<String, Object> buildInstanceSnapshot(ApprovalSubmitRequest request, ApprovalFlowDetailVo flow,
|
||||
@@ -344,15 +367,17 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
approvalLogMapper.insert(log);
|
||||
}
|
||||
|
||||
private ApprovalInstance requireActiveInstance(BigInteger instanceId) {
|
||||
private ApprovalInstance requireActiveInstance(BigInteger instanceId, BigInteger operatorId) {
|
||||
if (instanceId == null) {
|
||||
throw new BusinessException("审批实例ID不能为空");
|
||||
}
|
||||
ApprovalInstance instance = approvalInstanceMapper.selectOneByQuery(
|
||||
QueryWrapper.create().eq(ApprovalInstance::getId, instanceId).forUpdate()
|
||||
);
|
||||
SysAccount operator = requireTenantAccount(operatorId, "操作人");
|
||||
ApprovalInstance instance = approvalInstanceMapper.selectOneByQuery(QueryWrapper.create()
|
||||
.eq(ApprovalInstance::getId, instanceId)
|
||||
.eq(ApprovalInstance::getTenantId, operator.getTenantId())
|
||||
.forUpdate());
|
||||
if (instance == null) {
|
||||
throw new BusinessException("审批实例不存在");
|
||||
throw new BusinessException(404, 404, "审批实例不存在");
|
||||
}
|
||||
if (ApprovalInstanceStatus.from(instance.getStatus()).isFinished()) {
|
||||
throw new BusinessException("审批实例已结束,无法继续处理");
|
||||
@@ -360,6 +385,49 @@ public class ApprovalInstanceServiceImpl implements ApprovalInstanceService {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取账号及其稳定租户归属。
|
||||
*
|
||||
* @param accountId 账号 ID
|
||||
* @param accountLabel 账号角色说明
|
||||
* @return 有效账号
|
||||
* @throws BusinessException 账号不存在或缺少租户归属时抛出
|
||||
*/
|
||||
private SysAccount requireTenantAccount(BigInteger accountId, String accountLabel) {
|
||||
if (accountId == null) {
|
||||
throw new BusinessException(accountLabel + "不能为空");
|
||||
}
|
||||
SysAccount account = sysAccountService.getById(accountId);
|
||||
if (account == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(403, 403, accountLabel + "不存在或租户信息无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录账号的租户 ID。
|
||||
*
|
||||
* @return 当前租户 ID
|
||||
* @throws BusinessException 登录态缺少账号或租户信息时抛出
|
||||
*/
|
||||
private BigInteger requireCurrentTenantId() {
|
||||
return requireCurrentLoginAccount().getTenantId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整的当前登录账号。
|
||||
*
|
||||
* @return 当前登录账号
|
||||
* @throws BusinessException 登录态缺少账号或租户信息时抛出
|
||||
*/
|
||||
private LoginAccount requireCurrentLoginAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
private ApprovalTask requireCurrentTask(BigInteger instanceId, Integer stepNo) {
|
||||
QueryWrapper queryWrapper = QueryWrapper.create()
|
||||
.eq(ApprovalTask::getInstanceId, instanceId)
|
||||
|
||||
@@ -26,9 +26,11 @@ import tech.easyflow.approval.mapper.ApprovalFlowStepMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalInstanceMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalLogMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalTaskMapper;
|
||||
import tech.easyflow.approval.service.ApprovalActionFacade;
|
||||
import tech.easyflow.approval.service.ApprovalAssigneeService;
|
||||
import tech.easyflow.approval.service.ApprovalQueryService;
|
||||
import tech.easyflow.system.entity.SysAccount;
|
||||
import tech.easyflow.system.service.CategoryPermissionService;
|
||||
import tech.easyflow.system.service.SysAccountService;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
@@ -64,6 +66,12 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
@Resource
|
||||
private ApprovalAssigneeService approvalAssigneeService;
|
||||
|
||||
@Resource
|
||||
private ApprovalActionFacade approvalActionFacade;
|
||||
|
||||
@Resource
|
||||
private CategoryPermissionService categoryPermissionService;
|
||||
|
||||
@Resource
|
||||
private SysAccountService sysAccountService;
|
||||
|
||||
@@ -80,6 +88,7 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
return new Page<>(List.of(), safePageNumber(pageNumber), safePageSize(pageSize), 0L);
|
||||
}
|
||||
QueryWrapper queryWrapper = buildBaseQuery(resourceType, actionType, keyword);
|
||||
queryWrapper.eq(ApprovalInstance::getTenantId, account.getTenantId());
|
||||
queryWrapper.in(ApprovalInstance::getId, instanceIds);
|
||||
queryWrapper.in(ApprovalInstance::getStatus, List.of(
|
||||
ApprovalInstanceStatus.PENDING.getCode(),
|
||||
@@ -109,6 +118,7 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
return new Page<>(List.of(), safePageNumber(pageNumber), safePageSize(pageSize), 0L);
|
||||
}
|
||||
QueryWrapper queryWrapper = buildBaseQuery(resourceType, actionType, keyword);
|
||||
queryWrapper.eq(ApprovalInstance::getTenantId, account.getTenantId());
|
||||
queryWrapper.in(ApprovalInstance::getId, instanceIds);
|
||||
queryWrapper.orderBy("finished_at desc, id desc");
|
||||
return mapPage(queryWrapper, safePageNumber(pageNumber), safePageSize(pageSize), false, account, Set.of());
|
||||
@@ -122,6 +132,7 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
Long pageNumber, Long pageSize) {
|
||||
LoginAccount account = requireLoginAccount();
|
||||
QueryWrapper queryWrapper = buildBaseQuery(resourceType, actionType, keyword);
|
||||
queryWrapper.eq(ApprovalInstance::getTenantId, account.getTenantId());
|
||||
queryWrapper.eq(ApprovalInstance::getApplicantId, account.getId());
|
||||
queryWrapper.orderBy("submitted_at desc, id desc");
|
||||
return mapPage(queryWrapper, safePageNumber(pageNumber), safePageSize(pageSize), false, account, Set.of());
|
||||
@@ -132,10 +143,18 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
*/
|
||||
@Override
|
||||
public ApprovalInstanceDetailVo detail(BigInteger instanceId) {
|
||||
ApprovalInstance instance = approvalInstanceMapper.selectOneById(instanceId);
|
||||
if (instance == null) {
|
||||
throw new BusinessException("审批实例不存在");
|
||||
LoginAccount account = requireLoginAccount();
|
||||
ApprovalInstance instance = approvalInstanceMapper.selectOneByQuery(QueryWrapper.create()
|
||||
.eq(ApprovalInstance::getId, instanceId)
|
||||
.eq(ApprovalInstance::getTenantId, account.getTenantId()));
|
||||
if (instance == null || !Objects.equals(account.getTenantId(), instance.getTenantId())) {
|
||||
throw new BusinessException(404, 404, "审批实例不存在");
|
||||
}
|
||||
List<ApprovalTask> tasks = approvalTaskMapper.selectListByQuery(
|
||||
QueryWrapper.create().eq(ApprovalTask::getInstanceId, instanceId));
|
||||
Set<BigInteger> roleIds = approvalAssigneeService.getAvailableRoleIds(account.getId());
|
||||
assertDetailAccess(instance, tasks, account, roleIds);
|
||||
|
||||
ApprovalInstanceDetailVo detail = new ApprovalInstanceDetailVo();
|
||||
detail.setId(instance.getId());
|
||||
detail.setFlowId(instance.getFlowId());
|
||||
@@ -152,12 +171,10 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
detail.setFinishedAt(instance.getFinishedAt());
|
||||
detail.setSnapshotJson(instance.getSnapshotJson());
|
||||
|
||||
List<ApprovalTask> tasks = approvalTaskMapper.selectListByQuery(
|
||||
QueryWrapper.create().eq(ApprovalTask::getInstanceId, instanceId));
|
||||
List<ApprovalLog> logs = approvalLogMapper.selectListByQuery(
|
||||
QueryWrapper.create().eq(ApprovalLog::getInstanceId, instanceId));
|
||||
Map<Integer, ApprovalFlowStepVo> frozenStepMap = resolveFrozenStepMap(instance);
|
||||
Map<BigInteger, SysAccount> accountMap = loadAccountMap(instance, tasks, logs);
|
||||
Map<BigInteger, SysAccount> accountMap = loadAccountMap(instance, tasks, logs, account.getTenantId());
|
||||
detail.setApplicantName(resolveAccountName(accountMap.get(instance.getApplicantId())));
|
||||
detail.setApplicantAccount(resolveAccountLoginName(accountMap.get(instance.getApplicantId())));
|
||||
|
||||
@@ -201,8 +218,6 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
})
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
LoginAccount account = requireLoginAccount();
|
||||
Set<BigInteger> roleIds = approvalAssigneeService.getAvailableRoleIds(account.getId());
|
||||
boolean active = !ApprovalInstanceStatus.from(instance.getStatus()).isFinished();
|
||||
boolean canReview = active
|
||||
&& tasks.stream().anyMatch(item -> item.getStepNo().equals(instance.getCurrentStepNo())
|
||||
@@ -220,10 +235,11 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
* @param instance 审批实例
|
||||
* @param tasks 审批任务列表
|
||||
* @param logs 审批日志列表
|
||||
* @param tenantId 当前租户 ID
|
||||
* @return 账号 ID 到账号实体的映射
|
||||
*/
|
||||
private Map<BigInteger, SysAccount> loadAccountMap(ApprovalInstance instance, List<ApprovalTask> tasks,
|
||||
List<ApprovalLog> logs) {
|
||||
List<ApprovalLog> logs, BigInteger tenantId) {
|
||||
Set<BigInteger> accountIds = new HashSet<>();
|
||||
if (instance.getApplicantId() != null) {
|
||||
accountIds.add(instance.getApplicantId());
|
||||
@@ -239,7 +255,9 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
if (CollectionUtil.isEmpty(accountIds)) {
|
||||
return Map.of();
|
||||
}
|
||||
return sysAccountService.listByIds(accountIds).stream()
|
||||
return sysAccountService.list(QueryWrapper.create()
|
||||
.in(SysAccount::getId, accountIds)
|
||||
.eq(SysAccount::getTenantId, tenantId)).stream()
|
||||
.collect(Collectors.toMap(
|
||||
SysAccount::getId,
|
||||
account -> account,
|
||||
@@ -297,6 +315,7 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
boolean pendingMode, LoginAccount account, Set<BigInteger> roleIds) {
|
||||
Page<ApprovalInstance> page = approvalInstanceMapper.paginate(pageNumber, pageSize, queryWrapper);
|
||||
List<ApprovalInstance> records = page.getRecords();
|
||||
Map<BigInteger, SysAccount> applicantAccountMap = loadApplicantAccountMap(records, account.getTenantId());
|
||||
Set<BigInteger> pendingTaskInstanceIds = pendingMode
|
||||
? approvalAssigneeService.listPendingInstanceIds(account.getId(), roleIds,
|
||||
records.stream().map(ApprovalInstance::getId).collect(Collectors.toList()))
|
||||
@@ -315,6 +334,9 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
item.setSummary(record.getSummary());
|
||||
item.setApplicationReason(record.getApplicationReason());
|
||||
item.setApplicantId(record.getApplicantId());
|
||||
SysAccount applicantAccount = applicantAccountMap.get(record.getApplicantId());
|
||||
item.setApplicantName(resolveAccountName(applicantAccount));
|
||||
item.setApplicantAccount(resolveAccountLoginName(applicantAccount));
|
||||
item.setSubmittedAt(record.getSubmittedAt());
|
||||
item.setFinishedAt(record.getFinishedAt());
|
||||
boolean active = !ApprovalInstanceStatus.from(record.getStatus()).isFinished();
|
||||
@@ -332,6 +354,31 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
return voPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量加载分页记录中的申请人账号,避免列表逐行查询。
|
||||
*
|
||||
* @param records 审批实例分页记录
|
||||
* @param tenantId 当前租户 ID
|
||||
* @return 申请人 ID 到账号实体的映射
|
||||
*/
|
||||
private Map<BigInteger, SysAccount> loadApplicantAccountMap(List<ApprovalInstance> records, BigInteger tenantId) {
|
||||
Set<BigInteger> applicantIds = records.stream()
|
||||
.map(ApprovalInstance::getApplicantId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
if (CollectionUtil.isEmpty(applicantIds)) {
|
||||
return Map.of();
|
||||
}
|
||||
return sysAccountService.list(QueryWrapper.create()
|
||||
.in(SysAccount::getId, applicantIds)
|
||||
.eq(SysAccount::getTenantId, tenantId)).stream()
|
||||
.collect(Collectors.toMap(
|
||||
SysAccount::getId,
|
||||
account -> account,
|
||||
(left, right) -> left,
|
||||
LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private long safePageNumber(Long pageNumber) {
|
||||
return pageNumber == null || pageNumber < 1 ? 1L : pageNumber;
|
||||
}
|
||||
@@ -342,12 +389,39 @@ public class ApprovalQueryServiceImpl implements ApprovalQueryService {
|
||||
|
||||
private LoginAccount requireLoginAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null) {
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException("当前未登录");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验审批详情的主体权限。
|
||||
*
|
||||
* @param instance 审批实例
|
||||
* @param tasks 审批任务
|
||||
* @param account 当前账号
|
||||
* @param roleIds 当前账号的有效角色 ID
|
||||
* @throws BusinessException 当前用户不是申请人、处理人、同租户超管或资源授权者时抛出
|
||||
*/
|
||||
private void assertDetailAccess(ApprovalInstance instance,
|
||||
List<ApprovalTask> tasks,
|
||||
LoginAccount account,
|
||||
Set<BigInteger> roleIds) {
|
||||
if (account.getId().equals(instance.getApplicantId())
|
||||
|| categoryPermissionService.isSuperAdmin(account)) {
|
||||
return;
|
||||
}
|
||||
boolean taskParticipant = tasks.stream().anyMatch(task -> account.getId().equals(task.getActedBy())
|
||||
|| ApprovalTaskStatus.PENDING.getCode().equals(task.getStatus())
|
||||
&& approvalAssigneeService.canHandleTask(task, account.getId(), roleIds));
|
||||
if (taskParticipant
|
||||
|| approvalActionFacade.canAccessApprovalDetail(instance.getResourceType(), instance.getResourceId())) {
|
||||
return;
|
||||
}
|
||||
throw new BusinessException(403, 403, "无权限查看该审批实例");
|
||||
}
|
||||
|
||||
private String resolveCurrentStepName(ApprovalInstance instance) {
|
||||
Map<Integer, ApprovalFlowStepVo> stepMap = resolveFrozenStepMap(instance);
|
||||
return resolveStepName(stepMap, instance.getCurrentStepNo());
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package tech.easyflow.approval.service.impl;
|
||||
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import tech.easyflow.approval.entity.ApprovalInstance;
|
||||
import tech.easyflow.approval.entity.ApprovalLog;
|
||||
import tech.easyflow.approval.entity.ApprovalTask;
|
||||
import tech.easyflow.approval.entity.vo.ApprovalSubmitRequest;
|
||||
import tech.easyflow.approval.enums.ApprovalInstanceStatus;
|
||||
import tech.easyflow.approval.enums.ApprovalTaskStatus;
|
||||
import tech.easyflow.approval.mapper.ApprovalInstanceMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalLogMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalTaskMapper;
|
||||
import tech.easyflow.approval.service.ApprovalActionFacade;
|
||||
import tech.easyflow.approval.service.ApprovalMatchService;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.system.entity.SysAccount;
|
||||
import tech.easyflow.system.service.SysAccountService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link ApprovalInstanceServiceImpl} 审批提交身份授权测试。
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ApprovalInstanceServiceImplAccessTest {
|
||||
|
||||
@Mock
|
||||
private ApprovalMatchService approvalMatchService;
|
||||
|
||||
@Mock
|
||||
private SysAccountService sysAccountService;
|
||||
|
||||
@Mock
|
||||
private ApprovalInstanceMapper approvalInstanceMapper;
|
||||
|
||||
@Mock
|
||||
private ApprovalTaskMapper approvalTaskMapper;
|
||||
|
||||
@Mock
|
||||
private ApprovalLogMapper approvalLogMapper;
|
||||
|
||||
@Mock
|
||||
private ApprovalActionFacade approvalActionFacade;
|
||||
|
||||
@InjectMocks
|
||||
private ApprovalInstanceServiceImpl service;
|
||||
|
||||
/**
|
||||
* 验证同租户账号也不能代替当前登录人发起审批。
|
||||
*/
|
||||
@Test
|
||||
public void submitApprovalShouldRejectForgedApplicantBeforeMatchingFlow() {
|
||||
LoginAccount loginAccount = new LoginAccount();
|
||||
loginAccount.setId(BigInteger.ONE);
|
||||
loginAccount.setTenantId(BigInteger.valueOf(42));
|
||||
ApprovalSubmitRequest request = new ApprovalSubmitRequest();
|
||||
request.setApplicantId(BigInteger.TWO);
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(loginAccount);
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.submitApproval(request));
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
}
|
||||
|
||||
verify(sysAccountService, never()).getById(BigInteger.TWO);
|
||||
verify(approvalMatchService, never()).matchFlow(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证申请人可撤回进行中的审批,并同步结束当前任务与恢复资源状态。
|
||||
*/
|
||||
@Test
|
||||
public void revokeShouldCompleteCurrentTaskForApplicant() {
|
||||
BigInteger applicantId = BigInteger.valueOf(7);
|
||||
BigInteger tenantId = BigInteger.valueOf(42);
|
||||
BigInteger instanceId = BigInteger.valueOf(101);
|
||||
SysAccount applicant = tenantAccount(applicantId, tenantId);
|
||||
ApprovalInstance instance = activeInstance(instanceId, applicantId, tenantId);
|
||||
ApprovalTask task = new ApprovalTask();
|
||||
task.setInstanceId(instanceId);
|
||||
task.setStepNo(1);
|
||||
task.setStatus(ApprovalTaskStatus.PENDING.getCode());
|
||||
|
||||
when(sysAccountService.getById(applicantId)).thenReturn(applicant);
|
||||
when(approvalInstanceMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(instance);
|
||||
when(approvalTaskMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(task);
|
||||
|
||||
service.revoke(instanceId, "内容需要调整", applicantId);
|
||||
|
||||
assertEquals(ApprovalInstanceStatus.REVOKED.getCode(), instance.getStatus());
|
||||
assertNotNull(instance.getFinishedAt());
|
||||
assertEquals(ApprovalTaskStatus.REVOKED.getCode(), task.getStatus());
|
||||
assertEquals(applicantId, task.getActedBy());
|
||||
assertEquals("内容需要调整", task.getComment());
|
||||
verify(approvalLogMapper).insert(any(ApprovalLog.class));
|
||||
verify(approvalActionFacade).handleRevoked(instance, applicantId, "内容需要调整");
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证非申请人即使属于同一租户也不能撤回审批。
|
||||
*/
|
||||
@Test
|
||||
public void revokeShouldRejectSameTenantNonApplicant() {
|
||||
BigInteger applicantId = BigInteger.valueOf(7);
|
||||
BigInteger operatorId = BigInteger.valueOf(8);
|
||||
BigInteger tenantId = BigInteger.valueOf(42);
|
||||
BigInteger instanceId = BigInteger.valueOf(101);
|
||||
|
||||
when(sysAccountService.getById(operatorId)).thenReturn(tenantAccount(operatorId, tenantId));
|
||||
when(approvalInstanceMapper.selectOneByQuery(any(QueryWrapper.class)))
|
||||
.thenReturn(activeInstance(instanceId, applicantId, tenantId));
|
||||
|
||||
BusinessException exception = assertThrows(
|
||||
BusinessException.class,
|
||||
() -> service.revoke(instanceId, "尝试撤回", operatorId)
|
||||
);
|
||||
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
verify(approvalTaskMapper, never()).selectOneByQuery(any(QueryWrapper.class));
|
||||
verify(approvalActionFacade, never())
|
||||
.handleRevoked(any(ApprovalInstance.class), any(BigInteger.class), any(String.class));
|
||||
}
|
||||
|
||||
private ApprovalInstance activeInstance(BigInteger instanceId, BigInteger applicantId, BigInteger tenantId) {
|
||||
ApprovalInstance instance = new ApprovalInstance();
|
||||
instance.setId(instanceId);
|
||||
instance.setApplicantId(applicantId);
|
||||
instance.setTenantId(tenantId);
|
||||
instance.setCurrentStepNo(1);
|
||||
instance.setStatus(ApprovalInstanceStatus.PENDING.getCode());
|
||||
return instance;
|
||||
}
|
||||
|
||||
private SysAccount tenantAccount(BigInteger accountId, BigInteger tenantId) {
|
||||
SysAccount account = new SysAccount();
|
||||
account.setId(accountId);
|
||||
account.setTenantId(tenantId);
|
||||
return account;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package tech.easyflow.approval.service.impl;
|
||||
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import tech.easyflow.approval.entity.ApprovalInstance;
|
||||
import tech.easyflow.approval.enums.ApprovalInstanceStatus;
|
||||
import tech.easyflow.approval.mapper.ApprovalInstanceMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalTaskMapper;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.system.entity.SysAccount;
|
||||
import tech.easyflow.system.service.SysAccountService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link ApprovalInstanceServiceImpl} 审批决策并发互斥测试。
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ApprovalInstanceServiceImplConcurrencyTest {
|
||||
|
||||
@Mock
|
||||
private ApprovalInstanceMapper approvalInstanceMapper;
|
||||
@Mock
|
||||
private ApprovalTaskMapper approvalTaskMapper;
|
||||
@Mock
|
||||
private SysAccountService sysAccountService;
|
||||
@InjectMocks
|
||||
private ApprovalInstanceServiceImpl service;
|
||||
|
||||
/**
|
||||
* 审批实例与当前任务必须在状态判断前加行锁,避免重复执行同一决策。
|
||||
*/
|
||||
@Test
|
||||
public void approvalDecisionLocksInstanceAndCurrentTask() {
|
||||
BigInteger instanceId = BigInteger.valueOf(101);
|
||||
BigInteger tenantId = BigInteger.valueOf(42);
|
||||
ApprovalInstance instance = new ApprovalInstance();
|
||||
instance.setId(instanceId);
|
||||
instance.setTenantId(tenantId);
|
||||
instance.setStatus(ApprovalInstanceStatus.PENDING.getCode());
|
||||
instance.setCurrentStepNo(1);
|
||||
SysAccount operator = new SysAccount();
|
||||
operator.setId(BigInteger.ONE);
|
||||
operator.setTenantId(tenantId);
|
||||
when(sysAccountService.getById(BigInteger.ONE)).thenReturn(operator);
|
||||
when(approvalInstanceMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(instance);
|
||||
when(approvalTaskMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(null);
|
||||
|
||||
assertThrows(BusinessException.class,
|
||||
() -> service.approve(instanceId, "通过", BigInteger.ONE));
|
||||
|
||||
ArgumentCaptor<QueryWrapper> instanceQuery = ArgumentCaptor.forClass(QueryWrapper.class);
|
||||
ArgumentCaptor<QueryWrapper> taskQuery = ArgumentCaptor.forClass(QueryWrapper.class);
|
||||
verify(approvalInstanceMapper).selectOneByQuery(instanceQuery.capture());
|
||||
verify(approvalTaskMapper).selectOneByQuery(taskQuery.capture());
|
||||
assertTrue(instanceQuery.getValue().toSQL().toLowerCase(Locale.ROOT).contains("for update"));
|
||||
assertTrue(instanceQuery.getValue().toSQL().toLowerCase(Locale.ROOT).contains("tenant_id"));
|
||||
assertTrue(taskQuery.getValue().toSQL().toLowerCase(Locale.ROOT).contains("for update"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package tech.easyflow.approval.service.impl;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* V32 审批实例租户迁移契约测试。
|
||||
*/
|
||||
public class ApprovalInstanceTenantMigrationContractTest {
|
||||
|
||||
/**
|
||||
* 验证历史实例从申请人账号回填租户,且空租户会阻断迁移。
|
||||
*
|
||||
* @throws Exception 迁移文件不可读时抛出
|
||||
*/
|
||||
@Test
|
||||
public void migrationShouldBackfillAndGuardApprovalTenant() throws Exception {
|
||||
String sql = migrationSql();
|
||||
|
||||
assertTrue(sql.contains("ADD COLUMN `tenant_id` BIGINT UNSIGNED NULL"));
|
||||
assertTrue(sql.contains("LEFT JOIN `tb_sys_account` applicant ON applicant.`id` = approval.`applicant_id`"));
|
||||
assertTrue(sql.contains("applicant.`id` IS NULL OR applicant.`tenant_id` IS NULL"));
|
||||
assertTrue(sql.contains("JOIN `tb_sys_account` applicant ON applicant.`id` = approval.`applicant_id`"));
|
||||
assertTrue(sql.contains("SET approval.`tenant_id` = applicant.`tenant_id`"));
|
||||
assertTrue(sql.contains("tmp_approval_instance_tenant_guard"));
|
||||
assertTrue(sql.indexOf("tmp_approval_instance_tenant_guard") < sql.indexOf("ADD COLUMN `tenant_id`"));
|
||||
assertTrue(sql.contains("MODIFY COLUMN `tenant_id` BIGINT UNSIGNED NOT NULL"));
|
||||
assertTrue(sql.contains("`tenant_id`, `status`, `submitted_at`"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取工作区中的 V32 MySQL 迁移。
|
||||
*
|
||||
* @return 迁移 SQL
|
||||
* @throws Exception 迁移文件不存在或不可读时抛出
|
||||
*/
|
||||
private String migrationSql() throws Exception {
|
||||
Path root = Path.of(System.getProperty("maven.multiModuleProjectDirectory",
|
||||
Path.of(System.getProperty("user.dir")).toAbsolutePath().toString()));
|
||||
while (root != null) {
|
||||
Path migration = root.resolve("easyflow-starter/easyflow-starter-all/src/main/resources/"
|
||||
+ "db/migration/mysql/V32__mysql_approval_instance_tenant.sql");
|
||||
if (Files.isRegularFile(migration)) {
|
||||
return Files.readString(migration, StandardCharsets.UTF_8);
|
||||
}
|
||||
root = root.getParent();
|
||||
}
|
||||
throw new IllegalStateException("找不到 V32 审批实例租户迁移");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package tech.easyflow.approval.service.impl;
|
||||
|
||||
import com.mybatisflex.core.paginate.Page;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import tech.easyflow.approval.entity.ApprovalInstance;
|
||||
import tech.easyflow.approval.entity.ApprovalLog;
|
||||
import tech.easyflow.approval.entity.ApprovalTask;
|
||||
import tech.easyflow.approval.entity.vo.ApprovalInstanceDetailVo;
|
||||
import tech.easyflow.approval.entity.vo.ApprovalInstancePageVo;
|
||||
import tech.easyflow.approval.enums.ApprovalAssigneeType;
|
||||
import tech.easyflow.approval.enums.ApprovalEventType;
|
||||
import tech.easyflow.approval.enums.ApprovalInstanceStatus;
|
||||
import tech.easyflow.approval.enums.ApprovalTaskStatus;
|
||||
import tech.easyflow.approval.mapper.ApprovalFlowStepMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalInstanceMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalLogMapper;
|
||||
import tech.easyflow.approval.mapper.ApprovalTaskMapper;
|
||||
import tech.easyflow.approval.service.ApprovalActionFacade;
|
||||
import tech.easyflow.approval.service.ApprovalAssigneeService;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.system.entity.SysAccount;
|
||||
import tech.easyflow.system.service.CategoryPermissionService;
|
||||
import tech.easyflow.system.service.SysAccountService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
|
||||
/**
|
||||
* {@link ApprovalQueryServiceImpl} 审批详情租户和主体授权回归测试。
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ApprovalQueryServiceImplAccessTest {
|
||||
|
||||
private static final BigInteger INSTANCE_ID = BigInteger.valueOf(101);
|
||||
private static final BigInteger RESOURCE_ID = BigInteger.valueOf(501);
|
||||
private static final BigInteger TENANT_ID = BigInteger.valueOf(42);
|
||||
|
||||
@Mock
|
||||
private ApprovalInstanceMapper approvalInstanceMapper;
|
||||
@Mock
|
||||
private ApprovalTaskMapper approvalTaskMapper;
|
||||
@Mock
|
||||
private ApprovalLogMapper approvalLogMapper;
|
||||
@Mock
|
||||
private ApprovalFlowStepMapper approvalFlowStepMapper;
|
||||
@Mock
|
||||
private ApprovalAssigneeService approvalAssigneeService;
|
||||
@Mock
|
||||
private ApprovalActionFacade approvalActionFacade;
|
||||
@Mock
|
||||
private CategoryPermissionService categoryPermissionService;
|
||||
@Mock
|
||||
private SysAccountService sysAccountService;
|
||||
@InjectMocks
|
||||
private ApprovalQueryServiceImpl service;
|
||||
|
||||
/**
|
||||
* 验证详情查询显式带租户条件,并拒绝 Mapper 异常返回的跨租户实例。
|
||||
*/
|
||||
@Test
|
||||
public void detailShouldRejectCrossTenantInstanceBeforeReadingSnapshot() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(99, 99);
|
||||
when(approvalInstanceMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(instance);
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.detail(INSTANCE_ID));
|
||||
assertEquals(404, exception.getHttpStatus());
|
||||
}
|
||||
|
||||
ArgumentCaptor<QueryWrapper> query = ArgumentCaptor.forClass(QueryWrapper.class);
|
||||
verify(approvalInstanceMapper).selectOneByQuery(query.capture());
|
||||
assertTrue(query.getValue().toSQL().toLowerCase(Locale.ROOT).contains("tenant_id"));
|
||||
verify(approvalTaskMapper, never()).selectListByQuery(any(QueryWrapper.class));
|
||||
verify(approvalLogMapper, never()).selectListByQuery(any(QueryWrapper.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证同租户普通用户不能仅凭审批查询操作权限读取完整资源快照。
|
||||
*/
|
||||
@Test
|
||||
public void detailShouldRejectSameTenantNonParticipant() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(8, 42);
|
||||
when(approvalInstanceMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(instance);
|
||||
when(approvalTaskMapper.selectListByQuery(any(QueryWrapper.class))).thenReturn(List.of());
|
||||
when(approvalAssigneeService.getAvailableRoleIds(account.getId())).thenReturn(Set.of());
|
||||
when(approvalActionFacade.canAccessApprovalDetail("SKILL", RESOURCE_ID)).thenReturn(false);
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.detail(INSTANCE_ID));
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
}
|
||||
|
||||
verify(approvalLogMapper, never()).selectListByQuery(any(QueryWrapper.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证申请人仍可读取自己发起的审批快照。
|
||||
*/
|
||||
@Test
|
||||
public void detailShouldAllowApplicant() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(7, 42);
|
||||
Map<String, Object> snapshot = instance.getSnapshotJson();
|
||||
stubAuthorizedDetail(instance, account, List.of());
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
ApprovalInstanceDetailVo detail = service.detail(INSTANCE_ID);
|
||||
assertSame(snapshot, detail.getSnapshotJson());
|
||||
assertFalse(detail.isCanApprove());
|
||||
assertFalse(detail.isCanReject());
|
||||
assertTrue(detail.isCanRevoke());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证当前待办处理人可查看审批详情。
|
||||
*/
|
||||
@Test
|
||||
public void detailShouldAllowCurrentTaskHandler() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(8, 42);
|
||||
ApprovalTask task = task(ApprovalTaskStatus.PENDING.getCode(), null);
|
||||
task.setAssigneeType(ApprovalAssigneeType.USER.getCode());
|
||||
task.setAssigneeTargetId(account.getId());
|
||||
stubAuthorizedDetail(instance, account, List.of(task));
|
||||
when(approvalAssigneeService.canHandleTask(task, account.getId(), Set.of())).thenReturn(true);
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
ApprovalInstanceDetailVo detail = service.detail(INSTANCE_ID);
|
||||
assertEquals(INSTANCE_ID, detail.getId());
|
||||
assertTrue(detail.isCanApprove());
|
||||
assertTrue(detail.isCanReject());
|
||||
assertFalse(detail.isCanRevoke());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证实际处理过历史步骤的用户仍可查看审批详情。
|
||||
*/
|
||||
@Test
|
||||
public void detailShouldAllowHistoricalActor() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(8, 42);
|
||||
ApprovalTask task = task(ApprovalTaskStatus.APPROVED.getCode(), account.getId());
|
||||
stubAuthorizedDetail(instance, account, List.of(task));
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
assertEquals(INSTANCE_ID, service.detail(INSTANCE_ID).getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证审批说明在详情、审批任务和提交日志中完整透传。
|
||||
*/
|
||||
@Test
|
||||
public void detailShouldExposeApplicationReasonAcrossRelatedViews() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(7, 42);
|
||||
instance.setApplicationReason("发布新的问答流程");
|
||||
ApprovalTask task = task(ApprovalTaskStatus.PENDING.getCode(), null);
|
||||
ApprovalLog log = new ApprovalLog();
|
||||
log.setEventType(ApprovalEventType.SUBMITTED.getCode());
|
||||
stubAuthorizedDetail(instance, account, List.of(task));
|
||||
when(approvalLogMapper.selectListByQuery(any(QueryWrapper.class))).thenReturn(List.of(log));
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
ApprovalInstanceDetailVo detail = service.detail(INSTANCE_ID);
|
||||
assertEquals("发布新的问答流程", detail.getApplicationReason());
|
||||
assertEquals("发布新的问答流程", detail.getTasks().get(0).getApplicationReason());
|
||||
assertEquals("发布新的问答流程", detail.getLogs().get(0).getApplicationReason());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证审批分页列表返回申请人填写的审批说明和账号信息。
|
||||
*/
|
||||
@Test
|
||||
public void initiatedPageShouldExposeApplicationReasonAndApplicant() {
|
||||
LoginAccount account = account(7, 42);
|
||||
ApprovalInstance instance = instance(7, 42);
|
||||
instance.setApplicationReason("发布新的问答流程");
|
||||
SysAccount applicant = new SysAccount();
|
||||
applicant.setId(account.getId());
|
||||
applicant.setNickname("陈子默");
|
||||
applicant.setLoginName("czm");
|
||||
Page<ApprovalInstance> page = new Page<>(List.of(instance), 1L, 10L, 1L);
|
||||
when(approvalInstanceMapper.paginate(anyLong(), anyLong(), any(QueryWrapper.class))).thenReturn(page);
|
||||
when(sysAccountService.list(any(QueryWrapper.class))).thenReturn(List.of(applicant));
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
ApprovalInstancePageVo item = service.initiatedPage(null, null, null, 1L, 10L)
|
||||
.getRecords()
|
||||
.get(0);
|
||||
assertEquals("发布新的问答流程", item.getApplicationReason());
|
||||
assertEquals("陈子默", item.getApplicantName());
|
||||
assertEquals("czm", item.getApplicantAccount());
|
||||
assertTrue(item.isCanRevoke());
|
||||
assertFalse(item.isCanApprove());
|
||||
assertFalse(item.isCanReject());
|
||||
}
|
||||
}
|
||||
|
||||
private void stubAuthorizedDetail(ApprovalInstance instance, LoginAccount account, List<ApprovalTask> tasks) {
|
||||
when(approvalInstanceMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(instance);
|
||||
when(approvalTaskMapper.selectListByQuery(any(QueryWrapper.class))).thenReturn(tasks);
|
||||
when(approvalAssigneeService.getAvailableRoleIds(account.getId())).thenReturn(Set.of());
|
||||
when(approvalLogMapper.selectListByQuery(any(QueryWrapper.class))).thenReturn(List.of());
|
||||
when(sysAccountService.list(any(QueryWrapper.class))).thenReturn(List.of());
|
||||
}
|
||||
|
||||
private ApprovalInstance instance(long applicantId, long tenantId) {
|
||||
ApprovalInstance instance = new ApprovalInstance();
|
||||
instance.setId(INSTANCE_ID);
|
||||
instance.setTenantId(BigInteger.valueOf(tenantId));
|
||||
instance.setFlowId(BigInteger.valueOf(301));
|
||||
instance.setFlowVersion(1);
|
||||
instance.setResourceType("SKILL");
|
||||
instance.setResourceId(RESOURCE_ID);
|
||||
instance.setActionType("PUBLISH");
|
||||
instance.setStatus(ApprovalInstanceStatus.PENDING.getCode());
|
||||
instance.setCurrentStepNo(1);
|
||||
instance.setApplicantId(BigInteger.valueOf(applicantId));
|
||||
instance.setSnapshotJson(Map.of(
|
||||
"resourceSnapshot", Map.of("skillContent", "private prompt"),
|
||||
"steps", List.of(Map.of(
|
||||
"stepNo", 1,
|
||||
"stepName", "审核",
|
||||
"assigneeType", ApprovalAssigneeType.USER.getCode(),
|
||||
"assigneeTargetId", 7))));
|
||||
return instance;
|
||||
}
|
||||
|
||||
private ApprovalTask task(String status, BigInteger actedBy) {
|
||||
ApprovalTask task = new ApprovalTask();
|
||||
task.setInstanceId(INSTANCE_ID);
|
||||
task.setStepNo(1);
|
||||
task.setStatus(status);
|
||||
task.setActedBy(actedBy);
|
||||
return task;
|
||||
}
|
||||
|
||||
private LoginAccount account(long accountId, long tenantId) {
|
||||
LoginAccount account = new LoginAccount();
|
||||
account.setId(BigInteger.valueOf(accountId));
|
||||
account.setTenantId(BigInteger.valueOf(tenantId));
|
||||
return account;
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,10 @@
|
||||
<groupId>tech.easyflow</groupId>
|
||||
<artifactId>easyflow-common-file-storage</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tech.easyflow</groupId>
|
||||
<artifactId>easyflow-common-cache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mybatis-flex</groupId>
|
||||
<artifactId>mybatis-flex-spring-boot3-starter</artifactId>
|
||||
@@ -49,11 +53,26 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>5.12.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Skill 能力绑定业务服务。
|
||||
*/
|
||||
public interface SkillCapabilityBindingService extends IService<SkillCapabilityBinding> {
|
||||
|
||||
/**
|
||||
* 查询当前用户可查看的 Skill 能力绑定。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @return 有序绑定列表
|
||||
*/
|
||||
List<SkillCapabilityBinding> listBindings(BigInteger skillId);
|
||||
|
||||
/**
|
||||
* 查询面向管理端读取接口的安全绑定,并按当前用户 MANAGE 权限隐藏内部目标 ID。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @return 有序安全绑定列表
|
||||
*/
|
||||
List<SkillCapabilityBinding> listVisibleBindings(BigInteger skillId);
|
||||
|
||||
/**
|
||||
* 原子替换 Skill 能力绑定。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param bindings 新绑定列表
|
||||
* @return 保存后的绑定列表
|
||||
*/
|
||||
List<SkillCapabilityBinding> replaceBindings(BigInteger skillId, List<SkillCapabilityBinding> bindings);
|
||||
|
||||
/**
|
||||
* 按客户端读取到的能力 hash 原子替换绑定,防止多标签页相互覆盖。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param bindings 新绑定列表
|
||||
* @param expectedCapabilityHash 客户端读取到的能力 hash
|
||||
* @return 保存后的绑定列表
|
||||
*/
|
||||
List<SkillCapabilityBinding> replaceBindings(BigInteger skillId,
|
||||
List<SkillCapabilityBinding> bindings,
|
||||
String expectedCapabilityHash);
|
||||
|
||||
/**
|
||||
* 校验待保存或现有绑定。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param bindings 可选待校验绑定,为空时校验已保存绑定
|
||||
* @param publishValidation 是否执行发布级实时工具解析
|
||||
* @return 结构化校验结果
|
||||
*/
|
||||
SkillValidationResult validateBindings(BigInteger skillId,
|
||||
List<SkillCapabilityBinding> bindings,
|
||||
boolean publishValidation);
|
||||
|
||||
/**
|
||||
* 校验增强包导入预览中的能力绑定。
|
||||
*
|
||||
* <p>该入口不读取或写入 Skill 业务数据,也不要求已有 Skill 权限。未映射目标仅保留给
|
||||
* 导入映射步骤处理;已经映射的目标仍会校验当前操作者的使用权限和可用状态。</p>
|
||||
*
|
||||
* @param bindings 从增强包 manifest 还原的能力绑定
|
||||
* @return 结构化校验结果
|
||||
*/
|
||||
SkillValidationResult validateImportBindings(List<SkillCapabilityBinding> bindings);
|
||||
|
||||
/**
|
||||
* 查询可绑定能力候选项。
|
||||
*
|
||||
* @param capabilityType 能力类型
|
||||
* @param keyword 关键词
|
||||
* @return 候选列表
|
||||
*/
|
||||
List<SkillCapabilityCandidate> listCandidates(SkillCapabilityType capabilityType, String keyword);
|
||||
|
||||
/**
|
||||
* 按需获取 MCP 工具清单。
|
||||
*
|
||||
* @param targetId MCP ID
|
||||
* @return MCP 候选详情
|
||||
*/
|
||||
SkillCapabilityCandidate getMcpTools(BigInteger targetId);
|
||||
|
||||
/**
|
||||
* 构建经过发布级校验的安全快照。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @return 不含凭据的能力快照
|
||||
*/
|
||||
List<Map<String, Object>> buildPublishSnapshot(BigInteger skillId);
|
||||
|
||||
/**
|
||||
* 计算当前能力配置 hash。
|
||||
*
|
||||
* @param bindings 能力绑定
|
||||
* @return SHA-256 hash
|
||||
*/
|
||||
String calculateHash(List<SkillCapabilityBinding> bindings);
|
||||
|
||||
/**
|
||||
* 基于数据库原始绑定计算 hash,不暴露可能被展示边界脱敏的历史配置。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @return SHA-256 hash
|
||||
*/
|
||||
String calculateStoredHash(BigInteger skillId);
|
||||
|
||||
/**
|
||||
* 删除 Skill 的全部能力绑定。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
*/
|
||||
void removeBySkillId(BigInteger skillId);
|
||||
}
|
||||
@@ -0,0 +1,990 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import com.easyagents.skill.util.SkillHashes;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tech.easyflow.ai.permission.McpAccessPermissionChecker;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityExecutionMode;
|
||||
import tech.easyflow.skill.enums.SkillCapabilitySelectionMode;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
import tech.easyflow.skill.mapper.SkillCapabilityBindingMapper;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.security.SkillCredentialValueGuard;
|
||||
import tech.easyflow.skill.security.SkillPortableTargetSanitizer;
|
||||
import tech.easyflow.skill.security.SkillSensitiveConfigSanitizer;
|
||||
import tech.easyflow.skill.validation.SkillValidationIssue;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
import tech.easyflow.system.enums.CategoryResourceType;
|
||||
import tech.easyflow.system.enums.ResourceAction;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Skill 能力绑定业务服务实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillCapabilityBindingServiceImpl
|
||||
extends ServiceImpl<SkillCapabilityBindingMapper, SkillCapabilityBinding>
|
||||
implements SkillCapabilityBindingService {
|
||||
|
||||
private static final Pattern RUNTIME_NAME_PATTERN = Pattern.compile("^[A-Za-z][A-Za-z0-9_-]{0,63}$");
|
||||
private static final Pattern MCP_TOOL_NAME_PATTERN = Pattern.compile("^[A-Za-z][A-Za-z0-9_.-]{0,127}$");
|
||||
private static final int MAX_BINDINGS = 200;
|
||||
private static final int MAX_SELECTED_TOOLS = 200;
|
||||
private static final int MAX_CONFIG_BYTES = 4096;
|
||||
|
||||
private final SkillMapper skillMapper;
|
||||
private final SkillCapabilityTargetAccessService targetAccessService;
|
||||
private final McpAccessPermissionChecker mcpAccessPermissionChecker;
|
||||
private final ResourceAccessService resourceAccessService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 创建 Skill 能力绑定服务。
|
||||
*
|
||||
* @param skillMapper Skill Mapper
|
||||
* @param targetAccessService 目标授权服务
|
||||
* @param mcpAccessPermissionChecker MCP 查询与使用权限检查器
|
||||
* @param resourceAccessService Skill 资源授权服务
|
||||
* @param objectMapper JSON 映射器
|
||||
*/
|
||||
public SkillCapabilityBindingServiceImpl(SkillMapper skillMapper,
|
||||
SkillCapabilityTargetAccessService targetAccessService,
|
||||
McpAccessPermissionChecker mcpAccessPermissionChecker,
|
||||
ResourceAccessService resourceAccessService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.skillMapper = skillMapper;
|
||||
this.targetAccessService = targetAccessService;
|
||||
this.mcpAccessPermissionChecker = mcpAccessPermissionChecker;
|
||||
this.resourceAccessService = resourceAccessService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<SkillCapabilityBinding> listBindings(BigInteger skillId) {
|
||||
return listBindings(skillId, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<SkillCapabilityBinding> listVisibleBindings(BigInteger skillId) {
|
||||
return listBindings(skillId, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询并填充绑定展示状态,可选按 MANAGE 权限移除内部目标标识。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param redactReadOnlyTargets 是否为只读调用方脱敏
|
||||
* @return 有序绑定列表
|
||||
*/
|
||||
private List<SkillCapabilityBinding> listBindings(BigInteger skillId, boolean redactReadOnlyTargets) {
|
||||
Skill skill = requireSkill(skillId);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill, ResourceAction.READ, "无权限查看 Skill 能力绑定");
|
||||
boolean manageable = !redactReadOnlyTargets
|
||||
|| resourceAccessService.canAccess(CategoryResourceType.SKILL, skill, ResourceAction.MANAGE);
|
||||
List<SkillCapabilityBinding> bindings = listRaw(skillId);
|
||||
for (SkillCapabilityBinding binding : bindings) {
|
||||
enrichDisplayStatus(binding);
|
||||
boolean targetPermissionDenied = "NO_PERMISSION".equals(binding.getTargetStatus());
|
||||
if (!manageable || targetPermissionDenied) {
|
||||
binding.setTargetId(null);
|
||||
if (targetPermissionDenied) {
|
||||
// Skill 管理权限不能替代目标能力权限;目标不可读时只保留可删除的绑定外壳。
|
||||
binding.setTargetLogicalRef(null);
|
||||
binding.setTargetName(null);
|
||||
binding.setSelectedToolNamesJson(List.of());
|
||||
binding.setResolvedToolNames(List.of());
|
||||
}
|
||||
}
|
||||
sanitizeBindingForExposure(binding);
|
||||
}
|
||||
return bindings;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<SkillCapabilityBinding> replaceBindings(BigInteger skillId, List<SkillCapabilityBinding> bindings) {
|
||||
return replaceBindingsInternal(skillId, bindings, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<SkillCapabilityBinding> replaceBindings(BigInteger skillId,
|
||||
List<SkillCapabilityBinding> bindings,
|
||||
String expectedCapabilityHash) {
|
||||
if (expectedCapabilityHash == null || !expectedCapabilityHash.matches("^[a-f0-9]{64}$")) {
|
||||
throw new BusinessException(409, 4093, "缺少或无效的能力配置版本,请重新加载后再保存");
|
||||
}
|
||||
return replaceBindingsInternal(skillId, bindings, expectedCapabilityHash);
|
||||
}
|
||||
|
||||
private List<SkillCapabilityBinding> replaceBindingsInternal(BigInteger skillId,
|
||||
List<SkillCapabilityBinding> bindings,
|
||||
String expectedCapabilityHash) {
|
||||
Skill skill = requireSkill(skillId, true);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill, ResourceAction.MANAGE, "无权限管理 Skill 能力绑定");
|
||||
if (expectedCapabilityHash != null && !expectedCapabilityHash.equals(skill.getCapabilityHash())) {
|
||||
throw new BusinessException(409, 4093, "能力配置已被其他操作更新,请重新加载后合并");
|
||||
}
|
||||
List<SkillCapabilityBinding> safeBindings = bindings == null ? new ArrayList<>() : new ArrayList<>(bindings);
|
||||
if (safeBindings.size() > MAX_BINDINGS) {
|
||||
throw new BusinessException("单个 Skill 最多绑定 " + MAX_BINDINGS + " 项能力");
|
||||
}
|
||||
SkillValidationResult validation = validateInternal(safeBindings, ValidationMode.SAVE);
|
||||
assertNoErrors(validation);
|
||||
|
||||
QueryWrapper deleteQuery = QueryWrapper.create()
|
||||
.eq(SkillCapabilityBinding::getTenantId, skill.getTenantId())
|
||||
.eq(SkillCapabilityBinding::getSkillId, skillId);
|
||||
long existingBindingCount = count(deleteQuery);
|
||||
if (existingBindingCount > 0 && getMapper().deleteByQuery(deleteQuery) != existingBindingCount) {
|
||||
throw new BusinessException(500, 500, "替换 Skill 能力绑定失败,请稍后重试");
|
||||
}
|
||||
LoginAccount account = requireAccount();
|
||||
Date now = new Date();
|
||||
for (int index = 0; index < safeBindings.size(); index++) {
|
||||
SkillCapabilityBinding binding = safeBindings.get(index);
|
||||
binding.setId(null);
|
||||
binding.setTenantId(skill.getTenantId());
|
||||
binding.setSkillId(skillId);
|
||||
binding.setSortNo(index);
|
||||
binding.setCreated(now);
|
||||
binding.setCreatedBy(account.getId());
|
||||
binding.setModified(now);
|
||||
binding.setModifiedBy(account.getId());
|
||||
}
|
||||
if (!safeBindings.isEmpty()) {
|
||||
if (!saveBatch(safeBindings)) {
|
||||
throw new BusinessException(500, 500, "保存 Skill 能力绑定失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
Skill update = new Skill();
|
||||
update.setId(skillId);
|
||||
update.setCapabilityCount(safeBindings.size());
|
||||
update.setCapabilityHash(calculateHash(safeBindings));
|
||||
update.setModified(now);
|
||||
update.setModifiedBy(account.getId());
|
||||
QueryWrapper updateQuery = QueryWrapper.create()
|
||||
.eq(Skill::getId, skillId)
|
||||
.eq(Skill::getTenantId, skill.getTenantId());
|
||||
if (expectedCapabilityHash != null) {
|
||||
updateQuery.eq(Skill::getCapabilityHash, expectedCapabilityHash);
|
||||
}
|
||||
if (skillMapper.updateByQuery(update, updateQuery) != 1) {
|
||||
if (expectedCapabilityHash != null) {
|
||||
throw new BusinessException(409, 4093, "能力配置已被其他操作更新,请重新加载后合并");
|
||||
}
|
||||
throw new BusinessException(500, 500, "更新 Skill 能力摘要失败,请稍后重试");
|
||||
}
|
||||
return listBindings(skillId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SkillValidationResult validateBindings(BigInteger skillId,
|
||||
List<SkillCapabilityBinding> bindings,
|
||||
boolean publishValidation) {
|
||||
Skill skill = requireSkill(skillId);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill,
|
||||
bindings == null ? ResourceAction.READ : ResourceAction.MANAGE,
|
||||
bindings == null ? "无权限校验 Skill 能力绑定" : "无权限校验待保存的 Skill 能力绑定");
|
||||
return validateInternal(bindings == null ? listRaw(skillId) : bindings,
|
||||
publishValidation ? ValidationMode.PUBLISH : ValidationMode.SAVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SkillValidationResult validateImportBindings(List<SkillCapabilityBinding> bindings) {
|
||||
return validateInternal(bindings == null ? List.of() : bindings, ValidationMode.IMPORT_PREVIEW);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<SkillCapabilityCandidate> listCandidates(SkillCapabilityType capabilityType, String keyword) {
|
||||
return targetAccessService.listCandidates(capabilityType, keyword);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SkillCapabilityCandidate getMcpTools(BigInteger targetId) {
|
||||
return targetAccessService.getMcpTools(targetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<Map<String, Object>> buildPublishSnapshot(BigInteger skillId) {
|
||||
List<SkillCapabilityBinding> bindings = listRaw(skillId);
|
||||
ValidatedBindings validated = validateInternalWithTargets(bindings, ValidationMode.PUBLISH);
|
||||
assertNoErrors(validated.result());
|
||||
List<Map<String, Object>> snapshots = new ArrayList<>();
|
||||
for (int index = 0; index < bindings.size(); index++) {
|
||||
SkillCapabilityBinding binding = bindings.get(index);
|
||||
SkillCapabilityType capabilityType = SkillCapabilityType.from(binding.getCapabilityType());
|
||||
SkillCapabilityTarget target = Boolean.TRUE.equals(binding.getEnabled())
|
||||
? validated.targetsByIndex().get(index) : null;
|
||||
Map<String, Object> snapshot = new LinkedHashMap<>();
|
||||
snapshot.put("capabilityType", binding.getCapabilityType());
|
||||
snapshot.put("runtimeName", binding.getRuntimeName());
|
||||
snapshot.put("enabled", binding.getEnabled());
|
||||
snapshot.put("selectionMode", binding.getSelectionMode());
|
||||
snapshot.put("selectedToolNames", binding.getSelectedToolNamesJson());
|
||||
snapshot.put("resolvedToolNames", binding.getResolvedToolNames());
|
||||
snapshot.put("executionMode", binding.getExecutionMode());
|
||||
snapshot.put("hitlEnabled", binding.getHitlEnabled());
|
||||
snapshot.put("hitlConfig", SkillSensitiveConfigSanitizer.sanitizeHitl(binding.getHitlConfigJson()));
|
||||
snapshot.put("options", SkillSensitiveConfigSanitizer.sanitizeOptions(binding.getOptionsJson()));
|
||||
snapshot.put("sortNo", binding.getSortNo());
|
||||
if (target != null) {
|
||||
String targetName = SkillPortableTargetSanitizer.safePortableMetadataOrNull(target.getName());
|
||||
String targetRevision = SkillPortableTargetSanitizer.safePortableMetadataOrNull(target.getRevision());
|
||||
if (targetName != null) {
|
||||
snapshot.put("targetName", targetName);
|
||||
}
|
||||
snapshot.put("targetLogicalRef", SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
capabilityType, target.getLogicalRef()));
|
||||
if (targetRevision != null) {
|
||||
snapshot.put("targetRevision", targetRevision);
|
||||
}
|
||||
} else {
|
||||
snapshot.put("targetLogicalRef", SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
capabilityType, binding.getTargetLogicalRef()));
|
||||
}
|
||||
assertCredentialFreeSnapshot(snapshot);
|
||||
snapshots.add(snapshot);
|
||||
}
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public String calculateHash(List<SkillCapabilityBinding> bindings) {
|
||||
List<Map<String, Object>> canonical = new ArrayList<>();
|
||||
if (bindings != null) {
|
||||
bindings.stream().sorted((left, right) -> Integer.compare(
|
||||
left.getSortNo() == null ? 0 : left.getSortNo(),
|
||||
right.getSortNo() == null ? 0 : right.getSortNo()))
|
||||
.forEach(binding -> {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("type", binding.getCapabilityType());
|
||||
item.put("targetId", binding.getTargetId() == null ? null : binding.getTargetId().toString());
|
||||
item.put("targetLogicalRef", binding.getTargetLogicalRef());
|
||||
item.put("runtimeName", binding.getRuntimeName());
|
||||
item.put("enabled", binding.getEnabled());
|
||||
item.put("selectionMode", binding.getSelectionMode());
|
||||
item.put("selectedTools", binding.getSelectedToolNamesJson());
|
||||
item.put("executionMode", binding.getExecutionMode());
|
||||
item.put("hitlEnabled", binding.getHitlEnabled());
|
||||
item.put("hitlConfig", SkillSensitiveConfigSanitizer.sanitizeHitl(binding.getHitlConfigJson()));
|
||||
item.put("options", SkillSensitiveConfigSanitizer.sanitizeOptions(binding.getOptionsJson()));
|
||||
canonical.add(item);
|
||||
});
|
||||
}
|
||||
try {
|
||||
return SkillHashes.sha256Hex(objectMapper.writeValueAsString(canonicalize(canonical))
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new BusinessException(500, 500, "计算 Skill 能力配置 hash 失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public String calculateStoredHash(BigInteger skillId) {
|
||||
Skill skill = requireSkill(skillId);
|
||||
resourceAccessService.assertAccess(
|
||||
CategoryResourceType.SKILL, skill, ResourceAction.READ, "无权限读取 Skill 能力摘要");
|
||||
return calculateHash(listRaw(skillId));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void removeBySkillId(BigInteger skillId) {
|
||||
if (skillId != null) {
|
||||
QueryWrapper deleteQuery = QueryWrapper.create()
|
||||
.eq(SkillCapabilityBinding::getTenantId, requireAccount().getTenantId())
|
||||
.eq(SkillCapabilityBinding::getSkillId, skillId);
|
||||
long existingBindingCount = count(deleteQuery);
|
||||
if (existingBindingCount > 0 && getMapper().deleteByQuery(deleteQuery) != existingBindingCount) {
|
||||
throw new BusinessException(500, 500, "删除 Skill 能力绑定失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SkillValidationResult validateInternal(List<SkillCapabilityBinding> bindings, ValidationMode mode) {
|
||||
return validateInternalWithTargets(bindings, mode).result();
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验能力绑定并保留本次调用已授权的目标摘要,供发布快照复用。
|
||||
*
|
||||
* @param bindings 能力绑定
|
||||
* @param mode 校验场景
|
||||
* @return 校验结果与按绑定序号记录的目标摘要
|
||||
*/
|
||||
private ValidatedBindings validateInternalWithTargets(List<SkillCapabilityBinding> bindings,
|
||||
ValidationMode mode) {
|
||||
assertMcpAccessWhenPresent(bindings);
|
||||
List<SkillValidationIssue> issues = new ArrayList<>();
|
||||
if (bindings.size() > MAX_BINDINGS) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_BINDING_LIMIT",
|
||||
"单个 Skill 最多绑定 " + MAX_BINDINGS + " 项能力", "capabilities"));
|
||||
SkillValidationResult result = new SkillValidationResult();
|
||||
result.setIssues(issues);
|
||||
result.setValid(false);
|
||||
return new ValidatedBindings(result, Map.of());
|
||||
}
|
||||
Set<String> runtimeNames = new HashSet<>();
|
||||
Map<TargetCacheKey, SkillCapabilityTarget> targetCache = new HashMap<>();
|
||||
Map<Integer, SkillCapabilityTarget> targetsByIndex = new HashMap<>();
|
||||
for (int index = 0; index < bindings.size(); index++) {
|
||||
validateOne(bindings.get(index), index, mode, runtimeNames, targetCache, targetsByIndex, issues);
|
||||
}
|
||||
SkillValidationResult result = new SkillValidationResult();
|
||||
result.setIssues(issues);
|
||||
result.setValid(issues.stream().noneMatch(issue -> "ERROR".equals(issue.getSeverity())));
|
||||
return new ValidatedBindings(result, targetsByIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当配置中出现 MCP 能力时校验当前操作者的 MCP 查询与使用权限。
|
||||
*
|
||||
* <p>该检查先于目标映射执行,因此禁用或尚未映射的 MCP 绑定也不能绕过授权。</p>
|
||||
*
|
||||
* @param bindings 待校验能力绑定
|
||||
*/
|
||||
private void assertMcpAccessWhenPresent(List<SkillCapabilityBinding> bindings) {
|
||||
boolean containsMcp = bindings.stream()
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.map(SkillCapabilityBinding::getCapabilityType)
|
||||
.anyMatch(type -> type != null && SkillCapabilityType.MCP.name().equalsIgnoreCase(type.trim()));
|
||||
if (containsMcp) {
|
||||
mcpAccessPermissionChecker.assertCanUseMcp();
|
||||
}
|
||||
}
|
||||
|
||||
private void validateOne(SkillCapabilityBinding binding,
|
||||
int index,
|
||||
ValidationMode mode,
|
||||
Set<String> runtimeNames,
|
||||
Map<TargetCacheKey, SkillCapabilityTarget> targetCache,
|
||||
Map<Integer, SkillCapabilityTarget> targetsByIndex,
|
||||
List<SkillValidationIssue> issues) {
|
||||
String path = "capabilities[" + index + "]";
|
||||
if (binding == null) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_EMPTY", "能力绑定不能为空", path));
|
||||
return;
|
||||
}
|
||||
validateCredentialFields(binding, path, issues);
|
||||
SkillCapabilityType type;
|
||||
try {
|
||||
type = SkillCapabilityType.from(binding.getCapabilityType());
|
||||
binding.setCapabilityType(type.name());
|
||||
} catch (BusinessException exception) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_TYPE_INVALID",
|
||||
"能力类型不受支持", path + ".capabilityType"));
|
||||
return;
|
||||
}
|
||||
boolean enabled = binding.getEnabled() == null || binding.getEnabled();
|
||||
binding.setEnabled(enabled);
|
||||
binding.setHitlEnabled(Boolean.TRUE.equals(binding.getHitlEnabled()));
|
||||
validateSafeConfigs(binding, path, issues);
|
||||
if (binding.getRuntimeName() == null || !RUNTIME_NAME_PATTERN.matcher(binding.getRuntimeName()).matches()) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "RUNTIME_NAME_INVALID",
|
||||
"运行时名称必须以字母开头,且只包含字母、数字、下划线或连字符,最长 64 个字符",
|
||||
path + ".runtimeName"));
|
||||
}
|
||||
validateStaticTypeConfiguration(binding, type, enabled, path, issues);
|
||||
if (binding.getTargetId() == null) {
|
||||
if (!SkillPortableTargetSanitizer.isSafeLogicalRef(type, binding.getTargetLogicalRef())) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "TARGET_LOGICAL_REF_INVALID",
|
||||
"未映射能力的目标逻辑引用格式不正确", path + ".targetLogicalRef"));
|
||||
}
|
||||
if (mode.allowUnresolvedTarget()) {
|
||||
validateRuntimeNamesWithoutTarget(binding, type, enabled, path, runtimeNames, issues);
|
||||
} else {
|
||||
issues.add(SkillValidationIssue.of(enabled ? "ERROR" : "WARNING", "TARGET_UNRESOLVED",
|
||||
enabled ? "启用的能力必须映射目标资源" : "能力尚未映射目标资源,保持禁用后可保存",
|
||||
path + ".targetId"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (binding.getTargetLogicalRef() != null && binding.getTargetLogicalRef().length() > 512) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "TARGET_LOGICAL_REF_INVALID",
|
||||
"目标逻辑引用不能超过 512 个字符", path + ".targetLogicalRef"));
|
||||
}
|
||||
SkillCapabilityTarget target;
|
||||
try {
|
||||
boolean resolveMcpTools = mode.publishValidation() && enabled && type == SkillCapabilityType.MCP;
|
||||
TargetCacheKey cacheKey = new TargetCacheKey(type, binding.getTargetId(), resolveMcpTools);
|
||||
target = targetCache.get(cacheKey);
|
||||
if (target == null) {
|
||||
target = targetAccessService.requireUsableTarget(binding, resolveMcpTools);
|
||||
targetCache.put(cacheKey, target);
|
||||
}
|
||||
} catch (BusinessException exception) {
|
||||
boolean permissionError = exception.getHttpStatus() == 403;
|
||||
issues.add(SkillValidationIssue.of(permissionError || enabled ? "ERROR" : "WARNING",
|
||||
permissionError ? "TARGET_NO_PERMISSION" : "TARGET_UNAVAILABLE",
|
||||
permissionError ? "当前用户无权使用目标能力" : "目标能力当前不可用",
|
||||
path + ".targetId"));
|
||||
return;
|
||||
}
|
||||
targetsByIndex.put(index, target);
|
||||
validateResolvedTargetCredentials(target, path, issues);
|
||||
binding.setTargetName(target.getName());
|
||||
binding.setTargetStatus(target.getStatus());
|
||||
binding.setTargetLogicalRef(target.getLogicalRef());
|
||||
if (type == SkillCapabilityType.MCP) {
|
||||
validateMcp(binding, target, enabled, mode.publishValidation(), path, runtimeNames, issues);
|
||||
} else {
|
||||
if (enabled && binding.getRuntimeName() != null
|
||||
&& !runtimeNames.add(binding.getRuntimeName().toLowerCase(Locale.ROOT))) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "RUNTIME_NAME_DUPLICATE",
|
||||
"最终运行时工具名重复", path + ".runtimeName"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验能力绑定所有持久化字符串面不含认证凭据。
|
||||
*
|
||||
* @param binding 能力绑定
|
||||
* @param path 能力绑定路径
|
||||
* @param issues 问题集合
|
||||
*/
|
||||
private void validateCredentialFields(SkillCapabilityBinding binding,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
validateCredentialValue(binding.getCapabilityType(), path + ".capabilityType", issues);
|
||||
validateCredentialValue(binding.getTargetLogicalRef(), path + ".targetLogicalRef", issues);
|
||||
validateCredentialValue(binding.getRuntimeName(), path + ".runtimeName", issues);
|
||||
validateCredentialValue(binding.getSelectionMode(), path + ".selectionMode", issues);
|
||||
validateCredentialValue(binding.getExecutionMode(), path + ".executionMode", issues);
|
||||
List<String> selectedTools = binding.getSelectedToolNamesJson() == null
|
||||
? List.of() : binding.getSelectedToolNamesJson();
|
||||
for (int index = 0; index < selectedTools.size(); index++) {
|
||||
validateCredentialValue(selectedTools.get(index),
|
||||
path + ".selectedToolNamesJson[" + index + "]", issues);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单个字符串中的凭据问题转换为稳定、无回显的校验结果。
|
||||
*
|
||||
* @param value 字符串值
|
||||
* @param path 字段路径
|
||||
* @param issues 问题集合
|
||||
*/
|
||||
private void validateCredentialValue(String value,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
if (SkillCredentialValueGuard.containsCredential(value)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "SENSITIVE_VALUE_DETECTED",
|
||||
"能力配置不能包含认证凭据,请改用运行环境中的安全配置", path));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验目标解析结果中会进入发布快照的字符串字段。
|
||||
*
|
||||
* @param target 已授权目标摘要
|
||||
* @param path 能力绑定路径
|
||||
* @param issues 问题集合
|
||||
*/
|
||||
private void validateResolvedTargetCredentials(SkillCapabilityTarget target,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
// 展示元数据与逻辑引用在快照构造时采用 fail-closed 降级;工具名会直接成为运行时名称,必须阻断。
|
||||
List<String> tools = target.getToolNames() == null ? List.of() : target.getToolNames();
|
||||
for (int index = 0; index < tools.size(); index++) {
|
||||
validateCredentialValue(tools.get(index), path + ".resolvedToolNames[" + index + "]", issues);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对最终快照执行纵深凭据检查,防止未来新增字符串字段遗漏显式校验。
|
||||
*
|
||||
* @param snapshot 单项发布快照
|
||||
*/
|
||||
private void assertCredentialFreeSnapshot(Object snapshot) {
|
||||
if (snapshot instanceof String text) {
|
||||
if (SkillCredentialValueGuard.containsCredential(text)) {
|
||||
throw new BusinessException("Skill 能力发布快照包含不安全配置");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (snapshot instanceof Map<?, ?> map) {
|
||||
map.values().forEach(this::assertCredentialFreeSnapshot);
|
||||
return;
|
||||
}
|
||||
if (snapshot instanceof List<?> list) {
|
||||
list.forEach(this::assertCredentialFreeSnapshot);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在目标尚未映射时校验可由 manifest 独立确定的最终运行时名称。
|
||||
*
|
||||
* @param binding 能力绑定
|
||||
* @param type 能力类型
|
||||
* @param enabled 是否启用
|
||||
* @param path 问题路径
|
||||
* @param runtimeNames 已占用的运行时名称
|
||||
* @param issues 问题集合
|
||||
*/
|
||||
private void validateRuntimeNamesWithoutTarget(SkillCapabilityBinding binding,
|
||||
SkillCapabilityType type,
|
||||
boolean enabled,
|
||||
String path,
|
||||
Set<String> runtimeNames,
|
||||
List<SkillValidationIssue> issues) {
|
||||
if (type == SkillCapabilityType.MCP) {
|
||||
validateMcp(binding, null, enabled, false, path, runtimeNames, issues);
|
||||
return;
|
||||
}
|
||||
if (enabled && binding.getRuntimeName() != null
|
||||
&& !runtimeNames.add(binding.getRuntimeName().toLowerCase(Locale.ROOT))) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "RUNTIME_NAME_DUPLICATE",
|
||||
"最终运行时工具名重复", path + ".runtimeName"));
|
||||
}
|
||||
}
|
||||
|
||||
private void validateMcp(SkillCapabilityBinding binding,
|
||||
SkillCapabilityTarget target,
|
||||
boolean enabled,
|
||||
boolean publishValidation,
|
||||
String path,
|
||||
Set<String> runtimeNames,
|
||||
List<SkillValidationIssue> issues) {
|
||||
SkillCapabilitySelectionMode mode = SkillCapabilitySelectionMode.fromOrDefault(binding.getSelectionMode());
|
||||
List<String> selected = binding.getSelectedToolNamesJson();
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
List<String> available = target == null ? List.of() : target.getToolNames();
|
||||
List<String> resolved;
|
||||
if (mode == SkillCapabilitySelectionMode.SELECTED) {
|
||||
resolved = selected;
|
||||
} else if (publishValidation) {
|
||||
resolved = available;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (resolved.isEmpty()) {
|
||||
if (mode == SkillCapabilitySelectionMode.SELECTED) {
|
||||
// SELECTED 空清单已经由静态配置校验给出精确问题,避免重复且含混的发布错误。
|
||||
return;
|
||||
}
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_TOOLS_EMPTY", "MCP 当前没有可发布的工具",
|
||||
path + ".selectedToolNamesJson"));
|
||||
return;
|
||||
}
|
||||
if (publishValidation && mode == SkillCapabilitySelectionMode.SELECTED && !available.containsAll(selected)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_TOOL_MISSING",
|
||||
"部分已选择的 MCP 工具已不存在,请重新选择", path + ".selectedToolNamesJson"));
|
||||
return;
|
||||
}
|
||||
binding.setResolvedToolNames(resolved);
|
||||
for (String toolName : resolved) {
|
||||
String finalName = binding.getRuntimeName() + "_" + toolName;
|
||||
if (finalName.length() > 128 || !Pattern.matches("^[A-Za-z][A-Za-z0-9_.-]{0,127}$", finalName)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_RUNTIME_NAME_INVALID",
|
||||
"MCP 最终工具名不符合平台命名规则", path + ".runtimeName"));
|
||||
continue;
|
||||
}
|
||||
if (!runtimeNames.add(finalName.toLowerCase(Locale.ROOT))) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "RUNTIME_NAME_DUPLICATE",
|
||||
"最终运行时工具名重复", path + ".runtimeName"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateStaticTypeConfiguration(SkillCapabilityBinding binding,
|
||||
SkillCapabilityType type,
|
||||
boolean enabled,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
if (type != SkillCapabilityType.MCP) {
|
||||
if (binding.getSelectionMode() != null && !binding.getSelectionMode().isBlank()) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_SELECTION_MODE_NOT_ALLOWED",
|
||||
"工作流或插件能力不能配置 MCP 工具选择模式", path + ".selectionMode"));
|
||||
}
|
||||
if (binding.getSelectedToolNamesJson() != null && !binding.getSelectedToolNamesJson().isEmpty()) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_TOOL_SELECTION_NOT_ALLOWED",
|
||||
"工作流或插件能力不能配置 MCP 工具清单", path + ".selectedToolNamesJson"));
|
||||
}
|
||||
try {
|
||||
binding.setExecutionMode(SkillCapabilityExecutionMode.fromOrDefault(binding.getExecutionMode()).name());
|
||||
} catch (BusinessException exception) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "EXECUTION_MODE_INVALID",
|
||||
"能力执行模式不受支持", path + ".executionMode"));
|
||||
binding.setExecutionMode(SkillCapabilityExecutionMode.SYNC.name());
|
||||
}
|
||||
binding.setSelectionMode(null);
|
||||
binding.setSelectedToolNamesJson(List.of());
|
||||
return;
|
||||
}
|
||||
if (binding.getExecutionMode() != null && !binding.getExecutionMode().isBlank()) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_EXECUTION_MODE_NOT_ALLOWED",
|
||||
"MCP 能力不能配置工作流或插件执行模式", path + ".executionMode"));
|
||||
}
|
||||
binding.setExecutionMode(null);
|
||||
SkillCapabilitySelectionMode mode;
|
||||
try {
|
||||
mode = SkillCapabilitySelectionMode.fromOrDefault(binding.getSelectionMode());
|
||||
} catch (BusinessException exception) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_SELECTION_MODE_INVALID",
|
||||
"MCP 工具选择模式不受支持", path + ".selectionMode"));
|
||||
mode = SkillCapabilitySelectionMode.ALL;
|
||||
}
|
||||
binding.setSelectionMode(mode.name());
|
||||
List<String> requested = binding.getSelectedToolNamesJson() == null
|
||||
? List.of() : binding.getSelectedToolNamesJson();
|
||||
if (requested.size() > MAX_SELECTED_TOOLS) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_TOOL_SELECTION_LIMIT",
|
||||
"MCP 最多选择 " + MAX_SELECTED_TOOLS + " 个工具", path + ".selectedToolNamesJson"));
|
||||
}
|
||||
Set<String> validTools = new LinkedHashSet<>();
|
||||
for (int toolIndex = 0; toolIndex < requested.size(); toolIndex++) {
|
||||
String tool = requested.get(toolIndex);
|
||||
if (tool == null || !MCP_TOOL_NAME_PATTERN.matcher(tool).matches()) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "MCP_TOOL_NAME_INVALID",
|
||||
"MCP 工具名不符合平台命名规则",
|
||||
path + ".selectedToolNamesJson[" + toolIndex + "]"));
|
||||
} else {
|
||||
validTools.add(tool);
|
||||
}
|
||||
}
|
||||
List<String> selected = new ArrayList<>(validTools);
|
||||
selected.sort(String::compareTo);
|
||||
binding.setSelectedToolNamesJson(selected);
|
||||
if (mode == SkillCapabilitySelectionMode.SELECTED && selected.isEmpty()) {
|
||||
issues.add(SkillValidationIssue.of(enabled ? "ERROR" : "WARNING", "MCP_TOOL_SELECTION_EMPTY",
|
||||
"MCP SELECTED 模式至少选择一个工具", path + ".selectedToolNamesJson"));
|
||||
}
|
||||
}
|
||||
|
||||
private void validateSafeConfigs(SkillCapabilityBinding binding,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
Map<String, Object> originalHitl = binding.getHitlConfigJson() == null
|
||||
? Map.of() : binding.getHitlConfigJson();
|
||||
Map<String, Object> originalOptions = binding.getOptionsJson() == null
|
||||
? Map.of() : binding.getOptionsJson();
|
||||
Map<String, Object> safeHitl = SkillSensitiveConfigSanitizer.sanitizeHitl(binding.getHitlConfigJson());
|
||||
Map<String, Object> safeOptions = SkillSensitiveConfigSanitizer.sanitizeOptions(binding.getOptionsJson());
|
||||
if (!safeHitl.equals(originalHitl)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "HITL_CONFIG_UNSAFE",
|
||||
"HITL 配置包含未允许字段或复杂值", path + ".hitlConfigJson"));
|
||||
}
|
||||
if (!safeOptions.equals(originalOptions)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_OPTIONS_UNSAFE",
|
||||
"能力选项包含未允许字段或复杂值", path + ".optionsJson"));
|
||||
}
|
||||
try {
|
||||
if (objectMapper.writeValueAsBytes(safeHitl).length > MAX_CONFIG_BYTES
|
||||
|| objectMapper.writeValueAsBytes(safeOptions).length > MAX_CONFIG_BYTES) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_CONFIG_TOO_LARGE",
|
||||
"能力配置不能超过 4 KiB", path));
|
||||
}
|
||||
} catch (JsonProcessingException exception) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_CONFIG_INVALID",
|
||||
"能力配置无法序列化", path));
|
||||
}
|
||||
binding.setHitlConfigJson(safeHitl);
|
||||
binding.setOptionsJson(safeOptions);
|
||||
validateSafeConfigValues(safeHitl, safeOptions, path, issues);
|
||||
}
|
||||
|
||||
private void validateSafeConfigValues(Map<String, Object> hitl,
|
||||
Map<String, Object> options,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
for (Map.Entry<String, Object> entry : hitl.entrySet()) {
|
||||
int maxLength = "confirmLabel".equals(entry.getKey()) || "cancelLabel".equals(entry.getKey())
|
||||
? 128 : 2_000;
|
||||
if (!(entry.getValue() instanceof String text) || text.length() > maxLength) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "HITL_CONFIG_VALUE_INVALID",
|
||||
"HITL 配置字段类型或长度不正确:" + entry.getKey(), path + ".hitlConfigJson." + entry.getKey()));
|
||||
} else if (SkillCredentialValueGuard.containsCredential(text)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "SENSITIVE_VALUE_DETECTED",
|
||||
"HITL 配置不能包含认证凭据,请改用运行环境中的安全配置",
|
||||
path + ".hitlConfigJson." + entry.getKey()));
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, Object> entry : options.entrySet()) {
|
||||
if (entry.getValue() instanceof String text) {
|
||||
validateCredentialValue(text, path + ".optionsJson." + entry.getKey(), issues);
|
||||
}
|
||||
}
|
||||
validateIntegerOption(options, "timeoutMs", 100, 300_000, path, issues);
|
||||
validateIntegerOption(options, "retryCount", 0, 10, path, issues);
|
||||
for (String key : List.of("async", "readOnly")) {
|
||||
if (options.containsKey(key) && !(options.get(key) instanceof Boolean)) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_OPTION_VALUE_INVALID",
|
||||
"能力选项必须为布尔值:" + key, path + ".optionsJson." + key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateIntegerOption(Map<String, Object> options,
|
||||
String key,
|
||||
int minimum,
|
||||
int maximum,
|
||||
String path,
|
||||
List<SkillValidationIssue> issues) {
|
||||
if (!options.containsKey(key)) {
|
||||
return;
|
||||
}
|
||||
Object value = options.get(key);
|
||||
boolean valid = value instanceof Number number
|
||||
&& number.doubleValue() == number.longValue()
|
||||
&& number.longValue() >= minimum
|
||||
&& number.longValue() <= maximum;
|
||||
if (!valid) {
|
||||
issues.add(SkillValidationIssue.of("ERROR", "CAPABILITY_OPTION_VALUE_INVALID",
|
||||
"能力选项数值超出范围:" + key, path + ".optionsJson." + key));
|
||||
}
|
||||
}
|
||||
|
||||
private void enrichDisplayStatus(SkillCapabilityBinding binding) {
|
||||
if (binding.getTargetId() == null) {
|
||||
binding.setTargetStatus("UNRESOLVED");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
SkillCapabilityTarget target = targetAccessService.requireUsableTarget(binding, false);
|
||||
binding.setTargetName(target.getName());
|
||||
binding.setTargetStatus("AVAILABLE");
|
||||
} catch (BusinessException exception) {
|
||||
boolean permissionDenied = exception.getHttpStatus() == 403;
|
||||
binding.setTargetStatus(permissionDenied ? "NO_PERMISSION" : "UNAVAILABLE");
|
||||
if (permissionDenied) {
|
||||
// 目标不可读时不能沿用调用前对象中可能存在的展示残留。
|
||||
binding.setTargetName(null);
|
||||
binding.setResolvedToolNames(List.of());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对读取出的历史能力配置执行展示边界脱敏,防止遗留脏数据通过列表或详情接口回显。
|
||||
*
|
||||
* @param binding 待读取能力绑定
|
||||
*/
|
||||
private void sanitizeBindingForExposure(SkillCapabilityBinding binding) {
|
||||
binding.setCapabilityType(safeNonCredentialOrNull(binding.getCapabilityType()));
|
||||
binding.setTargetLogicalRef(safeNonCredentialOrNull(binding.getTargetLogicalRef()));
|
||||
binding.setRuntimeName(safeNonCredentialOrNull(binding.getRuntimeName()));
|
||||
binding.setSelectionMode(safeNonCredentialOrNull(binding.getSelectionMode()));
|
||||
binding.setExecutionMode(safeNonCredentialOrNull(binding.getExecutionMode()));
|
||||
binding.setTargetName(SkillPortableTargetSanitizer.safePortableMetadataOrNull(binding.getTargetName()));
|
||||
binding.setTargetStatus(safeNonCredentialOrNull(binding.getTargetStatus()));
|
||||
binding.setSelectedToolNamesJson(sanitizeToolNamesForExposure(binding.getSelectedToolNamesJson()));
|
||||
binding.setResolvedToolNames(sanitizeToolNamesForExposure(binding.getResolvedToolNames()));
|
||||
|
||||
Map<String, Object> hitl = SkillSensitiveConfigSanitizer.sanitizeHitl(binding.getHitlConfigJson());
|
||||
hitl.entrySet().removeIf(entry -> !(entry.getValue() instanceof String text)
|
||||
|| SkillCredentialValueGuard.containsCredential(text));
|
||||
binding.setHitlConfigJson(hitl);
|
||||
|
||||
Map<String, Object> options = SkillSensitiveConfigSanitizer.sanitizeOptions(binding.getOptionsJson());
|
||||
options.entrySet().removeIf(entry -> !isSafeOptionForExposure(entry.getKey(), entry.getValue()));
|
||||
binding.setOptionsJson(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤历史工具名中的异常或凭据式值。
|
||||
*
|
||||
* @param values 原始工具名
|
||||
* @return 可安全展示的工具名
|
||||
*/
|
||||
private List<String> sanitizeToolNamesForExposure(List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return values.stream()
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.filter(value -> MCP_TOOL_NAME_PATTERN.matcher(value).matches())
|
||||
.filter(value -> !SkillCredentialValueGuard.containsCredential(value))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断能力选项是否符合公开返回的严格类型和值域。
|
||||
*
|
||||
* @param key 选项键
|
||||
* @param value 选项值
|
||||
* @return 可安全展示时为 true
|
||||
*/
|
||||
private boolean isSafeOptionForExposure(String key, Object value) {
|
||||
if (("async".equals(key) || "readOnly".equals(key))) {
|
||||
return value instanceof Boolean;
|
||||
}
|
||||
if (!(value instanceof Number number)
|
||||
|| number.doubleValue() != number.longValue()) {
|
||||
return false;
|
||||
}
|
||||
long numeric = number.longValue();
|
||||
if ("timeoutMs".equals(key)) {
|
||||
return numeric >= 100 && numeric <= 300_000;
|
||||
}
|
||||
return "retryCount".equals(key) && numeric >= 0 && numeric <= 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回不含凭据的字符串;敏感或空白值统一移除。
|
||||
*
|
||||
* @param value 原始字符串
|
||||
* @return 可安全返回的值
|
||||
*/
|
||||
private String safeNonCredentialOrNull(String value) {
|
||||
return value == null || value.isBlank() || SkillCredentialValueGuard.containsCredential(value)
|
||||
? null : value;
|
||||
}
|
||||
|
||||
private List<SkillCapabilityBinding> listRaw(BigInteger skillId) {
|
||||
return list(QueryWrapper.create()
|
||||
.eq(SkillCapabilityBinding::getTenantId, requireAccount().getTenantId())
|
||||
.eq(SkillCapabilityBinding::getSkillId, skillId)
|
||||
.orderBy("sort_no asc, id asc"));
|
||||
}
|
||||
|
||||
private Skill requireSkill(BigInteger skillId) {
|
||||
return requireSkill(skillId, false);
|
||||
}
|
||||
|
||||
private Skill requireSkill(BigInteger skillId, boolean forUpdate) {
|
||||
if (skillId == null) {
|
||||
throw new BusinessException("Skill ID 不能为空");
|
||||
}
|
||||
LoginAccount account = requireAccount();
|
||||
QueryWrapper query = QueryWrapper.create()
|
||||
.eq(Skill::getId, skillId)
|
||||
.eq(Skill::getTenantId, account.getTenantId());
|
||||
if (forUpdate) {
|
||||
query.forUpdate();
|
||||
}
|
||||
Skill skill = skillMapper.selectOneByQuery(query);
|
||||
if (skill == null) {
|
||||
throw new BusinessException(404, 404, "Skill 不存在");
|
||||
}
|
||||
return skill;
|
||||
}
|
||||
|
||||
private LoginAccount requireAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
private void assertNoErrors(SkillValidationResult result) {
|
||||
result.getIssues().stream().filter(issue -> "ERROR".equals(issue.getSeverity())).findFirst()
|
||||
.ifPresent(issue -> {
|
||||
if ("TARGET_NO_PERMISSION".equals(issue.getCode())) {
|
||||
throw new BusinessException(403, 403, issue.getMessage());
|
||||
}
|
||||
throw new BusinessException(issue.getMessage());
|
||||
});
|
||||
}
|
||||
|
||||
private Object canonicalize(Object value) {
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
Map<String, Object> sorted = new java.util.TreeMap<>();
|
||||
map.forEach((key, item) -> sorted.put(String.valueOf(key), canonicalize(item)));
|
||||
return sorted;
|
||||
}
|
||||
if (value instanceof List<?> list) {
|
||||
return list.stream().map(this::canonicalize).toList();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 能力绑定校验场景。
|
||||
*
|
||||
* @param publishValidation 是否执行发布级 MCP 工具解析
|
||||
* @param allowUnresolvedTarget 是否允许目标留待导入映射处理
|
||||
*/
|
||||
private record ValidationMode(boolean publishValidation, boolean allowUnresolvedTarget) {
|
||||
|
||||
private static final ValidationMode SAVE = new ValidationMode(false, false);
|
||||
private static final ValidationMode PUBLISH = new ValidationMode(true, false);
|
||||
private static final ValidationMode IMPORT_PREVIEW = new ValidationMode(false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单次校验内目标查询的稳定缓存键。
|
||||
*
|
||||
* @param type 能力类型
|
||||
* @param targetId 目标 ID
|
||||
* @param resolveMcpTools 是否解析 MCP 工具清单
|
||||
*/
|
||||
private record TargetCacheKey(SkillCapabilityType type,
|
||||
BigInteger targetId,
|
||||
boolean resolveMcpTools) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验结果及其已授权目标摘要。
|
||||
*
|
||||
* @param result 结构化校验结果
|
||||
* @param targetsByIndex 按绑定序号记录的目标摘要
|
||||
*/
|
||||
private record ValidatedBindings(SkillValidationResult result,
|
||||
Map<Integer, SkillCapabilityTarget> targetsByIndex) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 当前操作者可绑定的能力候选项。
|
||||
*/
|
||||
public class SkillCapabilityCandidate {
|
||||
|
||||
private String capabilityType;
|
||||
private BigInteger targetId;
|
||||
private String name;
|
||||
private String description;
|
||||
private String logicalRef;
|
||||
private String revision;
|
||||
private String status;
|
||||
private List<String> toolNames = new ArrayList<>();
|
||||
|
||||
public String getCapabilityType() { return capabilityType; }
|
||||
public void setCapabilityType(String capabilityType) { this.capabilityType = capabilityType; }
|
||||
public BigInteger getTargetId() { return targetId; }
|
||||
public void setTargetId(BigInteger targetId) { this.targetId = targetId; }
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
public String getLogicalRef() { return logicalRef; }
|
||||
public void setLogicalRef(String logicalRef) { this.logicalRef = logicalRef; }
|
||||
public String getRevision() { return revision; }
|
||||
public void setRevision(String revision) { this.revision = revision; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public List<String> getToolNames() { return toolNames; }
|
||||
public void setToolNames(List<String> toolNames) { this.toolNames = toolNames == null ? new ArrayList<>() : new ArrayList<>(toolNames); }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 已授权能力目标的安全解析结果。
|
||||
*/
|
||||
public class SkillCapabilityTarget {
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
private String logicalRef;
|
||||
private String revision;
|
||||
private String status;
|
||||
private List<String> toolNames = new ArrayList<>();
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
public String getLogicalRef() { return logicalRef; }
|
||||
public void setLogicalRef(String logicalRef) { this.logicalRef = logicalRef; }
|
||||
public String getRevision() { return revision; }
|
||||
public void setRevision(String revision) { this.revision = revision; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public List<String> getToolNames() { return toolNames; }
|
||||
public void setToolNames(List<String> toolNames) { this.toolNames = toolNames == null ? new ArrayList<>() : new ArrayList<>(toolNames); }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 能力目标的统一授权与安全摘要服务。
|
||||
*/
|
||||
public interface SkillCapabilityTargetAccessService {
|
||||
|
||||
/**
|
||||
* 解析并校验一个能力绑定目标。
|
||||
*
|
||||
* @param binding 能力绑定
|
||||
* @param resolveMcpTools 是否实时解析 MCP 工具
|
||||
* @return 不含凭据的目标摘要
|
||||
*/
|
||||
SkillCapabilityTarget requireUsableTarget(SkillCapabilityBinding binding, boolean resolveMcpTools);
|
||||
|
||||
/**
|
||||
* 查询当前操作者可绑定的目标。
|
||||
*
|
||||
* @param capabilityType 能力类型
|
||||
* @param keyword 关键词
|
||||
* @return 可绑定目标
|
||||
*/
|
||||
List<SkillCapabilityCandidate> listCandidates(SkillCapabilityType capabilityType, String keyword);
|
||||
|
||||
/**
|
||||
* 按逻辑引用尝试解析当前环境目标。
|
||||
*
|
||||
* @param capabilityType 能力类型
|
||||
* @param logicalRef 逻辑引用
|
||||
* @return 当前用户有权使用的目标 ID,未匹配时为空
|
||||
*/
|
||||
BigInteger resolveLogicalRef(SkillCapabilityType capabilityType, String logicalRef);
|
||||
|
||||
/**
|
||||
* 按需解析一个已授权 MCP 的工具清单。
|
||||
*
|
||||
* @param targetId MCP ID
|
||||
* @return MCP 候选详情及工具名
|
||||
*/
|
||||
SkillCapabilityCandidate getMcpTools(BigInteger targetId);
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import io.modelcontextprotocol.spec.McpSchema;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.ai.entity.Mcp;
|
||||
import tech.easyflow.ai.entity.Plugin;
|
||||
import tech.easyflow.ai.entity.PluginItem;
|
||||
import tech.easyflow.ai.entity.Workflow;
|
||||
import tech.easyflow.ai.enums.PublishStatus;
|
||||
import tech.easyflow.ai.permission.McpAccessPermissionChecker;
|
||||
import tech.easyflow.ai.permission.WorkflowVisibilityQueryHelper;
|
||||
import tech.easyflow.ai.service.McpService;
|
||||
import tech.easyflow.ai.service.PluginItemService;
|
||||
import tech.easyflow.ai.service.PluginService;
|
||||
import tech.easyflow.ai.service.PluginVisibilityService;
|
||||
import tech.easyflow.ai.service.WorkflowService;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
import tech.easyflow.skill.security.SkillPortableTargetSanitizer;
|
||||
import tech.easyflow.system.entity.vo.RoleCategoryAccessSnapshot;
|
||||
import tech.easyflow.system.enums.CategoryResourceType;
|
||||
import tech.easyflow.system.enums.ResourceAction;
|
||||
import tech.easyflow.system.service.CategoryPermissionService;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Skill 能力目标授权服务默认实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillCapabilityTargetAccessServiceImpl implements SkillCapabilityTargetAccessService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SkillCapabilityTargetAccessServiceImpl.class);
|
||||
private static final int MAX_CANDIDATES = 100;
|
||||
private static final String UNRESOLVED_PREFIX = "unresolved:";
|
||||
|
||||
private final WorkflowService workflowService;
|
||||
private final PluginItemService pluginItemService;
|
||||
private final PluginService pluginService;
|
||||
private final PluginVisibilityService pluginVisibilityService;
|
||||
private final McpService mcpService;
|
||||
private final McpAccessPermissionChecker mcpAccessPermissionChecker;
|
||||
private final ResourceAccessService resourceAccessService;
|
||||
private final WorkflowVisibilityQueryHelper workflowVisibilityQueryHelper;
|
||||
private final CategoryPermissionService categoryPermissionService;
|
||||
|
||||
/**
|
||||
* 创建能力目标授权服务。
|
||||
*
|
||||
* @param workflowService 工作流服务
|
||||
* @param pluginItemService 插件工具项服务
|
||||
* @param pluginService 插件服务
|
||||
* @param pluginVisibilityService 插件可见性服务
|
||||
* @param mcpService MCP 服务
|
||||
* @param mcpAccessPermissionChecker MCP 查询与使用权限检查器
|
||||
* @param resourceAccessService 分类资源访问服务
|
||||
* @param workflowVisibilityQueryHelper 工作流可见性查询助手
|
||||
* @param categoryPermissionService 分类权限服务
|
||||
*/
|
||||
public SkillCapabilityTargetAccessServiceImpl(WorkflowService workflowService,
|
||||
PluginItemService pluginItemService,
|
||||
PluginService pluginService,
|
||||
PluginVisibilityService pluginVisibilityService,
|
||||
McpService mcpService,
|
||||
McpAccessPermissionChecker mcpAccessPermissionChecker,
|
||||
ResourceAccessService resourceAccessService,
|
||||
WorkflowVisibilityQueryHelper workflowVisibilityQueryHelper,
|
||||
CategoryPermissionService categoryPermissionService) {
|
||||
this.workflowService = workflowService;
|
||||
this.pluginItemService = pluginItemService;
|
||||
this.pluginService = pluginService;
|
||||
this.pluginVisibilityService = pluginVisibilityService;
|
||||
this.mcpService = mcpService;
|
||||
this.mcpAccessPermissionChecker = mcpAccessPermissionChecker;
|
||||
this.resourceAccessService = resourceAccessService;
|
||||
this.workflowVisibilityQueryHelper = workflowVisibilityQueryHelper;
|
||||
this.categoryPermissionService = categoryPermissionService;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SkillCapabilityTarget requireUsableTarget(SkillCapabilityBinding binding, boolean resolveMcpTools) {
|
||||
if (binding == null || binding.getTargetId() == null) {
|
||||
throw new BusinessException("能力绑定目标不能为空");
|
||||
}
|
||||
SkillCapabilityType type = SkillCapabilityType.from(binding.getCapabilityType());
|
||||
return switch (type) {
|
||||
case WORKFLOW -> requireWorkflow(binding.getTargetId());
|
||||
case PLUGIN_ITEM -> requirePluginItem(binding.getTargetId());
|
||||
case MCP -> requireMcp(binding.getTargetId(), resolveMcpTools);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<SkillCapabilityCandidate> listCandidates(SkillCapabilityType capabilityType, String keyword) {
|
||||
String normalizedKeyword = keyword == null ? "" : keyword.trim().toLowerCase();
|
||||
return switch (capabilityType) {
|
||||
case WORKFLOW -> workflowCandidates(normalizedKeyword);
|
||||
case PLUGIN_ITEM -> pluginCandidates(normalizedKeyword);
|
||||
case MCP -> mcpCandidates(normalizedKeyword);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public BigInteger resolveLogicalRef(SkillCapabilityType capabilityType, String logicalRef) {
|
||||
if (capabilityType == SkillCapabilityType.MCP) {
|
||||
// 显式未映射引用仍属于增强包 MCP 映射流程,不能绕过模块权限。
|
||||
mcpAccessPermissionChecker.assertCanUseMcp();
|
||||
}
|
||||
if (!SkillPortableTargetSanitizer.isSafeLogicalRef(capabilityType, logicalRef)) {
|
||||
return null;
|
||||
}
|
||||
if (logicalRef.startsWith(UNRESOLVED_PREFIX)
|
||||
|| "workflow:unmapped".equals(logicalRef)
|
||||
|| "plugin-item:unmapped/unmapped".equals(logicalRef)
|
||||
|| "mcp:unmapped".equals(logicalRef)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return switch (capabilityType) {
|
||||
case WORKFLOW -> resolveWorkflowRef(logicalRef);
|
||||
case PLUGIN_ITEM -> resolvePluginItemRef(logicalRef);
|
||||
case MCP -> resolveMcpRef(logicalRef);
|
||||
};
|
||||
} catch (BusinessException exception) {
|
||||
if (exception.getHttpStatus() == 401 || exception.getHttpStatus() == 403) {
|
||||
throw exception;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SkillCapabilityCandidate getMcpTools(BigInteger targetId) {
|
||||
SkillCapabilityTarget target = requireMcp(targetId, true);
|
||||
return toCandidate(SkillCapabilityType.MCP, targetId, target);
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget requireWorkflow(BigInteger targetId) {
|
||||
Workflow workflow = workflowService.getOne(QueryWrapper.create()
|
||||
.eq(Workflow::getId, targetId)
|
||||
.eq(Workflow::getTenantId, requireAccount().getTenantId()));
|
||||
return toWorkflowTarget(workflow, targetId, true);
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget toWorkflowTarget(Workflow workflow, BigInteger targetId, boolean assertPermission) {
|
||||
if (workflow == null || PublishStatus.from(workflow.getPublishStatus()) != PublishStatus.PUBLISHED
|
||||
|| workflow.getPublishedSnapshotJson() == null || workflow.getPublishedSnapshotJson().isEmpty()) {
|
||||
throw new BusinessException(404, 404, "绑定工作流不存在、未发布或没有有效发布快照");
|
||||
}
|
||||
if (assertPermission) {
|
||||
resourceAccessService.assertAccess(CategoryResourceType.WORKFLOW, workflow, ResourceAction.USE,
|
||||
"无权限使用绑定工作流");
|
||||
}
|
||||
SkillCapabilityTarget target = new SkillCapabilityTarget();
|
||||
target.setName(workflow.getTitle());
|
||||
target.setDescription(workflow.getDescription());
|
||||
String stableRef = firstNonBlank(workflow.getAlias(), workflow.getEnglishName());
|
||||
target.setLogicalRef(SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
SkillCapabilityType.WORKFLOW, stableRef == null ? null : "workflow:" + stableRef));
|
||||
target.setRevision(workflow.getPublishedAt() == null ? null : String.valueOf(workflow.getPublishedAt().getTime()));
|
||||
target.setStatus("AVAILABLE");
|
||||
return target;
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget requirePluginItem(BigInteger targetId) {
|
||||
LoginAccount account = requireAccount();
|
||||
PluginItem item = pluginItemService.getOne(QueryWrapper.create()
|
||||
.eq(PluginItem::getId, targetId)
|
||||
.and("plugin_id IN (SELECT id FROM tb_plugin WHERE tenant_id = ?)",
|
||||
account.getTenantId().longValue()));
|
||||
if (item == null || !Integer.valueOf(1).equals(item.getStatus())
|
||||
|| !Integer.valueOf(1).equals(item.getServiceStatus())) {
|
||||
throw new BusinessException(404, 404, "绑定插件工具项不存在或未启用");
|
||||
}
|
||||
Plugin plugin = pluginService.getOne(QueryWrapper.create()
|
||||
.eq(Plugin::getId, item.getPluginId())
|
||||
.eq(Plugin::getTenantId, account.getTenantId().longValue()));
|
||||
return toPluginTarget(item, plugin, true, false);
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget toPluginTarget(PluginItem item, Plugin plugin,
|
||||
boolean assertPermission, boolean alreadyPrepared) {
|
||||
if (plugin == null) {
|
||||
throw new BusinessException(404, 404, "绑定插件工具项所属插件不存在");
|
||||
}
|
||||
LoginAccount account = requireAccount();
|
||||
if (!Objects.equals(plugin.getTenantId(), account.getTenantId().longValue())) {
|
||||
throw new BusinessException(403, 403, "无权限使用绑定插件");
|
||||
}
|
||||
if (assertPermission && !pluginVisibilityService.canAccessPlugin(plugin.getCreatedBy(), plugin.getId())) {
|
||||
throw new BusinessException(403, 403, "无权限使用绑定插件");
|
||||
}
|
||||
Plugin prepared = alreadyPrepared ? plugin : pluginService.preparePluginForCurrentUser(plugin);
|
||||
if (prepared != null && Boolean.FALSE.equals(prepared.getAvailable())) {
|
||||
throw new BusinessException(firstNonBlank(prepared.getReasonMessage(), "绑定插件当前不可用"));
|
||||
}
|
||||
SkillCapabilityTarget target = new SkillCapabilityTarget();
|
||||
target.setName(plugin.getName() + " / " + item.getName());
|
||||
target.setDescription(item.getDescription());
|
||||
String pluginRef = firstNonBlank(plugin.getAlias());
|
||||
String itemRef = firstNonBlank(item.getEnglishName());
|
||||
String logicalRef = pluginRef == null || itemRef == null
|
||||
? null : "plugin-item:" + pluginRef + "/" + itemRef;
|
||||
target.setLogicalRef(SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
SkillCapabilityType.PLUGIN_ITEM, logicalRef));
|
||||
target.setRevision(item.getSchemaHash());
|
||||
target.setStatus("AVAILABLE");
|
||||
return target;
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget requireMcp(BigInteger targetId, boolean resolveTools) {
|
||||
mcpAccessPermissionChecker.assertCanUseMcp();
|
||||
Mcp mcp = mcpService.getOne(QueryWrapper.create()
|
||||
.eq(Mcp::getId, targetId)
|
||||
.eq(Mcp::getTenantId, requireAccount().getTenantId()));
|
||||
return toMcpTarget(mcp, targetId, resolveTools);
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget toMcpTarget(Mcp mcp, BigInteger targetId, boolean resolveTools) {
|
||||
LoginAccount account = requireAccount();
|
||||
if (mcp == null || !Boolean.TRUE.equals(mcp.getStatus())) {
|
||||
throw new BusinessException(404, 404, "绑定 MCP 不存在或未启用");
|
||||
}
|
||||
// MCP 尚未纳入 CategoryResourceType,显式限制到当前租户,防止使用 ID 绕过租户隔离。
|
||||
if (!Objects.equals(account.getTenantId(), mcp.getTenantId())) {
|
||||
throw new BusinessException(403, 403, "无权限使用绑定 MCP");
|
||||
}
|
||||
SkillCapabilityTarget target = new SkillCapabilityTarget();
|
||||
target.setName(mcp.getTitle());
|
||||
target.setDescription(mcp.getDescription());
|
||||
target.setLogicalRef(SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
SkillCapabilityType.MCP, mcp.getTitle() == null ? null : "mcp:" + mcp.getTitle()));
|
||||
target.setRevision(mcp.getModified() == null ? null : String.valueOf(mcp.getModified().getTime()));
|
||||
target.setStatus("AVAILABLE");
|
||||
if (resolveTools) {
|
||||
try {
|
||||
Mcp resolved = mcpService.getMcpTools(targetId.toString());
|
||||
if (resolved == null || resolved.getTools() == null) {
|
||||
throw new BusinessException("MCP 当前未连接,无法解析工具清单");
|
||||
}
|
||||
target.setToolNames(resolved.getTools().stream().map(McpSchema.Tool::name).sorted().toList());
|
||||
} catch (BusinessException exception) {
|
||||
throw exception;
|
||||
} catch (Exception exception) {
|
||||
LOG.error("解析 Skill 绑定 MCP 工具清单失败,targetId={}", targetId, exception);
|
||||
throw new BusinessException(502, 5021,
|
||||
"MCP 工具清单解析失败,请检查服务连接状态", exception);
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private List<SkillCapabilityCandidate> workflowCandidates(String keyword) {
|
||||
QueryWrapper query = QueryWrapper.create()
|
||||
.eq(Workflow::getTenantId, requireAccount().getTenantId())
|
||||
.eq(Workflow::getPublishStatus, PublishStatus.PUBLISHED.getCode())
|
||||
.orderBy("modified desc");
|
||||
workflowVisibilityQueryHelper.applyReadableAccess(query);
|
||||
query.limit(MAX_CANDIDATES);
|
||||
applyKeyword(query, keyword, "title", "description", "alias", "english_name");
|
||||
List<SkillCapabilityCandidate> result = new ArrayList<>();
|
||||
for (Workflow workflow : workflowService.list(query)) {
|
||||
if (!resourceAccessService.canAccess(CategoryResourceType.WORKFLOW, workflow, ResourceAction.USE)) {
|
||||
continue;
|
||||
}
|
||||
SkillCapabilityTarget target;
|
||||
try {
|
||||
target = toWorkflowTarget(workflow, workflow.getId(), false);
|
||||
} catch (BusinessException ignored) {
|
||||
continue;
|
||||
}
|
||||
if (!matches(keyword, target.getName(), target.getDescription(), target.getLogicalRef())) {
|
||||
continue;
|
||||
}
|
||||
result.add(toCandidate(SkillCapabilityType.WORKFLOW, workflow.getId(), target));
|
||||
if (result.size() >= MAX_CANDIDATES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<SkillCapabilityCandidate> pluginCandidates(String keyword) {
|
||||
QueryWrapper query = QueryWrapper.create()
|
||||
.eq(PluginItem::getStatus, 1)
|
||||
.eq(PluginItem::getServiceStatus, 1)
|
||||
.orderBy("created desc");
|
||||
applyPluginReadableAccess(query);
|
||||
query.limit(MAX_CANDIDATES);
|
||||
applyKeyword(query, keyword, "name", "description", "english_name");
|
||||
List<PluginItem> items = pluginItemService.list(query);
|
||||
Map<BigInteger, Plugin> plugins = loadPlugins(items);
|
||||
Map<BigInteger, Plugin> preparedPlugins = new LinkedHashMap<>();
|
||||
for (Plugin plugin : plugins.values()) {
|
||||
preparedPlugins.put(plugin.getId(), pluginService.preparePluginForCurrentUser(plugin));
|
||||
}
|
||||
List<SkillCapabilityCandidate> result = new ArrayList<>();
|
||||
for (PluginItem item : items) {
|
||||
Plugin plugin = preparedPlugins.get(item.getPluginId());
|
||||
if (plugin == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
SkillCapabilityTarget target = toPluginTarget(item, plugin, false, true);
|
||||
if (matches(keyword, target.getName(), target.getDescription(), target.getLogicalRef())) {
|
||||
result.add(toCandidate(SkillCapabilityType.PLUGIN_ITEM, item.getId(), target));
|
||||
if (result.size() >= MAX_CANDIDATES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (BusinessException ignored) {
|
||||
// 候选列表只展示当前可用项,具体不可用原因在已保存绑定的校验结果中返回。
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<SkillCapabilityCandidate> mcpCandidates(String keyword) {
|
||||
// 候选枚举在查询数据前完成模块权限校验,避免把无权限误装成空列表。
|
||||
mcpAccessPermissionChecker.assertCanUseMcp();
|
||||
QueryWrapper query = QueryWrapper.create().eq(Mcp::getStatus, true)
|
||||
.eq(Mcp::getTenantId, requireAccount().getTenantId())
|
||||
.orderBy("modified desc").limit(MAX_CANDIDATES);
|
||||
applyKeyword(query, keyword, "title", "description");
|
||||
List<SkillCapabilityCandidate> result = new ArrayList<>();
|
||||
for (Mcp mcp : mcpService.list(query)) {
|
||||
try {
|
||||
SkillCapabilityTarget target = toMcpTarget(mcp, mcp.getId(), false);
|
||||
if (matches(keyword, target.getName(), target.getDescription(), target.getLogicalRef())) {
|
||||
result.add(toCandidate(SkillCapabilityType.MCP, mcp.getId(), target));
|
||||
if (result.size() >= MAX_CANDIDATES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (BusinessException ignored) {
|
||||
// 同租户且启用的 MCP 才能成为候选。
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<BigInteger, Plugin> loadPlugins(List<PluginItem> items) {
|
||||
List<BigInteger> ids = items.stream().map(PluginItem::getPluginId).filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<BigInteger, Plugin> result = new LinkedHashMap<>();
|
||||
for (Plugin plugin : pluginService.list(QueryWrapper.create()
|
||||
.eq(Plugin::getTenantId, requireAccount().getTenantId().longValue())
|
||||
.in(Plugin::getId, ids))) {
|
||||
result.put(plugin.getId(), plugin);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void applyPluginReadableAccess(QueryWrapper itemQuery) {
|
||||
LoginAccount account = requireAccount();
|
||||
itemQuery.and("plugin_id IN (SELECT id FROM tb_plugin WHERE tenant_id = ?)",
|
||||
account.getTenantId().longValue());
|
||||
RoleCategoryAccessSnapshot snapshot = categoryPermissionService.getCurrentAccess("PLUGIN");
|
||||
if (snapshot.isSuperAdmin() || !snapshot.isRestricted()) {
|
||||
return;
|
||||
}
|
||||
if (snapshot.getAccountId() == null) {
|
||||
itemQuery.and("1 = 0");
|
||||
return;
|
||||
}
|
||||
if (snapshot.getCategoryIds().isEmpty()) {
|
||||
itemQuery.and("plugin_id IN (SELECT id FROM tb_plugin WHERE created_by = ?)",
|
||||
snapshot.getAccountId());
|
||||
return;
|
||||
}
|
||||
String placeholders = String.join(",", java.util.Collections.nCopies(
|
||||
snapshot.getCategoryIds().size(), "?"));
|
||||
List<Object> arguments = new ArrayList<>();
|
||||
arguments.add(snapshot.getAccountId());
|
||||
arguments.addAll(snapshot.getCategoryIds());
|
||||
itemQuery.and("plugin_id IN (SELECT id FROM tb_plugin WHERE created_by = ? OR id IN "
|
||||
+ "(SELECT plugin_id FROM tb_plugin_category_mapping WHERE category_id IN (" + placeholders + ")))",
|
||||
arguments.toArray());
|
||||
}
|
||||
|
||||
private BigInteger resolveWorkflowRef(String logicalRef) {
|
||||
if (!logicalRef.startsWith("workflow:")) {
|
||||
return null;
|
||||
}
|
||||
String key = logicalRef.substring("workflow:".length());
|
||||
QueryWrapper query = QueryWrapper.create();
|
||||
query.eq(Workflow::getTenantId, requireAccount().getTenantId());
|
||||
query.and("(alias = ? OR english_name = ?)", key, key);
|
||||
query.limit(2);
|
||||
List<Workflow> matches = workflowService.list(query).stream()
|
||||
.filter(workflow -> resourceAccessService.canAccess(
|
||||
CategoryResourceType.WORKFLOW, workflow, ResourceAction.USE))
|
||||
.toList();
|
||||
if (matches.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
toWorkflowTarget(matches.get(0), matches.get(0).getId(), false);
|
||||
return matches.get(0).getId();
|
||||
}
|
||||
|
||||
private BigInteger resolvePluginItemRef(String logicalRef) {
|
||||
if (!logicalRef.startsWith("plugin-item:") || !logicalRef.substring("plugin-item:".length()).contains("/")) {
|
||||
return null;
|
||||
}
|
||||
String value = logicalRef.substring("plugin-item:".length());
|
||||
int separator = value.indexOf('/');
|
||||
String pluginKey = value.substring(0, separator);
|
||||
String itemKey = value.substring(separator + 1);
|
||||
QueryWrapper pluginQuery = QueryWrapper.create();
|
||||
pluginQuery.eq(Plugin::getTenantId, requireAccount().getTenantId().longValue())
|
||||
.eq(Plugin::getAlias, pluginKey);
|
||||
pluginQuery.limit(2);
|
||||
List<Plugin> plugins = pluginService.list(pluginQuery).stream()
|
||||
.filter(plugin -> pluginVisibilityService.canAccessPlugin(plugin.getCreatedBy(), plugin.getId()))
|
||||
.toList();
|
||||
if (plugins.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
QueryWrapper itemQuery = QueryWrapper.create().eq(PluginItem::getPluginId, plugins.get(0).getId());
|
||||
itemQuery.and("(english_name = ? OR name = ?)", itemKey, itemKey);
|
||||
itemQuery.limit(2);
|
||||
List<PluginItem> items = pluginItemService.list(itemQuery);
|
||||
if (items.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
toPluginTarget(items.get(0), plugins.get(0), false, false);
|
||||
return items.get(0).getId();
|
||||
}
|
||||
|
||||
private BigInteger resolveMcpRef(String logicalRef) {
|
||||
if (!logicalRef.startsWith("mcp:")) {
|
||||
return null;
|
||||
}
|
||||
String title = logicalRef.substring("mcp:".length());
|
||||
List<Mcp> matches = mcpService.list(QueryWrapper.create()
|
||||
.eq(Mcp::getTenantId, requireAccount().getTenantId())
|
||||
.eq(Mcp::getTitle, title).limit(2));
|
||||
List<Mcp> usable = matches.stream().filter(mcp -> {
|
||||
try {
|
||||
toMcpTarget(mcp, mcp.getId(), false);
|
||||
return true;
|
||||
} catch (BusinessException exception) {
|
||||
return false;
|
||||
}
|
||||
}).toList();
|
||||
return usable.size() == 1 ? usable.get(0).getId() : null;
|
||||
}
|
||||
|
||||
private SkillCapabilityCandidate toCandidate(SkillCapabilityType type, BigInteger id, SkillCapabilityTarget target) {
|
||||
SkillCapabilityCandidate candidate = new SkillCapabilityCandidate();
|
||||
candidate.setCapabilityType(type.name());
|
||||
candidate.setTargetId(id);
|
||||
candidate.setName(target.getName());
|
||||
candidate.setDescription(target.getDescription());
|
||||
candidate.setLogicalRef(target.getLogicalRef());
|
||||
candidate.setRevision(target.getRevision());
|
||||
candidate.setStatus(target.getStatus());
|
||||
candidate.setToolNames(target.getToolNames());
|
||||
return candidate;
|
||||
}
|
||||
|
||||
private boolean matches(String keyword, String... values) {
|
||||
if (keyword == null || keyword.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
for (String value : values) {
|
||||
if (value != null && value.toLowerCase(Locale.ROOT).contains(keyword)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void applyKeyword(QueryWrapper query, String keyword, String... columns) {
|
||||
if (keyword == null || keyword.isBlank() || columns.length == 0) {
|
||||
return;
|
||||
}
|
||||
String pattern = "%" + keyword.toLowerCase(Locale.ROOT) + "%";
|
||||
StringBuilder condition = new StringBuilder("(");
|
||||
Object[] arguments = new Object[columns.length];
|
||||
for (int index = 0; index < columns.length; index++) {
|
||||
if (index > 0) {
|
||||
condition.append(" OR ");
|
||||
}
|
||||
condition.append("LOWER(").append(columns[index]).append(") LIKE ?");
|
||||
arguments[index] = pattern;
|
||||
}
|
||||
condition.append(')');
|
||||
query.and(condition.toString(), arguments);
|
||||
}
|
||||
|
||||
private LoginAccount requireAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
private String firstNonBlank(String... values) {
|
||||
for (String value : values) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -39,6 +39,10 @@ public class Skill extends DateEntity implements VisibilityResource, Serializabl
|
||||
private String visibilityScope;
|
||||
private String sourceType;
|
||||
private String packageHash;
|
||||
private String capabilityHash;
|
||||
private String snapshotHash;
|
||||
private Integer resourceCount;
|
||||
private Integer capabilityCount;
|
||||
private Integer referenceCount;
|
||||
private Integer scriptCount;
|
||||
private Integer assetCount;
|
||||
@@ -67,6 +71,10 @@ public class Skill extends DateEntity implements VisibilityResource, Serializabl
|
||||
private List<SkillScript> scripts;
|
||||
@Column(ignore = true)
|
||||
private List<SkillAsset> assets;
|
||||
@Column(ignore = true)
|
||||
private List<SkillResource> resources;
|
||||
@Column(ignore = true)
|
||||
private List<SkillCapabilityBinding> capabilityBindings;
|
||||
|
||||
public BigInteger getId() { return id; }
|
||||
public void setId(BigInteger id) { this.id = id; }
|
||||
@@ -94,6 +102,14 @@ public class Skill extends DateEntity implements VisibilityResource, Serializabl
|
||||
public void setSourceType(String sourceType) { this.sourceType = sourceType; }
|
||||
public String getPackageHash() { return packageHash; }
|
||||
public void setPackageHash(String packageHash) { this.packageHash = packageHash; }
|
||||
public String getCapabilityHash() { return capabilityHash; }
|
||||
public void setCapabilityHash(String capabilityHash) { this.capabilityHash = capabilityHash; }
|
||||
public String getSnapshotHash() { return snapshotHash; }
|
||||
public void setSnapshotHash(String snapshotHash) { this.snapshotHash = snapshotHash; }
|
||||
public Integer getResourceCount() { return resourceCount; }
|
||||
public void setResourceCount(Integer resourceCount) { this.resourceCount = resourceCount; }
|
||||
public Integer getCapabilityCount() { return capabilityCount; }
|
||||
public void setCapabilityCount(Integer capabilityCount) { this.capabilityCount = capabilityCount; }
|
||||
public Integer getReferenceCount() { return referenceCount; }
|
||||
public void setReferenceCount(Integer referenceCount) { this.referenceCount = referenceCount; }
|
||||
public Integer getScriptCount() { return scriptCount; }
|
||||
@@ -132,4 +148,8 @@ public class Skill extends DateEntity implements VisibilityResource, Serializabl
|
||||
public void setScripts(List<SkillScript> scripts) { this.scripts = scripts; }
|
||||
public List<SkillAsset> getAssets() { return assets; }
|
||||
public void setAssets(List<SkillAsset> assets) { this.assets = assets; }
|
||||
public List<SkillResource> getResources() { return resources; }
|
||||
public void setResources(List<SkillResource> resources) { this.resources = resources; }
|
||||
public List<SkillCapabilityBinding> getCapabilityBindings() { return capabilityBindings; }
|
||||
public void setCapabilityBindings(List<SkillCapabilityBinding> capabilityBindings) { this.capabilityBindings = capabilityBindings; }
|
||||
}
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package tech.easyflow.skill.entity;
|
||||
|
||||
import com.mybatisflex.annotation.Id;
|
||||
import com.mybatisflex.annotation.Table;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Skill asset 内容索引实体。
|
||||
*/
|
||||
@Table("tb_skill_asset_content")
|
||||
public class SkillAssetContent implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
private String contentRef;
|
||||
private String contentHash;
|
||||
private String filePath;
|
||||
private String mediaType;
|
||||
private Long size;
|
||||
private Integer refCount;
|
||||
private Date created;
|
||||
private Date modified;
|
||||
|
||||
public String getContentRef() { return contentRef; }
|
||||
public void setContentRef(String contentRef) { this.contentRef = contentRef; }
|
||||
public String getContentHash() { return contentHash; }
|
||||
public void setContentHash(String contentHash) { this.contentHash = contentHash; }
|
||||
public String getFilePath() { return filePath; }
|
||||
public void setFilePath(String filePath) { this.filePath = filePath; }
|
||||
public String getMediaType() { return mediaType; }
|
||||
public void setMediaType(String mediaType) { this.mediaType = mediaType; }
|
||||
public Long getSize() { return size; }
|
||||
public void setSize(Long size) { this.size = size; }
|
||||
public Integer getRefCount() { return refCount; }
|
||||
public void setRefCount(Integer refCount) { this.refCount = refCount; }
|
||||
public Date getCreated() { return created; }
|
||||
public void setCreated(Date created) { this.created = created; }
|
||||
public Date getModified() { return modified; }
|
||||
public void setModified(Date modified) { this.modified = modified; }
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package tech.easyflow.skill.entity;
|
||||
|
||||
import com.mybatisflex.annotation.Column;
|
||||
import com.mybatisflex.annotation.Id;
|
||||
import com.mybatisflex.annotation.KeyType;
|
||||
import com.mybatisflex.annotation.Table;
|
||||
import com.mybatisflex.core.handler.FastjsonTypeHandler;
|
||||
import tech.easyflow.common.entity.DateEntity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Skill 与平台能力的绑定实体。
|
||||
*/
|
||||
@Table("tb_skill_capability_binding")
|
||||
public class SkillCapabilityBinding extends DateEntity implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id(keyType = KeyType.Generator, value = "snowFlakeId")
|
||||
private BigInteger id;
|
||||
@Column(tenantId = true)
|
||||
private BigInteger tenantId;
|
||||
private BigInteger skillId;
|
||||
private String capabilityType;
|
||||
private BigInteger targetId;
|
||||
private String targetLogicalRef;
|
||||
private String runtimeName;
|
||||
private Boolean enabled;
|
||||
private String selectionMode;
|
||||
@Column(typeHandler = FastjsonTypeHandler.class)
|
||||
private List<String> selectedToolNamesJson = new ArrayList<>();
|
||||
private String executionMode;
|
||||
private Boolean hitlEnabled;
|
||||
@Column(typeHandler = FastjsonTypeHandler.class)
|
||||
private Map<String, Object> hitlConfigJson = new LinkedHashMap<>();
|
||||
@Column(typeHandler = FastjsonTypeHandler.class)
|
||||
private Map<String, Object> optionsJson = new LinkedHashMap<>();
|
||||
private Integer sortNo;
|
||||
private Date created;
|
||||
private BigInteger createdBy;
|
||||
private Date modified;
|
||||
private BigInteger modifiedBy;
|
||||
|
||||
@Column(ignore = true)
|
||||
private String targetName;
|
||||
@Column(ignore = true)
|
||||
private String targetStatus;
|
||||
@Column(ignore = true)
|
||||
private List<String> resolvedToolNames = new ArrayList<>();
|
||||
|
||||
public BigInteger getId() { return id; }
|
||||
public void setId(BigInteger id) { this.id = id; }
|
||||
public BigInteger getTenantId() { return tenantId; }
|
||||
public void setTenantId(BigInteger tenantId) { this.tenantId = tenantId; }
|
||||
public BigInteger getSkillId() { return skillId; }
|
||||
public void setSkillId(BigInteger skillId) { this.skillId = skillId; }
|
||||
public String getCapabilityType() { return capabilityType; }
|
||||
public void setCapabilityType(String capabilityType) { this.capabilityType = capabilityType; }
|
||||
public BigInteger getTargetId() { return targetId; }
|
||||
public void setTargetId(BigInteger targetId) { this.targetId = targetId; }
|
||||
public String getTargetLogicalRef() { return targetLogicalRef; }
|
||||
public void setTargetLogicalRef(String targetLogicalRef) { this.targetLogicalRef = targetLogicalRef; }
|
||||
public String getRuntimeName() { return runtimeName; }
|
||||
public void setRuntimeName(String runtimeName) { this.runtimeName = runtimeName; }
|
||||
public Boolean getEnabled() { return enabled; }
|
||||
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
|
||||
public String getSelectionMode() { return selectionMode; }
|
||||
public void setSelectionMode(String selectionMode) { this.selectionMode = selectionMode; }
|
||||
public List<String> getSelectedToolNamesJson() { return selectedToolNamesJson; }
|
||||
public void setSelectedToolNamesJson(List<String> selectedToolNamesJson) { this.selectedToolNamesJson = selectedToolNamesJson == null ? new ArrayList<>() : new ArrayList<>(selectedToolNamesJson); }
|
||||
public String getExecutionMode() { return executionMode; }
|
||||
public void setExecutionMode(String executionMode) { this.executionMode = executionMode; }
|
||||
public Boolean getHitlEnabled() { return hitlEnabled; }
|
||||
public void setHitlEnabled(Boolean hitlEnabled) { this.hitlEnabled = hitlEnabled; }
|
||||
public Map<String, Object> getHitlConfigJson() { return hitlConfigJson; }
|
||||
public void setHitlConfigJson(Map<String, Object> hitlConfigJson) { this.hitlConfigJson = hitlConfigJson == null ? new LinkedHashMap<>() : hitlConfigJson; }
|
||||
public Map<String, Object> getOptionsJson() { return optionsJson; }
|
||||
public void setOptionsJson(Map<String, Object> optionsJson) { this.optionsJson = optionsJson == null ? new LinkedHashMap<>() : optionsJson; }
|
||||
public Integer getSortNo() { return sortNo; }
|
||||
public void setSortNo(Integer sortNo) { this.sortNo = sortNo; }
|
||||
@Override public Date getCreated() { return created; }
|
||||
@Override public void setCreated(Date created) { this.created = created; }
|
||||
public BigInteger getCreatedBy() { return createdBy; }
|
||||
public void setCreatedBy(BigInteger createdBy) { this.createdBy = createdBy; }
|
||||
@Override public Date getModified() { return modified; }
|
||||
@Override public void setModified(Date modified) { this.modified = modified; }
|
||||
public BigInteger getModifiedBy() { return modifiedBy; }
|
||||
public void setModifiedBy(BigInteger modifiedBy) { this.modifiedBy = modifiedBy; }
|
||||
public String getTargetName() { return targetName; }
|
||||
public void setTargetName(String targetName) { this.targetName = targetName; }
|
||||
public String getTargetStatus() { return targetStatus; }
|
||||
public void setTargetStatus(String targetStatus) { this.targetStatus = targetStatus; }
|
||||
public List<String> getResolvedToolNames() { return resolvedToolNames; }
|
||||
public void setResolvedToolNames(List<String> resolvedToolNames) { this.resolvedToolNames = resolvedToolNames == null ? new ArrayList<>() : new ArrayList<>(resolvedToolNames); }
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import tech.easyflow.common.entity.DateEntity;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 分类实体。
|
||||
@@ -32,6 +34,8 @@ public class SkillCategory extends DateEntity implements Serializable {
|
||||
private BigInteger createdBy;
|
||||
private Date modified;
|
||||
private BigInteger modifiedBy;
|
||||
@Column(ignore = true)
|
||||
private List<SkillCategory> children = new ArrayList<>();
|
||||
|
||||
public BigInteger getId() { return id; }
|
||||
public void setId(BigInteger id) { this.id = id; }
|
||||
@@ -57,4 +61,6 @@ public class SkillCategory extends DateEntity implements Serializable {
|
||||
@Override public void setModified(Date modified) { this.modified = modified; }
|
||||
public BigInteger getModifiedBy() { return modifiedBy; }
|
||||
public void setModifiedBy(BigInteger modifiedBy) { this.modifiedBy = modifiedBy; }
|
||||
public List<SkillCategory> getChildren() { return children; }
|
||||
public void setChildren(List<SkillCategory> children) { this.children = children == null ? new ArrayList<>() : children; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package tech.easyflow.skill.entity;
|
||||
|
||||
import com.mybatisflex.annotation.Id;
|
||||
import com.mybatisflex.annotation.Table;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Skill 二进制内容索引实体。
|
||||
*/
|
||||
@Table("tb_skill_content")
|
||||
public class SkillContent implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 内容引用。 */
|
||||
@Id
|
||||
private String contentRef;
|
||||
/** 内容哈希。 */
|
||||
private String contentHash;
|
||||
/** 文件存储返回的读取路径。 */
|
||||
private String filePath;
|
||||
/** 可在写入前确定的稳定存储定位符。 */
|
||||
private String storageLocator;
|
||||
/** 媒体类型。 */
|
||||
private String mediaType;
|
||||
/** 内容字节数。 */
|
||||
private Long size;
|
||||
/** 当前引用数。 */
|
||||
private Integer refCount;
|
||||
/** 创建时间。 */
|
||||
private Date created;
|
||||
/** 修改时间。 */
|
||||
private Date modified;
|
||||
|
||||
/**
|
||||
* 获取内容引用。
|
||||
*
|
||||
* @return 内容引用
|
||||
*/
|
||||
public String getContentRef() {
|
||||
return contentRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容引用。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
*/
|
||||
public void setContentRef(String contentRef) {
|
||||
this.contentRef = contentRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取内容哈希。
|
||||
*
|
||||
* @return 内容哈希
|
||||
*/
|
||||
public String getContentHash() {
|
||||
return contentHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容哈希。
|
||||
*
|
||||
* @param contentHash 内容哈希
|
||||
*/
|
||||
public void setContentHash(String contentHash) {
|
||||
this.contentHash = contentHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件读取路径。
|
||||
*
|
||||
* @return 文件读取路径
|
||||
*/
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置文件读取路径。
|
||||
*
|
||||
* @param filePath 文件读取路径
|
||||
*/
|
||||
public void setFilePath(String filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取稳定存储定位符。
|
||||
*
|
||||
* @return 稳定存储定位符
|
||||
*/
|
||||
public String getStorageLocator() {
|
||||
return storageLocator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置稳定存储定位符。
|
||||
*
|
||||
* @param storageLocator 稳定存储定位符
|
||||
*/
|
||||
public void setStorageLocator(String storageLocator) {
|
||||
this.storageLocator = storageLocator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取媒体类型。
|
||||
*
|
||||
* @return 媒体类型
|
||||
*/
|
||||
public String getMediaType() {
|
||||
return mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置媒体类型。
|
||||
*
|
||||
* @param mediaType 媒体类型
|
||||
*/
|
||||
public void setMediaType(String mediaType) {
|
||||
this.mediaType = mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取内容字节数。
|
||||
*
|
||||
* @return 内容字节数
|
||||
*/
|
||||
public Long getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容字节数。
|
||||
*
|
||||
* @param size 内容字节数
|
||||
*/
|
||||
public void setSize(Long size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前引用数。
|
||||
*
|
||||
* @return 当前引用数
|
||||
*/
|
||||
public Integer getRefCount() {
|
||||
return refCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前引用数。
|
||||
*
|
||||
* @param refCount 当前引用数
|
||||
*/
|
||||
public void setRefCount(Integer refCount) {
|
||||
this.refCount = refCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取创建时间。
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
public Date getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置创建时间。
|
||||
*
|
||||
* @param created 创建时间
|
||||
*/
|
||||
public void setCreated(Date created) {
|
||||
this.created = created;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取修改时间。
|
||||
*
|
||||
* @return 修改时间
|
||||
*/
|
||||
public Date getModified() {
|
||||
return modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置修改时间。
|
||||
*
|
||||
* @param modified 修改时间
|
||||
*/
|
||||
public void setModified(Date modified) {
|
||||
this.modified = modified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package tech.easyflow.skill.entity;
|
||||
|
||||
import com.mybatisflex.annotation.Id;
|
||||
import com.mybatisflex.annotation.Table;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Skill 二进制内容写入意图实体。
|
||||
*
|
||||
* <p>写入意图独立于正式内容索引提交,用于在进程异常退出后定位尚未激活的物理对象。</p>
|
||||
*/
|
||||
@Table("tb_skill_content_write_intent")
|
||||
public class SkillContentWriteIntent implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 内容引用。 */
|
||||
@Id
|
||||
private String contentRef;
|
||||
/** 写入预留令牌。 */
|
||||
private String reservationToken;
|
||||
/** 内容哈希。 */
|
||||
private String contentHash;
|
||||
/** 可在写入前确定的稳定存储定位符。 */
|
||||
private String storageLocator;
|
||||
/** 媒体类型。 */
|
||||
private String mediaType;
|
||||
/** 内容字节数。 */
|
||||
private Long size;
|
||||
/** PENDING、WRITING 或 CLEANING 状态。 */
|
||||
private String state;
|
||||
/** 创建时间。 */
|
||||
private Date created;
|
||||
/** 修改时间。 */
|
||||
private Date modified;
|
||||
|
||||
/**
|
||||
* 获取内容引用。
|
||||
*
|
||||
* @return 内容引用
|
||||
*/
|
||||
public String getContentRef() {
|
||||
return contentRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容引用。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
*/
|
||||
public void setContentRef(String contentRef) {
|
||||
this.contentRef = contentRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取写入预留令牌。
|
||||
*
|
||||
* @return 写入预留令牌
|
||||
*/
|
||||
public String getReservationToken() {
|
||||
return reservationToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置写入预留令牌。
|
||||
*
|
||||
* @param reservationToken 写入预留令牌
|
||||
*/
|
||||
public void setReservationToken(String reservationToken) {
|
||||
this.reservationToken = reservationToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取内容哈希。
|
||||
*
|
||||
* @return 内容哈希
|
||||
*/
|
||||
public String getContentHash() {
|
||||
return contentHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容哈希。
|
||||
*
|
||||
* @param contentHash 内容哈希
|
||||
*/
|
||||
public void setContentHash(String contentHash) {
|
||||
this.contentHash = contentHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取稳定存储定位符。
|
||||
*
|
||||
* @return 稳定存储定位符
|
||||
*/
|
||||
public String getStorageLocator() {
|
||||
return storageLocator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置稳定存储定位符。
|
||||
*
|
||||
* @param storageLocator 稳定存储定位符
|
||||
*/
|
||||
public void setStorageLocator(String storageLocator) {
|
||||
this.storageLocator = storageLocator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取媒体类型。
|
||||
*
|
||||
* @return 媒体类型
|
||||
*/
|
||||
public String getMediaType() {
|
||||
return mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置媒体类型。
|
||||
*
|
||||
* @param mediaType 媒体类型
|
||||
*/
|
||||
public void setMediaType(String mediaType) {
|
||||
this.mediaType = mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取内容字节数。
|
||||
*
|
||||
* @return 内容字节数
|
||||
*/
|
||||
public Long getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置内容字节数。
|
||||
*
|
||||
* @param size 内容字节数
|
||||
*/
|
||||
public void setSize(Long size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取写入状态。
|
||||
*
|
||||
* @return 写入状态
|
||||
*/
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置写入状态。
|
||||
*
|
||||
* @param state 写入状态
|
||||
*/
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取创建时间。
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
public Date getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置创建时间。
|
||||
*
|
||||
* @param created 创建时间
|
||||
*/
|
||||
public void setCreated(Date created) {
|
||||
this.created = created;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取修改时间。
|
||||
*
|
||||
* @return 修改时间
|
||||
*/
|
||||
public Date getModified() {
|
||||
return modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置修改时间。
|
||||
*
|
||||
* @param modified 修改时间
|
||||
*/
|
||||
public void setModified(Date modified) {
|
||||
this.modified = modified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package tech.easyflow.skill.entity;
|
||||
|
||||
import com.mybatisflex.annotation.Column;
|
||||
import com.mybatisflex.annotation.Id;
|
||||
import com.mybatisflex.annotation.Table;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Skill 导入临时包索引。
|
||||
*/
|
||||
@Table("tb_skill_import_stage")
|
||||
public class SkillImportStage implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
private String importToken;
|
||||
@Column(tenantId = true)
|
||||
private BigInteger tenantId;
|
||||
private BigInteger accountId;
|
||||
private String filePath;
|
||||
private String originalName;
|
||||
private String format;
|
||||
private String status;
|
||||
private Date expiresAt;
|
||||
private Date created;
|
||||
|
||||
public String getImportToken() { return importToken; }
|
||||
public void setImportToken(String importToken) { this.importToken = importToken; }
|
||||
public BigInteger getTenantId() { return tenantId; }
|
||||
public void setTenantId(BigInteger tenantId) { this.tenantId = tenantId; }
|
||||
public BigInteger getAccountId() { return accountId; }
|
||||
public void setAccountId(BigInteger accountId) { this.accountId = accountId; }
|
||||
public String getFilePath() { return filePath; }
|
||||
public void setFilePath(String filePath) { this.filePath = filePath; }
|
||||
public String getOriginalName() { return originalName; }
|
||||
public void setOriginalName(String originalName) { this.originalName = originalName; }
|
||||
public String getFormat() { return format; }
|
||||
public void setFormat(String format) { this.format = format; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public Date getExpiresAt() { return expiresAt; }
|
||||
public void setExpiresAt(Date expiresAt) { this.expiresAt = expiresAt; }
|
||||
public Date getCreated() { return created; }
|
||||
public void setCreated(Date created) { this.created = created; }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package tech.easyflow.skill.entity;
|
||||
|
||||
import com.mybatisflex.annotation.Column;
|
||||
import com.mybatisflex.annotation.Id;
|
||||
import com.mybatisflex.annotation.KeyType;
|
||||
import com.mybatisflex.annotation.Table;
|
||||
import com.mybatisflex.core.handler.FastjsonTypeHandler;
|
||||
import tech.easyflow.common.entity.DateEntity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Skill 通用资源实体,统一承载文本与二进制包内文件。
|
||||
*/
|
||||
@Table("tb_skill_resource")
|
||||
public class SkillResource extends DateEntity implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id(keyType = KeyType.Generator, value = "snowFlakeId")
|
||||
private BigInteger id;
|
||||
@Column(tenantId = true)
|
||||
private BigInteger tenantId;
|
||||
private BigInteger skillId;
|
||||
private String path;
|
||||
private String normalizedPath;
|
||||
private String kind;
|
||||
private String language;
|
||||
private String mediaType;
|
||||
private Boolean isText;
|
||||
private String textContent;
|
||||
private String contentRef;
|
||||
private String contentHash;
|
||||
private Long size;
|
||||
@Column(typeHandler = FastjsonTypeHandler.class)
|
||||
private Map<String, Object> metadataJson = new LinkedHashMap<>();
|
||||
private Integer sortNo;
|
||||
private Date created;
|
||||
private BigInteger createdBy;
|
||||
private Date modified;
|
||||
private BigInteger modifiedBy;
|
||||
|
||||
public BigInteger getId() { return id; }
|
||||
public void setId(BigInteger id) { this.id = id; }
|
||||
public BigInteger getTenantId() { return tenantId; }
|
||||
public void setTenantId(BigInteger tenantId) { this.tenantId = tenantId; }
|
||||
public BigInteger getSkillId() { return skillId; }
|
||||
public void setSkillId(BigInteger skillId) { this.skillId = skillId; }
|
||||
public String getPath() { return path; }
|
||||
public void setPath(String path) { this.path = path; }
|
||||
public String getNormalizedPath() { return normalizedPath; }
|
||||
public void setNormalizedPath(String normalizedPath) { this.normalizedPath = normalizedPath; }
|
||||
public String getKind() { return kind; }
|
||||
public void setKind(String kind) { this.kind = kind; }
|
||||
public String getLanguage() { return language; }
|
||||
public void setLanguage(String language) { this.language = language; }
|
||||
public String getMediaType() { return mediaType; }
|
||||
public void setMediaType(String mediaType) { this.mediaType = mediaType; }
|
||||
public Boolean getIsText() { return isText; }
|
||||
public void setIsText(Boolean text) { isText = text; }
|
||||
public String getTextContent() { return textContent; }
|
||||
public void setTextContent(String textContent) { this.textContent = textContent; }
|
||||
public String getContentRef() { return contentRef; }
|
||||
public void setContentRef(String contentRef) { this.contentRef = contentRef; }
|
||||
public String getContentHash() { return contentHash; }
|
||||
public void setContentHash(String contentHash) { this.contentHash = contentHash; }
|
||||
public Long getSize() { return size; }
|
||||
public void setSize(Long size) { this.size = size; }
|
||||
public Map<String, Object> getMetadataJson() { return metadataJson; }
|
||||
public void setMetadataJson(Map<String, Object> metadataJson) { this.metadataJson = metadataJson == null ? new LinkedHashMap<>() : metadataJson; }
|
||||
public Integer getSortNo() { return sortNo; }
|
||||
public void setSortNo(Integer sortNo) { this.sortNo = sortNo; }
|
||||
@Override public Date getCreated() { return created; }
|
||||
@Override public void setCreated(Date created) { this.created = created; }
|
||||
public BigInteger getCreatedBy() { return createdBy; }
|
||||
public void setCreatedBy(BigInteger createdBy) { this.createdBy = createdBy; }
|
||||
@Override public Date getModified() { return modified; }
|
||||
@Override public void setModified(Date modified) { this.modified = modified; }
|
||||
public BigInteger getModifiedBy() { return modifiedBy; }
|
||||
public void setModifiedBy(BigInteger modifiedBy) { this.modifiedBy = modifiedBy; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tech.easyflow.skill.enums;
|
||||
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Skill 能力执行模式配置。
|
||||
*/
|
||||
public enum SkillCapabilityExecutionMode {
|
||||
SYNC,
|
||||
ASYNC;
|
||||
|
||||
/**
|
||||
* 解析执行模式,空值默认同步。
|
||||
*
|
||||
* @param value 模式编码
|
||||
* @return 执行模式
|
||||
*/
|
||||
public static SkillCapabilityExecutionMode fromOrDefault(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return SYNC;
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new BusinessException("不支持的能力执行模式");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tech.easyflow.skill.enums;
|
||||
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* MCP 工具选择模式。
|
||||
*/
|
||||
public enum SkillCapabilitySelectionMode {
|
||||
ALL,
|
||||
SELECTED;
|
||||
|
||||
/**
|
||||
* 解析选择模式,空值默认全部。
|
||||
*
|
||||
* @param value 模式编码
|
||||
* @return 选择模式
|
||||
*/
|
||||
public static SkillCapabilitySelectionMode fromOrDefault(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return ALL;
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new BusinessException("不支持的 MCP 工具选择模式");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package tech.easyflow.skill.enums;
|
||||
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Skill 可绑定的平台能力类型。
|
||||
*/
|
||||
public enum SkillCapabilityType {
|
||||
WORKFLOW,
|
||||
PLUGIN_ITEM,
|
||||
MCP;
|
||||
|
||||
/**
|
||||
* 解析能力类型。
|
||||
*
|
||||
* @param value 类型编码
|
||||
* @return 能力类型
|
||||
*/
|
||||
public static SkillCapabilityType from(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new BusinessException("能力类型不能为空");
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new BusinessException("不支持的能力类型");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,9 @@ public class SkillFileContent {
|
||||
private String content;
|
||||
private String language;
|
||||
private String mediaType;
|
||||
private Boolean isText;
|
||||
private Long size;
|
||||
private String downloadUrl;
|
||||
private String contentHash;
|
||||
|
||||
public String getPath() { return path; }
|
||||
public void setPath(String path) { this.path = path; }
|
||||
@@ -23,9 +24,10 @@ public class SkillFileContent {
|
||||
public void setLanguage(String language) { this.language = language; }
|
||||
public String getMediaType() { return mediaType; }
|
||||
public void setMediaType(String mediaType) { this.mediaType = mediaType; }
|
||||
public Boolean getIsText() { return isText; }
|
||||
public void setIsText(Boolean text) { isText = text; }
|
||||
public Long getSize() { return size; }
|
||||
public void setSize(Long size) { this.size = size; }
|
||||
public String getDownloadUrl() { return downloadUrl; }
|
||||
public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; }
|
||||
public String getContentHash() { return contentHash; }
|
||||
public void setContentHash(String contentHash) { this.contentHash = contentHash; }
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ public class SkillFileNode {
|
||||
private String type;
|
||||
private String language;
|
||||
private String mediaType;
|
||||
private Boolean isText;
|
||||
private Long size;
|
||||
private String contentHash;
|
||||
private List<SkillFileNode> children = new ArrayList<>();
|
||||
|
||||
public String getKey() { return key; }
|
||||
@@ -29,9 +31,12 @@ public class SkillFileNode {
|
||||
public void setLanguage(String language) { this.language = language; }
|
||||
public String getMediaType() { return mediaType; }
|
||||
public void setMediaType(String mediaType) { this.mediaType = mediaType; }
|
||||
public Boolean getIsText() { return isText; }
|
||||
public void setIsText(Boolean text) { isText = text; }
|
||||
public Long getSize() { return size; }
|
||||
public void setSize(Long size) { this.size = size; }
|
||||
public String getContentHash() { return contentHash; }
|
||||
public void setContentHash(String contentHash) { this.contentHash = contentHash; }
|
||||
public List<SkillFileNode> getChildren() { return children; }
|
||||
public void setChildren(List<SkillFileNode> children) { this.children = children == null ? new ArrayList<>() : children; }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package tech.easyflow.skill.file;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
/**
|
||||
* Skill 资源重命名请求。
|
||||
*/
|
||||
public class SkillFileRenameRequest {
|
||||
|
||||
private BigInteger skillId;
|
||||
private String path;
|
||||
private String newPath;
|
||||
private String expectedContentHash;
|
||||
|
||||
public BigInteger getSkillId() { return skillId; }
|
||||
public void setSkillId(BigInteger skillId) { this.skillId = skillId; }
|
||||
public String getPath() { return path; }
|
||||
public void setPath(String path) { this.path = path; }
|
||||
public String getNewPath() { return newPath; }
|
||||
public void setNewPath(String newPath) { this.newPath = newPath; }
|
||||
public String getExpectedContentHash() { return expectedContentHash; }
|
||||
public void setExpectedContentHash(String expectedContentHash) { this.expectedContentHash = expectedContentHash; }
|
||||
}
|
||||
@@ -10,6 +10,7 @@ public class SkillFileSaveRequest {
|
||||
private BigInteger skillId;
|
||||
private String path;
|
||||
private String content;
|
||||
private String expectedContentHash;
|
||||
|
||||
public BigInteger getSkillId() { return skillId; }
|
||||
public void setSkillId(BigInteger skillId) { this.skillId = skillId; }
|
||||
@@ -17,5 +18,6 @@ public class SkillFileSaveRequest {
|
||||
public void setPath(String path) { this.path = path; }
|
||||
public String getContent() { return content; }
|
||||
public void setContent(String content) { this.content = content; }
|
||||
public String getExpectedContentHash() { return expectedContentHash; }
|
||||
public void setExpectedContentHash(String expectedContentHash) { this.expectedContentHash = expectedContentHash; }
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,22 @@ public interface SkillFileService {
|
||||
*/
|
||||
SkillFileContent saveContent(SkillFileSaveRequest request);
|
||||
|
||||
/**
|
||||
* 创建 Skill 文本资源。
|
||||
*
|
||||
* @param request 创建请求
|
||||
* @return 创建后的文件内容
|
||||
*/
|
||||
SkillFileContent createTextFile(SkillFileSaveRequest request);
|
||||
|
||||
/**
|
||||
* 重命名 Skill 资源。
|
||||
*
|
||||
* @param request 重命名请求
|
||||
* @return 重命名后的文件内容
|
||||
*/
|
||||
SkillFileContent renameFile(SkillFileRenameRequest request);
|
||||
|
||||
/**
|
||||
* 删除逻辑文件。
|
||||
*
|
||||
@@ -44,6 +60,15 @@ public interface SkillFileService {
|
||||
*/
|
||||
void deleteFile(BigInteger skillId, String path);
|
||||
|
||||
/**
|
||||
* 按客户端读取到的内容 hash 删除逻辑文件。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param path 逻辑路径
|
||||
* @param expectedContentHash 客户端读取到的内容 hash
|
||||
*/
|
||||
void deleteFile(BigInteger skillId, String path, String expectedContentHash);
|
||||
|
||||
/**
|
||||
* 上传 asset 文件。
|
||||
*
|
||||
@@ -54,6 +79,30 @@ public interface SkillFileService {
|
||||
*/
|
||||
SkillFileContent uploadAsset(BigInteger skillId, String path, MultipartFile file);
|
||||
|
||||
/**
|
||||
* 上传任意安全的二进制资源。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param path 目标逻辑路径
|
||||
* @param file 上传文件
|
||||
* @return 保存后的资源内容
|
||||
*/
|
||||
SkillFileContent uploadResource(BigInteger skillId, String path, MultipartFile file);
|
||||
|
||||
/**
|
||||
* 上传或按内容 hash 原子替换二进制资源。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param path 目标逻辑路径
|
||||
* @param file 上传文件
|
||||
* @param expectedContentHash 已有路径的客户端内容 hash;新路径为空
|
||||
* @return 保存后的资源内容
|
||||
*/
|
||||
SkillFileContent uploadResource(BigInteger skillId,
|
||||
String path,
|
||||
MultipartFile file,
|
||||
String expectedContentHash);
|
||||
|
||||
/**
|
||||
* 打开 asset 输入流。
|
||||
*
|
||||
@@ -62,5 +111,13 @@ public interface SkillFileService {
|
||||
* @return asset 输入流
|
||||
*/
|
||||
InputStream openAsset(BigInteger skillId, String path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开二进制资源输入流。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param path 逻辑路径
|
||||
* @return 输入流,调用方负责关闭
|
||||
*/
|
||||
InputStream openResource(BigInteger skillId, String path);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,492 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import com.easyagents.skill.model.SkillPackageLimits;
|
||||
import com.easyagents.skill.exception.SkillException;
|
||||
import com.easyagents.skill.exception.SkillPackageException;
|
||||
import com.easyagents.skill.util.SkillPaths;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipException;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
/**
|
||||
* 将 EasyFlow Bundle 安全转换为标准 Skill ZIP,并提取平台 manifest。
|
||||
*/
|
||||
@Component
|
||||
public class EasyFlowBundleReader {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EasyFlowBundleReader.class);
|
||||
|
||||
private final EasyFlowSkillManifestCodec manifestCodec;
|
||||
|
||||
/**
|
||||
* 创建 EasyFlow Bundle 读取器。
|
||||
*
|
||||
* @param manifestCodec manifest 编解码器
|
||||
*/
|
||||
public EasyFlowBundleReader(EasyFlowSkillManifestCodec manifestCodec) {
|
||||
this.manifestCodec = manifestCodec;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 ZIP 是否包含 EasyFlow manifest。
|
||||
*
|
||||
* @param inputStream ZIP 输入流
|
||||
* @return 包含时为 true
|
||||
*/
|
||||
public boolean containsManifest(InputStream inputStream) {
|
||||
SkillPackageLimits limits = SkillPackageLimits.defaults();
|
||||
Path packageFile = null;
|
||||
try {
|
||||
packageFile = copyCompressedPackage(inputStream, limits.getMaxCompressedPackageBytes());
|
||||
try (ZipFile zip = new ZipFile(packageFile)) {
|
||||
Enumeration<ZipArchiveEntry> entries = zip.getEntries();
|
||||
int count = 0;
|
||||
long declaredTotalBytes = 0;
|
||||
long actualTotalBytes = 0;
|
||||
boolean containsManifest = false;
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipArchiveEntry entry = entries.nextElement();
|
||||
if (++count > limits.getMaxEntryCount() + 1) {
|
||||
throw new BusinessException("EasyFlow Skill 包文件数量超过限制");
|
||||
}
|
||||
String fullPath = validateCentralEntry(zip, entry, limits);
|
||||
if (entry.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
declaredTotalBytes = safeAdd(
|
||||
declaredTotalBytes, entry.getSize(), limits.getMaxTotalUncompressedBytes());
|
||||
long singleLimit = EasyFlowSkillManifestCodec.MANIFEST_PATH.equals(fullPath)
|
||||
? EasyFlowSkillManifestCodec.MAX_MANIFEST_BYTES : limits.getMaxBinaryFileBytes();
|
||||
long actualSize = readAndVerifyEntry(zip, entry, fullPath, singleLimit);
|
||||
actualTotalBytes = safeAdd(
|
||||
actualTotalBytes, actualSize, limits.getMaxTotalUncompressedBytes());
|
||||
containsManifest |= EasyFlowSkillManifestCodec.MANIFEST_PATH.equals(fullPath);
|
||||
}
|
||||
return containsManifest;
|
||||
}
|
||||
} catch (ZipException exception) {
|
||||
throw invalidZip(exception);
|
||||
} catch (IOException exception) {
|
||||
ZipException zipException = findZipException(exception);
|
||||
if (zipException != null) {
|
||||
throw invalidZip(zipException);
|
||||
}
|
||||
throw new BusinessException(500, 500, "读取 Skill 包格式失败", exception);
|
||||
} finally {
|
||||
deleteQuietly(packageFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取 manifest,并将 skills/ 前缀下的标准包内容流式写到临时 ZIP。
|
||||
*
|
||||
* @param inputStream EasyFlow Bundle 输入流
|
||||
* @return 可自动清理的准备结果
|
||||
*/
|
||||
public PreparedBundle prepare(InputStream inputStream) {
|
||||
SkillPackageLimits limits = SkillPackageLimits.defaults();
|
||||
Path packageFile = null;
|
||||
Path standardZip = null;
|
||||
try {
|
||||
packageFile = copyCompressedPackage(inputStream, limits.getMaxCompressedPackageBytes());
|
||||
standardZip = Files.createTempFile("easyflow-bundle-standard-", ".zip");
|
||||
byte[] manifestBytes = null;
|
||||
long declaredTotalBytes = 0;
|
||||
long actualTotalBytes = 0;
|
||||
int entryCount = 0;
|
||||
Set<String> paths = new HashSet<>();
|
||||
Set<String> collisionKeys = new HashSet<>();
|
||||
try (ZipFile input = new ZipFile(packageFile);
|
||||
ZipOutputStream output = new ZipOutputStream(
|
||||
Files.newOutputStream(standardZip, StandardOpenOption.TRUNCATE_EXISTING),
|
||||
StandardCharsets.UTF_8)) {
|
||||
Enumeration<ZipArchiveEntry> entries = input.getEntries();
|
||||
byte[] buffer = new byte[8192];
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipArchiveEntry entry = entries.nextElement();
|
||||
if (++entryCount > limits.getMaxEntryCount() + 1) {
|
||||
throw new BusinessException("EasyFlow Skill 包文件数量超过限制");
|
||||
}
|
||||
String fullPath = validateCentralEntry(input, entry, limits);
|
||||
if (entry.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
declaredTotalBytes = safeAdd(
|
||||
declaredTotalBytes, entry.getSize(), limits.getMaxTotalUncompressedBytes());
|
||||
if (EasyFlowSkillManifestCodec.MANIFEST_PATH.equals(fullPath)) {
|
||||
if (manifestBytes != null) {
|
||||
throw new BusinessException("EasyFlow Skill 包包含重复 manifest");
|
||||
}
|
||||
try (InputStream entryInput = input.getInputStream(entry)) {
|
||||
manifestBytes = readLimited(entryInput, EasyFlowSkillManifestCodec.MAX_MANIFEST_BYTES);
|
||||
}
|
||||
verifyCrc(entry, crc32(manifestBytes), fullPath);
|
||||
actualTotalBytes = safeAdd(actualTotalBytes, manifestBytes.length,
|
||||
limits.getMaxTotalUncompressedBytes());
|
||||
if (manifestBytes.length != entry.getSize()) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 实际大小与目录信息不一致");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!fullPath.startsWith("skills/")) {
|
||||
throw new BusinessException("EasyFlow Skill 包根目录只能包含 manifest 和 skills/");
|
||||
}
|
||||
String relativePath = normalizePackagePath(fullPath.substring("skills/".length()));
|
||||
if (!paths.add(relativePath) || !collisionKeys.add(SkillPaths.collisionKey(relativePath))) {
|
||||
throw new BusinessException("EasyFlow Skill 包存在重复或大小写冲突路径:" + relativePath);
|
||||
}
|
||||
ZipEntry outputEntry = new ZipEntry(relativePath);
|
||||
outputEntry.setTime(0L);
|
||||
output.putNextEntry(outputEntry);
|
||||
long entryBytes = 0;
|
||||
CRC32 crc = new CRC32();
|
||||
try (InputStream entryInput = input.getInputStream(entry)) {
|
||||
int length;
|
||||
while ((length = entryInput.read(buffer)) >= 0) {
|
||||
entryBytes += length;
|
||||
if (entryBytes > limits.getMaxBinaryFileBytes()) {
|
||||
throw new BusinessException("EasyFlow Skill 包单文件解压大小超过限制");
|
||||
}
|
||||
actualTotalBytes = safeAdd(actualTotalBytes, length,
|
||||
limits.getMaxTotalUncompressedBytes());
|
||||
crc.update(buffer, 0, length);
|
||||
output.write(buffer, 0, length);
|
||||
}
|
||||
}
|
||||
if (entryBytes != entry.getSize()) {
|
||||
throw new BusinessException("EasyFlow Skill 包条目实际大小与目录信息不一致");
|
||||
}
|
||||
verifyCrc(entry, crc.getValue(), fullPath);
|
||||
output.closeEntry();
|
||||
}
|
||||
output.finish();
|
||||
}
|
||||
if (manifestBytes == null) {
|
||||
throw new BusinessException("EasyFlow Skill 包缺少 easyflow-manifest.json");
|
||||
}
|
||||
return new PreparedBundle(standardZip, manifestCodec.decode(manifestBytes));
|
||||
} catch (RuntimeException | IOException exception) {
|
||||
deleteQuietly(standardZip);
|
||||
if (exception instanceof BusinessException businessException) {
|
||||
throw businessException;
|
||||
}
|
||||
if (exception instanceof SkillPackageException skillPackageException) {
|
||||
throw skillPackageException;
|
||||
}
|
||||
ZipException zipException = findZipException(exception);
|
||||
if (zipException != null) {
|
||||
throw invalidZip(zipException);
|
||||
}
|
||||
LOG.error("解析 EasyFlow Skill Bundle 失败", exception);
|
||||
throw new BusinessException(500, 500, "解析 EasyFlow Skill Bundle 失败", exception);
|
||||
}
|
||||
finally {
|
||||
deleteQuietly(packageFile);
|
||||
}
|
||||
}
|
||||
|
||||
private Path copyCompressedPackage(InputStream input, long limit) throws IOException {
|
||||
if (input == null) {
|
||||
throw new BusinessException("Skill 包输入流不能为空");
|
||||
}
|
||||
Path target = Files.createTempFile("easyflow-bundle-compressed-", ".zip");
|
||||
try (OutputStream output = Files.newOutputStream(target, StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
byte[] buffer = new byte[8192];
|
||||
long total = 0;
|
||||
int length;
|
||||
while ((length = input.read(buffer)) >= 0) {
|
||||
total += length;
|
||||
if (total > limit) {
|
||||
throw new BusinessException(413, 4131,
|
||||
"Skill 包压缩文件超过 " + limit + " 字节限制");
|
||||
}
|
||||
output.write(buffer, 0, length);
|
||||
}
|
||||
return target;
|
||||
} catch (RuntimeException | IOException exception) {
|
||||
deleteQuietly(target);
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验外层 ZIP 中央目录元数据并返回规范化路径。
|
||||
*
|
||||
* @param zip ZIP 文件
|
||||
* @param entry ZIP 条目
|
||||
* @param limits 包安全限制
|
||||
* @return 规范化包内路径
|
||||
* @throws BusinessException 条目类型、路径、大小或压缩比不安全
|
||||
* @throws SkillPackageException 原始文件名或 CRC 元数据不合法
|
||||
*/
|
||||
private String validateCentralEntry(ZipFile zip, ZipArchiveEntry entry, SkillPackageLimits limits) {
|
||||
if (!zip.canReadEntryData(entry)) {
|
||||
throw new BusinessException("Skill 包包含加密或不支持的压缩条目");
|
||||
}
|
||||
if (entry.isUnixSymlink()) {
|
||||
throw new BusinessException("Skill 包不允许包含符号链接");
|
||||
}
|
||||
String path = strictUtf8EntryName(entry);
|
||||
if (entry.isDirectory()) {
|
||||
while (path.endsWith("/")) {
|
||||
path = path.substring(0, path.length() - 1);
|
||||
}
|
||||
if (path.isBlank()) {
|
||||
throw new BusinessException("Skill 包包含非法空目录路径");
|
||||
}
|
||||
}
|
||||
String normalized = normalizePackagePath(path);
|
||||
if (normalized.length() > limits.getMaxPathLength()
|
||||
|| normalized.split("/").length > limits.getMaxPathDepth()) {
|
||||
throw new BusinessException("Skill 包路径长度或层级超过限制");
|
||||
}
|
||||
long size = entry.getSize();
|
||||
long compressedSize = entry.getCompressedSize();
|
||||
if (size < 0 || compressedSize < 0) {
|
||||
throw new BusinessException("Skill 包条目缺少可靠大小信息");
|
||||
}
|
||||
if (!entry.isDirectory() && entry.getCrc() < 0) {
|
||||
throw packageError("UNKNOWN_ENTRY_CRC", normalized,
|
||||
"EasyFlow Skill 包条目缺少中央目录 CRC");
|
||||
}
|
||||
double ratio = size == 0 ? 0D : (double) size / Math.max(1L, compressedSize);
|
||||
if (ratio > limits.getMaxCompressionRatio()) {
|
||||
throw new BusinessException("Skill 包条目压缩比超过安全限制");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 严格按 UTF-8 解码 ZIP 中央目录的原始文件名字节,并拒绝 Unicode extra field 造成的歧义。
|
||||
*
|
||||
* @param entry ZIP 条目
|
||||
* @return 唯一的 UTF-8 文件名
|
||||
* @throws SkillPackageException 原始文件名字节非法或与解析结果不一致
|
||||
*/
|
||||
private String strictUtf8EntryName(ZipArchiveEntry entry) {
|
||||
byte[] rawName = entry.getRawName();
|
||||
if (rawName == null) {
|
||||
throw packageError("INVALID_UTF8_ENTRY_NAME", entry.getName(),
|
||||
"EasyFlow Skill 包条目缺少原始文件名字节");
|
||||
}
|
||||
try {
|
||||
String decodedName = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(rawName))
|
||||
.toString();
|
||||
if (!decodedName.equals(entry.getName())) {
|
||||
throw packageError("INVALID_UTF8_ENTRY_NAME", entry.getName(),
|
||||
"EasyFlow Skill 包条目文件名必须具有唯一 UTF-8 表示");
|
||||
}
|
||||
return decodedName;
|
||||
} catch (CharacterCodingException exception) {
|
||||
throw new SkillPackageException("INVALID_UTF8_ENTRY_NAME", entry.getName(),
|
||||
"EasyFlow Skill 包条目文件名不是合法 UTF-8", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式读取单个外层 ZIP 条目,并同时校验实际大小与中央目录 CRC。
|
||||
*
|
||||
* @param zip ZIP 文件
|
||||
* @param entry ZIP 条目
|
||||
* @param path 已校验路径
|
||||
* @param sizeLimit 单文件解压上限
|
||||
* @return 实际解压字节数
|
||||
* @throws IOException 条目读取失败
|
||||
* @throws SkillPackageException CRC 不匹配
|
||||
*/
|
||||
private long readAndVerifyEntry(ZipFile zip,
|
||||
ZipArchiveEntry entry,
|
||||
String path,
|
||||
long sizeLimit) throws IOException {
|
||||
CRC32 crc = new CRC32();
|
||||
byte[] buffer = new byte[8192];
|
||||
long actualSize = 0;
|
||||
try (InputStream input = zip.getInputStream(entry)) {
|
||||
int length;
|
||||
while ((length = input.read(buffer)) >= 0) {
|
||||
actualSize += length;
|
||||
if (actualSize > sizeLimit) {
|
||||
throw new BusinessException(413, 4131, "EasyFlow Skill 包单文件解压大小超过限制");
|
||||
}
|
||||
crc.update(buffer, 0, length);
|
||||
}
|
||||
}
|
||||
if (actualSize != entry.getSize()) {
|
||||
throw packageError("ENTRY_SIZE_MISMATCH", path,
|
||||
"EasyFlow Skill 包条目实际大小与中央目录不一致");
|
||||
}
|
||||
verifyCrc(entry, crc.getValue(), path);
|
||||
return actualSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 ZIP 条目 CRC-32。
|
||||
*
|
||||
* @param entry ZIP 条目
|
||||
* @param actualCrc 实际内容 CRC-32
|
||||
* @param path 包内路径
|
||||
* @throws SkillPackageException CRC 与中央目录不一致
|
||||
*/
|
||||
private void verifyCrc(ZipArchiveEntry entry, long actualCrc, String path) {
|
||||
if (entry.getCrc() != actualCrc) {
|
||||
throw packageError("CRC_MISMATCH", path,
|
||||
"EasyFlow Skill 包条目 CRC 与实际内容不一致");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算字节内容的 CRC-32。
|
||||
*
|
||||
* @param bytes 内容字节
|
||||
* @return CRC-32
|
||||
*/
|
||||
private long crc32(byte[] bytes) {
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(bytes);
|
||||
return crc.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带稳定错误码和包内路径的 Skill 包异常。
|
||||
*
|
||||
* @param code 稳定错误码
|
||||
* @param path 包内路径
|
||||
* @param message 错误信息
|
||||
* @return Skill 包异常
|
||||
*/
|
||||
private SkillPackageException packageError(String code, String path, String message) {
|
||||
return new SkillPackageException(code, path, message);
|
||||
}
|
||||
|
||||
private long safeAdd(long current, long value, long limit) {
|
||||
if (value < 0 || current > limit - value) {
|
||||
throw new BusinessException("EasyFlow Skill 包解压总大小超过限制");
|
||||
}
|
||||
return current + value;
|
||||
}
|
||||
|
||||
private String normalizePackagePath(String path) {
|
||||
try {
|
||||
return SkillPaths.normalize(path);
|
||||
} catch (SkillException exception) {
|
||||
throw new BusinessException("Skill 包路径不合法:" + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] readLimited(InputStream input, long limit) throws IOException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[8192];
|
||||
long total = 0;
|
||||
int length;
|
||||
while ((length = input.read(buffer)) >= 0) {
|
||||
total += length;
|
||||
if (total > limit) {
|
||||
throw new BusinessException(413, 4131, "EasyFlow Skill manifest 超过 1 MiB 限制");
|
||||
}
|
||||
output.write(buffer, 0, length);
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
|
||||
private BusinessException invalidZip(ZipException exception) {
|
||||
return new BusinessException(400, 4001, "Skill 包不是有效的 ZIP 文件", exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* 沿异常链查找被 Commons Compress 包装的 ZIP 格式异常。
|
||||
*
|
||||
* @param exception 外层读取异常
|
||||
* @return ZIP 格式异常;不存在时返回 {@code null}
|
||||
*/
|
||||
private ZipException findZipException(Throwable exception) {
|
||||
Throwable current = exception;
|
||||
for (int depth = 0; current != null && depth < 32; depth++) {
|
||||
if (current instanceof ZipException zipException) {
|
||||
return zipException;
|
||||
}
|
||||
if (current == current.getCause()) {
|
||||
break;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void deleteQuietly(Path path) {
|
||||
if (path == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException exception) {
|
||||
LOG.warn("清理 EasyFlow Bundle 临时标准包失败,path={}", path, exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EasyFlow Bundle 准备结果。
|
||||
*/
|
||||
public final class PreparedBundle implements AutoCloseable {
|
||||
|
||||
private final Path standardZip;
|
||||
private final Map<String, Object> manifest;
|
||||
|
||||
private PreparedBundle(Path standardZip, Map<String, Object> manifest) {
|
||||
this.standardZip = standardZip;
|
||||
this.manifest = manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开转换后的标准 ZIP。
|
||||
*
|
||||
* @return 输入流
|
||||
* @throws IOException 临时文件无法读取
|
||||
*/
|
||||
public InputStream openStandardZip() throws IOException {
|
||||
return Files.newInputStream(standardZip);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已做基础版本校验的 manifest。
|
||||
*
|
||||
* @return manifest
|
||||
*/
|
||||
public Map<String, Object> getManifest() {
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除转换临时文件。
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
deleteQuietly(standardZip);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.capability.SkillCapabilityTarget;
|
||||
import tech.easyflow.skill.capability.SkillCapabilityTargetAccessService;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityExecutionMode;
|
||||
import tech.easyflow.skill.enums.SkillCapabilitySelectionMode;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
import tech.easyflow.skill.security.SkillCredentialValueGuard;
|
||||
import tech.easyflow.skill.security.SkillPortableTargetSanitizer;
|
||||
import tech.easyflow.skill.security.SkillSensitiveConfigSanitizer;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* EasyFlow Skill Bundle manifest 的版本化白名单编解码器。
|
||||
*/
|
||||
@Component
|
||||
public class EasyFlowSkillManifestCodec {
|
||||
|
||||
private static final Set<String> ROOT_FIELDS = Set.of("schemaVersion", "skills");
|
||||
private static final Set<String> SKILL_FIELDS = Set.of("packageRoot", "packageHash", "capabilities");
|
||||
private static final Set<String> BINDING_FIELDS = Set.of(
|
||||
"bindingKey", "capabilityType", "runtimeName", "enabled", "selectionMode",
|
||||
"selectedToolNames", "executionMode", "hitlEnabled", "hitlConfig", "options", "sortNo",
|
||||
"targetLogicalRef", "targetStatus", "targetName", "targetRevision");
|
||||
private static final Pattern RUNTIME_NAME_PATTERN = Pattern.compile("^[A-Za-z][A-Za-z0-9_-]{0,63}$");
|
||||
private static final Pattern MCP_TOOL_NAME_PATTERN = Pattern.compile("^[A-Za-z][A-Za-z0-9_.-]{0,127}$");
|
||||
|
||||
/** EasyFlow Bundle manifest 固定路径。 */
|
||||
public static final String MANIFEST_PATH = "easyflow-manifest.json";
|
||||
/** manifest 最大字节数。 */
|
||||
public static final long MAX_MANIFEST_BYTES = 1024L * 1024;
|
||||
/** 单个增强包最大 Skill 数。 */
|
||||
public static final int MAX_SKILLS = 100;
|
||||
/** packageRoot 最大字符数。 */
|
||||
public static final int MAX_PACKAGE_ROOT_LENGTH = 128;
|
||||
/** 单个 Skill 最大能力绑定数。 */
|
||||
public static final int MAX_BINDINGS_PER_SKILL = 200;
|
||||
/** 单个增强包最大能力绑定总数。 */
|
||||
public static final int MAX_TOTAL_BINDINGS = 1_000;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SkillCapabilityTargetAccessService targetAccessService;
|
||||
|
||||
/**
|
||||
* 创建 manifest 编解码器。
|
||||
*
|
||||
* @param objectMapper JSON 映射器
|
||||
* @param targetAccessService 能力目标授权服务
|
||||
*/
|
||||
public EasyFlowSkillManifestCodec(ObjectMapper objectMapper,
|
||||
SkillCapabilityTargetAccessService targetAccessService) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.targetAccessService = targetAccessService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Skill 列表编码为不含凭据的 manifest。
|
||||
*
|
||||
* @param skills Skill 详情
|
||||
* @return UTF-8 JSON
|
||||
*/
|
||||
public byte[] encode(List<Skill> skills) {
|
||||
if (skills == null || skills.size() > MAX_SKILLS) {
|
||||
throw new BusinessException("单个 EasyFlow Skill Bundle 最多包含 " + MAX_SKILLS + " 个 Skill");
|
||||
}
|
||||
Map<String, Object> manifest = new LinkedHashMap<>();
|
||||
manifest.put("schemaVersion", "1.0");
|
||||
List<Map<String, Object>> skillItems = new ArrayList<>();
|
||||
int totalBindings = 0;
|
||||
for (int skillIndex = 0; skillIndex < skills.size(); skillIndex++) {
|
||||
Skill skill = skills.get(skillIndex);
|
||||
String skillPath = "skills[" + skillIndex + "]";
|
||||
if (skill == null) {
|
||||
throw new SkillManifestValidationException("SKILL_EMPTY", skillPath,
|
||||
"EasyFlow Skill manifest 的 Skill 不能为空");
|
||||
}
|
||||
String packageRoot = boundedRequiredString(
|
||||
skill.getName(), skillPath + ".packageRoot", MAX_PACKAGE_ROOT_LENGTH);
|
||||
String packageHash = boundedRequiredString(
|
||||
skill.getPackageHash(), skillPath + ".packageHash", 128);
|
||||
validatePortableMetadata(packageRoot, skillPath + ".packageRoot");
|
||||
validatePortableMetadata(packageHash, skillPath + ".packageHash");
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("packageRoot", packageRoot);
|
||||
item.put("packageHash", packageHash);
|
||||
List<Map<String, Object>> bindings = new ArrayList<>();
|
||||
List<SkillCapabilityBinding> sourceBindings = skill.getCapabilityBindings() == null
|
||||
? List.of() : skill.getCapabilityBindings();
|
||||
if (sourceBindings.size() > MAX_BINDINGS_PER_SKILL
|
||||
|| (totalBindings += sourceBindings.size()) > MAX_TOTAL_BINDINGS) {
|
||||
throw new BusinessException("EasyFlow Skill Bundle 能力绑定数量超过限制");
|
||||
}
|
||||
for (int index = 0; index < sourceBindings.size(); index++) {
|
||||
bindings.add(bindingManifest(skillIndex, packageRoot, index, sourceBindings.get(index)));
|
||||
}
|
||||
item.put("capabilities", bindings);
|
||||
skillItems.add(item);
|
||||
}
|
||||
manifest.put("skills", skillItems);
|
||||
validateCredentialFreeTree(manifest, "");
|
||||
validateSkills(skillItems);
|
||||
try {
|
||||
byte[] bytes = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(manifest);
|
||||
if (bytes.length > MAX_MANIFEST_BYTES) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 超过 1 MiB 限制");
|
||||
}
|
||||
return bytes;
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new BusinessException(500, 500, "生成 EasyFlow Skill manifest 失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码并校验 manifest 基础版本结构。
|
||||
*
|
||||
* @param bytes manifest 字节
|
||||
* @return manifest 对象
|
||||
*/
|
||||
public Map<String, Object> decode(byte[] bytes) {
|
||||
if (bytes == null || bytes.length == 0 || bytes.length > MAX_MANIFEST_BYTES) {
|
||||
if (bytes != null && bytes.length > MAX_MANIFEST_BYTES) {
|
||||
throw new BusinessException(413, 4131, "EasyFlow Skill manifest 超过 1 MiB 限制");
|
||||
}
|
||||
throw new BusinessException("EasyFlow Skill manifest 不能为空");
|
||||
}
|
||||
try {
|
||||
Map<String, Object> manifest = objectMapper.readerFor(new TypeReference<Map<String, Object>>() { })
|
||||
.with(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
|
||||
.readValue(bytes);
|
||||
if (manifest == null) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 根对象不能为空");
|
||||
}
|
||||
// 在枚举解析和错误消息构造前先覆盖整个平台 manifest 字符串面,避免敏感值回显。
|
||||
validateCredentialFreeTree(manifest, "");
|
||||
assertOnlyFields(manifest, ROOT_FIELDS, "根对象");
|
||||
if (!"1.0".equals(String.valueOf(manifest.get("schemaVersion")))) {
|
||||
throw new BusinessException("不支持的 EasyFlow Skill manifest 版本");
|
||||
}
|
||||
if (!(manifest.get("skills") instanceof List<?> skills)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 缺少 skills 列表");
|
||||
}
|
||||
validateSkills(skills);
|
||||
return manifest;
|
||||
} catch (java.io.IOException exception) {
|
||||
throw new BusinessException("EasyFlow Skill manifest JSON 格式不正确");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateSkills(List<?> skills) {
|
||||
if (skills.size() > MAX_SKILLS) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 最多包含 " + MAX_SKILLS + " 个 Skill");
|
||||
}
|
||||
java.util.Set<String> roots = new java.util.HashSet<>();
|
||||
java.util.Set<String> bindingKeys = new java.util.HashSet<>();
|
||||
int totalBindings = 0;
|
||||
for (int skillIndex = 0; skillIndex < skills.size(); skillIndex++) {
|
||||
String skillPath = "skills[" + skillIndex + "]";
|
||||
Object source = skills.get(skillIndex);
|
||||
if (!(source instanceof Map<?, ?> skill)) {
|
||||
throw new SkillManifestValidationException("SKILL_INVALID", skillPath,
|
||||
"EasyFlow Skill manifest 的 Skill 项格式不正确");
|
||||
}
|
||||
assertOnlyFields(skill, SKILL_FIELDS, skillPath);
|
||||
String packageRoot = boundedRequiredString(
|
||||
skill.get("packageRoot"), skillPath + ".packageRoot", MAX_PACKAGE_ROOT_LENGTH);
|
||||
validatePortableMetadata(packageRoot, skillPath + ".packageRoot");
|
||||
validatePortableMetadata(boundedRequiredString(
|
||||
skill.get("packageHash"), skillPath + ".packageHash", 128),
|
||||
skillPath + ".packageHash");
|
||||
if (!roots.add(packageRoot)) {
|
||||
throw new SkillManifestValidationException("PACKAGE_ROOT_DUPLICATE",
|
||||
skillPath + ".packageRoot", "EasyFlow Skill manifest 存在重复 packageRoot");
|
||||
}
|
||||
Object capabilitiesValue = skill.get("capabilities");
|
||||
if (!(capabilitiesValue instanceof List<?> capabilities)) {
|
||||
throw new SkillManifestValidationException("CAPABILITIES_REQUIRED",
|
||||
skillPath + ".capabilities", "EasyFlow Skill manifest 缺少 capabilities 列表");
|
||||
}
|
||||
if (capabilities.size() > MAX_BINDINGS_PER_SKILL) {
|
||||
throw new BusinessException("单个 Skill 的能力绑定不能超过 " + MAX_BINDINGS_PER_SKILL + " 个");
|
||||
}
|
||||
totalBindings += capabilities.size();
|
||||
if (totalBindings > MAX_TOTAL_BINDINGS) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 能力绑定总数不能超过 "
|
||||
+ MAX_TOTAL_BINDINGS + " 个");
|
||||
}
|
||||
for (int bindingIndex = 0; bindingIndex < capabilities.size(); bindingIndex++) {
|
||||
Object bindingValue = capabilities.get(bindingIndex);
|
||||
String bindingPath = skillPath + ".capabilities[" + bindingIndex + "]";
|
||||
if (!(bindingValue instanceof Map<?, ?> binding)) {
|
||||
throw new SkillManifestValidationException("CAPABILITY_INVALID", bindingPath,
|
||||
"EasyFlow Skill manifest 的能力绑定格式不正确");
|
||||
}
|
||||
assertOnlyFields(binding, BINDING_FIELDS, bindingPath);
|
||||
String bindingKey = boundedRequiredString(
|
||||
binding.get("bindingKey"), bindingPath + ".bindingKey", 256);
|
||||
validatePortableMetadata(bindingKey, bindingPath + ".bindingKey");
|
||||
if (!bindingKeys.add(bindingKey)) {
|
||||
throw new SkillManifestValidationException("BINDING_KEY_DUPLICATE",
|
||||
bindingPath + ".bindingKey", "EasyFlow Skill manifest 存在重复 bindingKey");
|
||||
}
|
||||
SkillCapabilityType type = parseCapabilityType(binding.get("capabilityType"), bindingPath);
|
||||
String runtimeName = boundedRequiredString(
|
||||
binding.get("runtimeName"), bindingPath + ".runtimeName", 64);
|
||||
if (!RUNTIME_NAME_PATTERN.matcher(runtimeName).matches()) {
|
||||
throw new SkillManifestValidationException("RUNTIME_NAME_INVALID",
|
||||
bindingPath + ".runtimeName", "EasyFlow Skill manifest 的运行时名称格式不正确");
|
||||
}
|
||||
String logicalRef = boundedRequiredString(
|
||||
binding.get("targetLogicalRef"), bindingPath + ".targetLogicalRef", 512);
|
||||
validateLogicalRef(type, logicalRef, bindingPath + ".targetLogicalRef");
|
||||
validateSelectionMode(boundedOptionalString(
|
||||
binding.get("selectionMode"), bindingPath + ".selectionMode", 16), bindingPath);
|
||||
validateExecutionMode(boundedOptionalString(
|
||||
binding.get("executionMode"), bindingPath + ".executionMode", 16), bindingPath);
|
||||
validatePortableMetadata(boundedOptionalString(
|
||||
binding.get("targetStatus"), bindingPath + ".targetStatus", 32),
|
||||
bindingPath + ".targetStatus");
|
||||
validatePortableMetadata(boundedOptionalString(
|
||||
binding.get("targetName"), bindingPath + ".targetName", 256),
|
||||
bindingPath + ".targetName");
|
||||
validatePortableMetadata(boundedOptionalString(
|
||||
binding.get("targetRevision"), bindingPath + ".targetRevision", 256),
|
||||
bindingPath + ".targetRevision");
|
||||
validateBoolean(binding.get("enabled"), bindingPath + ".enabled");
|
||||
validateBoolean(binding.get("hitlEnabled"), bindingPath + ".hitlEnabled");
|
||||
validateInteger(binding.get("sortNo"), bindingPath + ".sortNo");
|
||||
validateStringList(binding.get("selectedToolNames"), bindingPath + ".selectedToolNames");
|
||||
validateSafeConfig(binding.get("hitlConfig"), true, bindingPath + ".hitlConfig");
|
||||
validateSafeConfig(binding.get("options"), false, bindingPath + ".options");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void assertOnlyFields(Map<?, ?> source, Set<String> allowed, String path) {
|
||||
for (Object key : source.keySet()) {
|
||||
if (!(key instanceof String field) || !allowed.contains(field)) {
|
||||
throw new SkillManifestValidationException("FIELD_NOT_ALLOWED", path,
|
||||
"EasyFlow Skill manifest 包含未允许字段");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateBoolean(Object value, String field) {
|
||||
if (value != null && !(value instanceof Boolean)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 类型不正确");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateInteger(Object value, String field) {
|
||||
if (value != null && (!(value instanceof Number number)
|
||||
|| number.doubleValue() != number.longValue()
|
||||
|| number.longValue() < Integer.MIN_VALUE || number.longValue() > Integer.MAX_VALUE)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 类型不正确");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateStringList(Object value, String field) {
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
if (!(value instanceof List<?> values) || values.size() > 200) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 类型不正确或超过限制");
|
||||
}
|
||||
for (int index = 0; index < values.size(); index++) {
|
||||
Object item = values.get(index);
|
||||
if (!(item instanceof String text) || !MCP_TOOL_NAME_PATTERN.matcher(text).matches()) {
|
||||
throw new SkillManifestValidationException("MCP_TOOL_NAME_INVALID",
|
||||
field + "[" + index + "]", "EasyFlow Skill manifest 包含非法工具名");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateLogicalRef(SkillCapabilityType type, String logicalRef, String path) {
|
||||
if (!SkillPortableTargetSanitizer.isSafeLogicalRef(type, logicalRef)) {
|
||||
throw new SkillManifestValidationException("TARGET_LOGICAL_REF_INVALID", path,
|
||||
"EasyFlow Skill manifest 的目标逻辑引用格式不正确");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 manifest 可移植元数据不含本机路径或认证材料。
|
||||
*
|
||||
* @param value 元数据值
|
||||
* @param field 字段名
|
||||
*/
|
||||
private void validatePortableMetadata(String value, String field) {
|
||||
if (SkillCredentialValueGuard.containsCredential(value)) {
|
||||
throw new SkillManifestValidationException("SENSITIVE_VALUE_DETECTED", field,
|
||||
"EasyFlow Skill manifest 不能包含认证凭据");
|
||||
}
|
||||
if (!SkillPortableTargetSanitizer.isSafePortableMetadata(value)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 包含不安全内容");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateSafeConfig(Object value, boolean hitl, String field) {
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
if (!(value instanceof Map<?, ?> raw)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 类型不正确");
|
||||
}
|
||||
Map<String, Object> source = new LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> entry : raw.entrySet()) {
|
||||
if (!(entry.getKey() instanceof String key)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 包含非法键");
|
||||
}
|
||||
source.put(key, entry.getValue());
|
||||
}
|
||||
Map<String, Object> safe = hitl
|
||||
? SkillSensitiveConfigSanitizer.sanitizeHitl(source)
|
||||
: SkillSensitiveConfigSanitizer.sanitizeOptions(source);
|
||||
if (!safe.equals(source)) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 包含未允许或敏感配置");
|
||||
}
|
||||
if (hitl) {
|
||||
for (Map.Entry<String, Object> entry : safe.entrySet()) {
|
||||
int maxLength = "confirmLabel".equals(entry.getKey()) || "cancelLabel".equals(entry.getKey())
|
||||
? 128 : 2_000;
|
||||
if (!(entry.getValue() instanceof String text) || text.length() > maxLength) {
|
||||
throw new SkillManifestValidationException("HITL_CONFIG_VALUE_INVALID",
|
||||
field + "." + entry.getKey(),
|
||||
"EasyFlow Skill manifest 的 HITL 配置字段类型或长度不正确");
|
||||
}
|
||||
if (SkillCredentialValueGuard.containsCredential(text)) {
|
||||
throw new SkillManifestValidationException("SENSITIVE_VALUE_DETECTED",
|
||||
field + "." + entry.getKey(),
|
||||
"EasyFlow Skill manifest 的 HITL 配置不能包含认证凭据");
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
validateOptionValue(safe, "timeoutMs", field);
|
||||
validateOptionValue(safe, "retryCount", field);
|
||||
for (String key : List.of("async", "readOnly")) {
|
||||
if (safe.containsKey(key) && !(safe.get(key) instanceof Boolean)) {
|
||||
throw new SkillManifestValidationException("CAPABILITY_OPTION_VALUE_INVALID",
|
||||
field + "." + key, "EasyFlow Skill manifest 的能力选项类型不正确");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验数值型能力选项。
|
||||
*
|
||||
* @param options 能力选项
|
||||
* @param key 选项键
|
||||
* @param path options 字段路径
|
||||
*/
|
||||
private void validateOptionValue(Map<String, Object> options,
|
||||
String key,
|
||||
String path) {
|
||||
if (!options.containsKey(key)) {
|
||||
return;
|
||||
}
|
||||
Object value = options.get(key);
|
||||
// manifest 解码只负责结构、类型和安全边界;运行时值域由能力预览校验统一返回结构化问题。
|
||||
boolean valid = value instanceof Number number
|
||||
&& number.doubleValue() == number.longValue()
|
||||
&& number.longValue() >= Integer.MIN_VALUE
|
||||
&& number.longValue() <= Integer.MAX_VALUE;
|
||||
if (!valid) {
|
||||
throw new SkillManifestValidationException("CAPABILITY_OPTION_VALUE_INVALID",
|
||||
path + "." + key, "EasyFlow Skill manifest 的能力选项数值不正确");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析能力类型并将不可信输入转换为稳定错误。
|
||||
*
|
||||
* @param value 原始类型值
|
||||
* @param bindingPath 能力绑定路径
|
||||
* @return 能力类型
|
||||
*/
|
||||
private SkillCapabilityType parseCapabilityType(Object value, String bindingPath) {
|
||||
String path = bindingPath + ".capabilityType";
|
||||
String type = boundedRequiredString(value, path, 32);
|
||||
try {
|
||||
return SkillCapabilityType.from(type);
|
||||
} catch (BusinessException exception) {
|
||||
throw new SkillManifestValidationException("CAPABILITY_TYPE_INVALID", path,
|
||||
"EasyFlow Skill manifest 的能力类型不受支持");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 MCP 工具选择模式且不回显原始值。
|
||||
*
|
||||
* @param value 模式值
|
||||
* @param bindingPath 能力绑定路径
|
||||
*/
|
||||
private void validateSelectionMode(String value, String bindingPath) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
SkillCapabilitySelectionMode.fromOrDefault(value);
|
||||
} catch (BusinessException exception) {
|
||||
throw new SkillManifestValidationException("MCP_SELECTION_MODE_INVALID",
|
||||
bindingPath + ".selectionMode", "EasyFlow Skill manifest 的 MCP 工具选择模式不受支持");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验能力执行模式且不回显原始值。
|
||||
*
|
||||
* @param value 模式值
|
||||
* @param bindingPath 能力绑定路径
|
||||
*/
|
||||
private void validateExecutionMode(String value, String bindingPath) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
SkillCapabilityExecutionMode.fromOrDefault(value);
|
||||
} catch (BusinessException exception) {
|
||||
throw new SkillManifestValidationException("EXECUTION_MODE_INVALID",
|
||||
bindingPath + ".executionMode", "EasyFlow Skill manifest 的执行模式不受支持");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归校验 manifest 中实际会携带的全部字符串值。
|
||||
*
|
||||
* @param value 当前值
|
||||
* @param path 当前字段路径
|
||||
*/
|
||||
private void validateCredentialFreeTree(Object value, String path) {
|
||||
Deque<ManifestNode> pending = new ArrayDeque<>();
|
||||
pending.push(new ManifestNode(value, path));
|
||||
while (!pending.isEmpty()) {
|
||||
ManifestNode node = pending.pop();
|
||||
if (node.value() instanceof String text) {
|
||||
if (SkillCredentialValueGuard.containsCredential(text)) {
|
||||
throw new SkillManifestValidationException("SENSITIVE_VALUE_DETECTED",
|
||||
node.path().isBlank() ? "manifest" : node.path(),
|
||||
"EasyFlow Skill manifest 不能包含认证凭据");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (node.value() instanceof Map<?, ?> map) {
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
if (entry.getKey() instanceof String key) {
|
||||
String childPath = node.path().isBlank() ? key : node.path() + "." + key;
|
||||
pending.push(new ManifestNode(entry.getValue(), childPath));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (node.value() instanceof List<?> list) {
|
||||
for (int index = list.size() - 1; index >= 0; index--) {
|
||||
pending.push(new ManifestNode(list.get(index), node.path() + "[" + index + "]"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 迭代扫描节点。
|
||||
*
|
||||
* @param value 当前值
|
||||
* @param path 当前路径
|
||||
*/
|
||||
private record ManifestNode(Object value, String path) {
|
||||
}
|
||||
|
||||
private String boundedRequiredString(Object value, String field, int maxLength) {
|
||||
String result = boundedOptionalString(value, field, maxLength);
|
||||
if (result == null || result.isBlank()) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 缺少 " + field);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String boundedOptionalString(Object value, String field, int maxLength) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (!(value instanceof String result) || result.length() > maxLength) {
|
||||
throw new BusinessException("EasyFlow Skill manifest 字段 " + field + " 超过限制或类型不正确");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> bindingManifest(int skillIndex,
|
||||
String packageRoot,
|
||||
int index,
|
||||
SkillCapabilityBinding binding) {
|
||||
String bindingPath = "skills[" + skillIndex + "].capabilities[" + index + "]";
|
||||
if (binding == null) {
|
||||
throw new SkillManifestValidationException("CAPABILITY_EMPTY", bindingPath,
|
||||
"EasyFlow Skill manifest 的能力绑定不能为空");
|
||||
}
|
||||
Map<String, Object> credentialSurface = new LinkedHashMap<>();
|
||||
credentialSurface.put("capabilityType", binding.getCapabilityType());
|
||||
credentialSurface.put("runtimeName", binding.getRuntimeName());
|
||||
credentialSurface.put("selectionMode", binding.getSelectionMode());
|
||||
credentialSurface.put("selectedToolNames", binding.getSelectedToolNamesJson());
|
||||
credentialSurface.put("executionMode", binding.getExecutionMode());
|
||||
validateCredentialFreeTree(credentialSurface, bindingPath);
|
||||
|
||||
SkillCapabilityType type = parseCapabilityType(binding.getCapabilityType(), bindingPath);
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("bindingKey", packageRoot + ":" + index);
|
||||
item.put("capabilityType", type.name());
|
||||
item.put("runtimeName", binding.getRuntimeName());
|
||||
item.put("enabled", binding.getEnabled());
|
||||
item.put("selectionMode", binding.getSelectionMode());
|
||||
item.put("selectedToolNames", binding.getSelectedToolNamesJson());
|
||||
item.put("executionMode", binding.getExecutionMode());
|
||||
item.put("hitlEnabled", binding.getHitlEnabled());
|
||||
Map<String, Object> safeHitl = SkillSensitiveConfigSanitizer.sanitizeHitl(binding.getHitlConfigJson());
|
||||
Map<String, Object> safeOptions = SkillSensitiveConfigSanitizer.sanitizeOptions(binding.getOptionsJson());
|
||||
validateSafeConfig(safeHitl, true, bindingPath + ".hitlConfig");
|
||||
validateSafeConfig(safeOptions, false, bindingPath + ".options");
|
||||
item.put("hitlConfig", safeHitl);
|
||||
item.put("options", safeOptions);
|
||||
item.put("sortNo", binding.getSortNo());
|
||||
String fallbackRef = SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
type, binding.getTargetLogicalRef());
|
||||
if (binding.getTargetId() == null || !Boolean.TRUE.equals(binding.getEnabled())) {
|
||||
item.put("targetLogicalRef", fallbackRef);
|
||||
item.put("targetStatus", binding.getTargetId() == null ? "UNRESOLVED" : "DISABLED");
|
||||
return item;
|
||||
}
|
||||
try {
|
||||
SkillCapabilityTarget target = targetAccessService.requireUsableTarget(binding, false);
|
||||
item.put("targetLogicalRef", SkillPortableTargetSanitizer.safeLogicalRefOrUnresolved(
|
||||
type, target.getLogicalRef()));
|
||||
putSafeMetadata(item, "targetName", target.getName());
|
||||
putSafeMetadata(item, "targetRevision", target.getRevision());
|
||||
item.put("targetStatus", "AVAILABLE");
|
||||
} catch (BusinessException exception) {
|
||||
// 备份导出必须可用;目标会在导入映射或再次发布时重新校验。
|
||||
item.put("targetLogicalRef", fallbackRef);
|
||||
putSafeMetadata(item, "targetName", binding.getTargetName());
|
||||
item.put("targetStatus", exception.getHttpStatus() == 403 ? "NO_PERMISSION" : "UNAVAILABLE");
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅在目标元数据安全且非空时写入 manifest。
|
||||
*
|
||||
* @param target 目标字段映射
|
||||
* @param field 字段名
|
||||
* @param value 原始元数据
|
||||
*/
|
||||
private void putSafeMetadata(Map<String, Object> target, String field, String value) {
|
||||
String safeValue = SkillPortableTargetSanitizer.safePortableMetadataOrNull(value);
|
||||
if (safeValue != null) {
|
||||
target.put(field, safeValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* 已完整构建并校验的 Skill 导出临时产物。
|
||||
*/
|
||||
public final class SkillExportArtifact implements AutoCloseable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SkillExportArtifact.class);
|
||||
|
||||
private final Path path;
|
||||
private final String fileName;
|
||||
private final String mediaType;
|
||||
|
||||
/**
|
||||
* 创建导出产物。
|
||||
*
|
||||
* @param path 临时文件
|
||||
* @param fileName 下载文件名
|
||||
* @param mediaType 媒体类型
|
||||
*/
|
||||
public SkillExportArtifact(Path path, String fileName, String mediaType) {
|
||||
this.path = path;
|
||||
this.fileName = fileName;
|
||||
this.mediaType = mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下载文件名。
|
||||
*
|
||||
* @return 文件名
|
||||
*/
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取媒体类型。
|
||||
*
|
||||
* @return 媒体类型
|
||||
*/
|
||||
public String getMediaType() {
|
||||
return mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将已完成产物传输到响应流。
|
||||
*
|
||||
* @param outputStream 输出流
|
||||
*/
|
||||
public void transferTo(OutputStream outputStream) {
|
||||
try (java.io.InputStream input = Files.newInputStream(path)) {
|
||||
input.transferTo(outputStream);
|
||||
outputStream.flush();
|
||||
} catch (IOException exception) {
|
||||
LOG.error("输出 Skill 导出文件失败,path={}", path, exception);
|
||||
throw new BusinessException(500, 500, "输出 Skill 导出文件失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理临时产物。
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException exception) {
|
||||
LOG.warn("清理 Skill 导出临时产物失败,path={}", path, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 导出请求。
|
||||
*/
|
||||
public class SkillExportRequest {
|
||||
|
||||
private List<BigInteger> ids = new ArrayList<>();
|
||||
private String format;
|
||||
|
||||
public List<BigInteger> getIds() { return ids; }
|
||||
public void setIds(List<BigInteger> ids) { this.ids = ids == null ? new ArrayList<>() : new ArrayList<>(ids); }
|
||||
public String getFormat() { return format; }
|
||||
public void setFormat(String format) { this.format = format; }
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Collection;
|
||||
|
||||
@@ -10,11 +9,11 @@ import java.util.Collection;
|
||||
public interface SkillExportService {
|
||||
|
||||
/**
|
||||
* 导出一个或多个 Skill 为标准 zip 包。
|
||||
* 在写入 HTTP 响应前完整构建导出临时产物。
|
||||
*
|
||||
* @param skillIds Skill ID 集合
|
||||
* @param outputStream zip 输出流
|
||||
* @param format 导出格式
|
||||
* @return 可自动清理的导出产物
|
||||
*/
|
||||
void exportZip(Collection<BigInteger> skillIds, OutputStream outputStream);
|
||||
SkillExportArtifact prepare(Collection<BigInteger> skillIds, SkillImportFormat format);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,106 +1,349 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import com.easyagents.skill.util.SkillPaths;
|
||||
import com.easyagents.skill.codec.SkillPackageWriteOptions;
|
||||
import com.easyagents.skill.codec.ZipSkillPackageCodec;
|
||||
import com.easyagents.skill.exception.SkillPackageException;
|
||||
import com.easyagents.skill.model.SkillPackage;
|
||||
import com.easyagents.skill.model.SkillPackageLayout;
|
||||
import com.easyagents.skill.model.SkillPackageLimits;
|
||||
import com.easyagents.skill.validation.SkillValidationIssue;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
import tech.easyflow.skill.service.SkillService;
|
||||
import tech.easyflow.skill.store.DBSkillContentStore;
|
||||
import tech.easyflow.skill.support.SkillModelConverter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import java.util.zip.Deflater;
|
||||
|
||||
/**
|
||||
* Skill zip 导出服务实现。
|
||||
* 标准 Skill ZIP 与 EasyFlow Bundle 安全导出服务。
|
||||
*/
|
||||
@Service
|
||||
public class SkillExportServiceImpl implements SkillExportService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SkillExportServiceImpl.class);
|
||||
|
||||
private final SkillService skillService;
|
||||
private final DBSkillContentStore contentStore;
|
||||
private final EasyFlowSkillManifestCodec manifestCodec;
|
||||
|
||||
/**
|
||||
* 创建 Skill 导出服务。
|
||||
*
|
||||
* @param skillService Skill 服务
|
||||
* @param contentStore Skill asset 内容存储
|
||||
* @param contentStore 二进制内容仓库
|
||||
* @param manifestCodec EasyFlow manifest 编解码器
|
||||
*/
|
||||
public SkillExportServiceImpl(SkillService skillService, DBSkillContentStore contentStore) {
|
||||
public SkillExportServiceImpl(SkillService skillService,
|
||||
DBSkillContentStore contentStore,
|
||||
EasyFlowSkillManifestCodec manifestCodec) {
|
||||
this.skillService = skillService;
|
||||
this.contentStore = contentStore;
|
||||
this.manifestCodec = manifestCodec;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void exportZip(Collection<BigInteger> skillIds, OutputStream outputStream) {
|
||||
public SkillExportArtifact prepare(Collection<BigInteger> skillIds, SkillImportFormat format) {
|
||||
if (skillIds == null || skillIds.isEmpty()) {
|
||||
throw new BusinessException("请选择要导出的 Skill");
|
||||
}
|
||||
try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, StandardCharsets.UTF_8)) {
|
||||
Set<String> folderNames = new LinkedHashSet<>();
|
||||
for (BigInteger skillId : skillIds) {
|
||||
Skill skill = skillService.getDetail(skillId);
|
||||
writeSkill(zipOutputStream, folderNames, skill);
|
||||
SkillImportFormat effectiveFormat = format == null ? SkillImportFormat.STANDARD : format;
|
||||
List<Skill> skills = loadAuthorizedSkills(
|
||||
skillIds, effectiveFormat == SkillImportFormat.EASYFLOW);
|
||||
Path standardPackage = null;
|
||||
Path finalPackage = null;
|
||||
try {
|
||||
standardPackage = Files.createTempFile("easyflow-skill-standard-", ".zip");
|
||||
encodeStandard(skills, standardPackage);
|
||||
finalPackage = effectiveFormat == SkillImportFormat.STANDARD
|
||||
? standardPackage : buildEasyFlowBundle(skills, standardPackage);
|
||||
if (!finalPackage.equals(standardPackage)) {
|
||||
deleteQuietly(standardPackage);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException("导出 Skill 失败");
|
||||
String fileStem = skills.size() == 1 ? safeFileStem(skills.get(0).getName()) : "skills";
|
||||
return new SkillExportArtifact(finalPackage,
|
||||
fileStem + (effectiveFormat == SkillImportFormat.EASYFLOW ? ".efskill" : ".zip"),
|
||||
effectiveFormat == SkillImportFormat.EASYFLOW
|
||||
? "application/vnd.easyflow.skill+zip" : "application/zip");
|
||||
} catch (BusinessException exception) {
|
||||
deleteQuietly(finalPackage != null && !finalPackage.equals(standardPackage) ? finalPackage : null);
|
||||
deleteQuietly(standardPackage);
|
||||
throw exception;
|
||||
} catch (SkillPackageException exception) {
|
||||
deleteQuietly(finalPackage != null && !finalPackage.equals(standardPackage) ? finalPackage : null);
|
||||
deleteQuietly(standardPackage);
|
||||
throw mapPackageException(exception, effectiveFormat, skillIds);
|
||||
} catch (Exception exception) {
|
||||
deleteQuietly(finalPackage != null && !finalPackage.equals(standardPackage) ? finalPackage : null);
|
||||
deleteQuietly(standardPackage);
|
||||
LOG.error("导出 Skill 包失败,format={}, skillIds={}", effectiveFormat, skillIds, exception);
|
||||
throw new BusinessException(500, 500, "导出 Skill 包失败,请稍后重试", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeSkill(ZipOutputStream zipOutputStream, Set<String> folderNames, Skill skill) throws IOException {
|
||||
String folder = uniqueFolderName(folderNames, skill.getName());
|
||||
writeText(zipOutputStream, folder + "/" + SkillPaths.SKILL_FILE, skill.getSkillContent());
|
||||
if (skill.getReferences() != null) {
|
||||
for (SkillReference reference : skill.getReferences()) {
|
||||
writeText(zipOutputStream, folder + "/" + reference.getPath(), reference.getContent());
|
||||
private List<Skill> loadAuthorizedSkills(Collection<BigInteger> skillIds, boolean includeCapabilities) {
|
||||
List<Skill> skills = new ArrayList<>();
|
||||
Set<BigInteger> uniqueIds = new HashSet<>();
|
||||
for (BigInteger skillId : skillIds) {
|
||||
if (skillId != null && uniqueIds.add(skillId)) {
|
||||
// 标准 ZIP 不读取平台能力目标;两个入口都在服务端逐项执行 Skill READ 权限校验。
|
||||
skills.add(includeCapabilities
|
||||
? skillService.getDetail(skillId)
|
||||
: skillService.getPackageDetail(skillId));
|
||||
}
|
||||
}
|
||||
if (skill.getScripts() != null) {
|
||||
for (SkillScript script : skill.getScripts()) {
|
||||
writeText(zipOutputStream, folder + "/" + script.getPath(), script.getContent());
|
||||
}
|
||||
if (skills.isEmpty()) {
|
||||
throw new BusinessException("请选择有效的 Skill");
|
||||
}
|
||||
if (skill.getAssets() != null) {
|
||||
for (SkillAsset asset : skill.getAssets()) {
|
||||
zipOutputStream.putNextEntry(new ZipEntry(folder + "/" + asset.getPath()));
|
||||
zipOutputStream.write(contentStore.readAllBytes(asset.getContentRef()));
|
||||
zipOutputStream.closeEntry();
|
||||
return skills;
|
||||
}
|
||||
|
||||
private void encodeStandard(List<Skill> skills, Path target) throws IOException {
|
||||
List<com.easyagents.skill.model.Skill> agentSkills = skills.stream()
|
||||
.map(SkillModelConverter::toAgentSkill)
|
||||
.toList();
|
||||
SkillPackage skillPackage = new SkillPackage(
|
||||
agentSkills.size() == 1 ? SkillPackageLayout.SINGLE_DIRECTORY : SkillPackageLayout.MULTI_DIRECTORY,
|
||||
agentSkills);
|
||||
try (OutputStream output = Files.newOutputStream(target, StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
new ZipSkillPackageCodec(contentStore).encode(skillPackage, output, SkillPackageWriteOptions.defaults());
|
||||
}
|
||||
ensureStandardDirectoryEntries(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为标准包中的每个 Skill 根目录补齐可移植的标准空目录项。
|
||||
*
|
||||
* @param packagePath 已由标准编解码器生成的 ZIP 路径
|
||||
* @throws IOException 读取、重写或替换 ZIP 失败时抛出
|
||||
*/
|
||||
private void ensureStandardDirectoryEntries(Path packagePath) throws IOException {
|
||||
Path rewritten = Files.createTempFile("easyflow-skill-directories-", ".zip");
|
||||
Set<String> entryNames = new HashSet<>();
|
||||
List<String> skillRoots = new ArrayList<>();
|
||||
try {
|
||||
try (ZipInputStream input = new ZipInputStream(
|
||||
Files.newInputStream(packagePath), StandardCharsets.UTF_8);
|
||||
ZipOutputStream output = new ZipOutputStream(
|
||||
Files.newOutputStream(rewritten, StandardOpenOption.TRUNCATE_EXISTING),
|
||||
StandardCharsets.UTF_8)) {
|
||||
ZipEntry entry;
|
||||
byte[] buffer = new byte[8192];
|
||||
while ((entry = input.getNextEntry()) != null) {
|
||||
String entryName = entry.getName();
|
||||
entryNames.add(entryName);
|
||||
if (entryName.endsWith("/SKILL.md")) {
|
||||
skillRoots.add(entryName.substring(0, entryName.length() - "SKILL.md".length()));
|
||||
} else if ("SKILL.md".equals(entryName)) {
|
||||
skillRoots.add("");
|
||||
}
|
||||
ZipEntry copied = new ZipEntry(entryName);
|
||||
copied.setTime(0L);
|
||||
output.putNextEntry(copied);
|
||||
if (!entry.isDirectory()) {
|
||||
int length;
|
||||
while ((length = input.read(buffer)) >= 0) {
|
||||
if (length > 0) {
|
||||
output.write(buffer, 0, length);
|
||||
}
|
||||
}
|
||||
}
|
||||
output.closeEntry();
|
||||
}
|
||||
for (String root : skillRoots) {
|
||||
for (String directory : List.of("references/", "scripts/", "assets/")) {
|
||||
String directoryPath = root + directory;
|
||||
if (entryNames.add(directoryPath)) {
|
||||
writeDirectoryEntry(output, directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
output.finish();
|
||||
}
|
||||
Files.move(rewritten, packagePath, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
deleteQuietly(rewritten);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeText(ZipOutputStream zipOutputStream, String path, String content) throws IOException {
|
||||
zipOutputStream.putNextEntry(new ZipEntry(path));
|
||||
zipOutputStream.write((content == null ? "" : content).getBytes(StandardCharsets.UTF_8));
|
||||
zipOutputStream.closeEntry();
|
||||
}
|
||||
|
||||
private String uniqueFolderName(Set<String> folderNames, String name) {
|
||||
String base = sanitizeFolderName(name);
|
||||
String candidate = base;
|
||||
int index = 2;
|
||||
while (!folderNames.add(candidate)) {
|
||||
candidate = base + "-" + index++;
|
||||
private Path buildEasyFlowBundle(List<Skill> skills, Path standardPackage) throws IOException {
|
||||
SkillPackageLimits limits = SkillPackageLimits.defaults();
|
||||
Path bundle = Files.createTempFile("easyflow-skill-bundle-", ".efskill");
|
||||
try {
|
||||
byte[] manifestBytes = manifestCodec.encode(skills);
|
||||
long totalBytes = addExportBytes(0, manifestBytes.length, limits.getMaxTotalUncompressedBytes());
|
||||
int entryCount = 1;
|
||||
try (ZipOutputStream output = new ZipOutputStream(
|
||||
Files.newOutputStream(bundle, StandardOpenOption.TRUNCATE_EXISTING), StandardCharsets.UTF_8)) {
|
||||
// 禁用二次高比率压缩,保证成功导出的外层 Bundle 能通过同一导入压缩比门禁。
|
||||
output.setLevel(Deflater.NO_COMPRESSION);
|
||||
writeEntry(output, EasyFlowSkillManifestCodec.MANIFEST_PATH, manifestBytes);
|
||||
try (ZipInputStream input = new ZipInputStream(
|
||||
Files.newInputStream(standardPackage), StandardCharsets.UTF_8)) {
|
||||
ZipEntry entry;
|
||||
byte[] buffer = new byte[8192];
|
||||
while ((entry = input.getNextEntry()) != null) {
|
||||
if (++entryCount > limits.getMaxEntryCount() + 1) {
|
||||
throw exportLimit("EasyFlow Skill 包文件数量超过限制");
|
||||
}
|
||||
String targetPath = "skills/" + entry.getName();
|
||||
if (targetPath.length() > limits.getMaxPathLength()
|
||||
|| targetPath.split("/").length > limits.getMaxPathDepth()) {
|
||||
throw exportLimit("EasyFlow Skill 包路径长度或层级超过限制");
|
||||
}
|
||||
ZipEntry targetEntry = new ZipEntry(targetPath);
|
||||
targetEntry.setTime(0L);
|
||||
output.putNextEntry(targetEntry);
|
||||
if (!entry.isDirectory()) {
|
||||
int length;
|
||||
while ((length = input.read(buffer)) >= 0) {
|
||||
if (length == 0) {
|
||||
continue;
|
||||
}
|
||||
totalBytes = addExportBytes(
|
||||
totalBytes, length, limits.getMaxTotalUncompressedBytes());
|
||||
output.write(buffer, 0, length);
|
||||
}
|
||||
}
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
output.finish();
|
||||
}
|
||||
if (Files.size(bundle) > limits.getMaxCompressedPackageBytes()) {
|
||||
throw exportLimit("EasyFlow Skill 包压缩文件超过限制");
|
||||
}
|
||||
return bundle;
|
||||
} catch (RuntimeException | IOException exception) {
|
||||
deleteQuietly(bundle);
|
||||
throw exception;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
private String sanitizeFolderName(String value) {
|
||||
String sanitized = value == null ? "skill" : value.trim().replaceAll("[\\\\/:*?\"<>|\\s]+", "-");
|
||||
sanitized = sanitized.replaceAll("^-+", "").replaceAll("-+$", "");
|
||||
return sanitized.isBlank() ? "skill" : sanitized;
|
||||
private long addExportBytes(long current, long increment, long limit) {
|
||||
if (increment < 0 || current > limit - increment) {
|
||||
throw exportLimit("EasyFlow Skill 包解压总大小超过限制");
|
||||
}
|
||||
return current + increment;
|
||||
}
|
||||
|
||||
private BusinessException exportLimit(String message) {
|
||||
return new BusinessException(413, 4131, message);
|
||||
}
|
||||
|
||||
private BusinessException mapPackageException(SkillPackageException exception,
|
||||
SkillImportFormat format,
|
||||
Collection<BigInteger> skillIds) {
|
||||
List<String> codes = new ArrayList<>();
|
||||
codes.add(exception.getCode() == null ? "SKILL_PACKAGE_FAILED" : exception.getCode());
|
||||
if (exception.getReport() != null) {
|
||||
exception.getReport().getIssues().stream()
|
||||
.map(SkillValidationIssue::getCode)
|
||||
.forEach(codes::add);
|
||||
}
|
||||
if (codes.stream().anyMatch(code -> Set.of(
|
||||
"ZIP_IO_ERROR", "CONTENT_STORE_ERROR", "CONTENT_NOT_FOUND", "SKILL_CONTENT_STORE_ERROR",
|
||||
"SKILL_CONTENT_ROLLBACK_ERROR", "CONTENT_REF_MISMATCH",
|
||||
"RESOURCE_SIZE_MISMATCH", "RESOURCE_HASH_MISMATCH", "CRC_MISMATCH")
|
||||
.contains(code))) {
|
||||
LOG.error("导出 Skill 包内部失败,format={}, skillIds={}, code={}, path={}",
|
||||
format, skillIds, exception.getCode(), exception.getPath(), exception);
|
||||
return new BusinessException(500, 500, "导出 Skill 包失败,请稍后重试", exception);
|
||||
}
|
||||
if (codes.stream().anyMatch(code -> code != null && (code.endsWith("_LIMIT")
|
||||
|| code.contains("SIZE_LIMIT")))) {
|
||||
return new BusinessException(413, 4131,
|
||||
"Skill 包超过导出限制:" + firstPackageMessage(exception), exception);
|
||||
}
|
||||
return new BusinessException(400, 4001,
|
||||
"Skill 包不符合导出规范:" + firstPackageMessage(exception), exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取结构化报告中的首个可执行错误消息。
|
||||
*
|
||||
* @param exception M18 包异常
|
||||
* @return 错误消息
|
||||
*/
|
||||
private String firstPackageMessage(SkillPackageException exception) {
|
||||
if (exception.getReport() != null) {
|
||||
return exception.getReport().getIssues().stream()
|
||||
.map(SkillValidationIssue::getMessage)
|
||||
.filter(message -> message != null && !message.isBlank())
|
||||
.findFirst()
|
||||
.orElse("Skill 包校验失败");
|
||||
}
|
||||
return exception.getMessage() == null || exception.getMessage().isBlank()
|
||||
? "Skill 包校验失败" : exception.getMessage();
|
||||
}
|
||||
|
||||
private void writeEntry(ZipOutputStream output, String path, byte[] bytes) throws IOException {
|
||||
ZipEntry entry = new ZipEntry(path);
|
||||
entry.setTime(0L);
|
||||
output.putNextEntry(entry);
|
||||
output.write(bytes);
|
||||
output.closeEntry();
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入确定时间戳的 ZIP 目录项。
|
||||
*
|
||||
* @param output ZIP 输出流
|
||||
* @param path 以斜杠结尾的目录路径
|
||||
* @throws IOException 写入目录项失败时抛出
|
||||
*/
|
||||
private void writeDirectoryEntry(ZipOutputStream output, String path) throws IOException {
|
||||
ZipEntry entry = new ZipEntry(path.endsWith("/") ? path : path + "/");
|
||||
entry.setTime(0L);
|
||||
output.putNextEntry(entry);
|
||||
output.closeEntry();
|
||||
}
|
||||
|
||||
private String safeFileStem(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return "skill";
|
||||
}
|
||||
String normalized = java.text.Normalizer.normalize(value, java.text.Normalizer.Form.NFKC)
|
||||
.toLowerCase(java.util.Locale.ROOT)
|
||||
.replaceAll("[^a-z0-9_-]+", "-")
|
||||
.replaceAll("^-+|-+$", "");
|
||||
if (normalized.isBlank()) {
|
||||
return "skill";
|
||||
}
|
||||
return normalized.substring(0, Math.min(normalized.length(), 80));
|
||||
}
|
||||
|
||||
private void deleteQuietly(Path path) {
|
||||
if (path == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException exception) {
|
||||
LOG.warn("清理 Skill 导出临时文件失败,path={}", path, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
/**
|
||||
* EasyFlow Bundle 能力目标映射项。
|
||||
*/
|
||||
public class SkillImportCapabilityMapping {
|
||||
|
||||
private String bindingKey;
|
||||
private String packageRoot;
|
||||
private String capabilityType;
|
||||
private String targetLogicalRef;
|
||||
private String targetName;
|
||||
private String status;
|
||||
private BigInteger targetId;
|
||||
private boolean disabled;
|
||||
|
||||
public String getBindingKey() { return bindingKey; }
|
||||
public void setBindingKey(String bindingKey) { this.bindingKey = bindingKey; }
|
||||
public String getPackageRoot() { return packageRoot; }
|
||||
public void setPackageRoot(String packageRoot) { this.packageRoot = packageRoot; }
|
||||
public String getCapabilityType() { return capabilityType; }
|
||||
public void setCapabilityType(String capabilityType) { this.capabilityType = capabilityType; }
|
||||
public String getTargetLogicalRef() { return targetLogicalRef; }
|
||||
public void setTargetLogicalRef(String targetLogicalRef) { this.targetLogicalRef = targetLogicalRef; }
|
||||
public String getTargetName() { return targetName; }
|
||||
public void setTargetName(String targetName) { this.targetName = targetName; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public BigInteger getTargetId() { return targetId; }
|
||||
public void setTargetId(BigInteger targetId) { this.targetId = targetId; }
|
||||
public boolean isDisabled() { return disabled; }
|
||||
public void setDisabled(boolean disabled) { this.disabled = disabled; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
/**
|
||||
* 导入确认阶段的窄能力映射请求。
|
||||
*
|
||||
* @param bindingKey manifest 中的能力绑定键
|
||||
* @param targetId 当前环境目标 ID,禁用时为空
|
||||
* @param disabled 是否保持未映射并禁用
|
||||
*/
|
||||
public record SkillImportCapabilityOverride(String bindingKey,
|
||||
BigInteger targetId,
|
||||
boolean disabled) {
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Skill 导入确认请求。
|
||||
*/
|
||||
public class SkillImportConfirmRequest {
|
||||
|
||||
private String importToken;
|
||||
private BigInteger categoryId;
|
||||
private String conflictStrategy;
|
||||
private Map<String, String> renames = new LinkedHashMap<>();
|
||||
private List<SkillImportCapabilityOverride> capabilityMappings = new ArrayList<>();
|
||||
|
||||
public String getImportToken() { return importToken; }
|
||||
public void setImportToken(String importToken) { this.importToken = importToken; }
|
||||
public BigInteger getCategoryId() { return categoryId; }
|
||||
public void setCategoryId(BigInteger categoryId) { this.categoryId = categoryId; }
|
||||
public String getConflictStrategy() { return conflictStrategy; }
|
||||
public void setConflictStrategy(String conflictStrategy) { this.conflictStrategy = conflictStrategy; }
|
||||
public Map<String, String> getRenames() { return renames; }
|
||||
public void setRenames(Map<String, String> renames) { this.renames = renames == null ? new LinkedHashMap<>() : new LinkedHashMap<>(renames); }
|
||||
public List<SkillImportCapabilityOverride> getCapabilityMappings() { return capabilityMappings; }
|
||||
public void setCapabilityMappings(List<SkillImportCapabilityOverride> capabilityMappings) { this.capabilityMappings = capabilityMappings == null ? new ArrayList<>() : new ArrayList<>(capabilityMappings); }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Skill 导入同名冲突策略。
|
||||
*/
|
||||
public enum SkillImportConflictStrategy {
|
||||
REJECT,
|
||||
RENAME,
|
||||
OVERWRITE;
|
||||
|
||||
/**
|
||||
* 解析冲突策略,空值默认拒绝。
|
||||
*
|
||||
* @param value 策略编码
|
||||
* @return 冲突策略
|
||||
*/
|
||||
public static SkillImportConflictStrategy fromOrDefault(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return REJECT;
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new BusinessException("不支持的 Skill 导入冲突策略:" + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Skill 导入导出格式。
|
||||
*/
|
||||
public enum SkillImportFormat {
|
||||
STANDARD,
|
||||
EASYFLOW;
|
||||
|
||||
/**
|
||||
* 解析格式编码。
|
||||
*
|
||||
* @param value 格式编码
|
||||
* @return 格式
|
||||
*/
|
||||
public static SkillImportFormat from(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return STANDARD;
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new BusinessException("不支持的 Skill 包格式:" + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package tech.easyflow.skill.imports;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Date;
|
||||
import tech.easyflow.skill.validation.SkillValidationIssue;
|
||||
|
||||
/**
|
||||
* Skill 导入预览结果。
|
||||
@@ -9,6 +11,11 @@ import java.util.List;
|
||||
public class SkillImportPreview {
|
||||
|
||||
private List<SkillImportPreviewItem> skills = new ArrayList<>();
|
||||
private String importToken;
|
||||
private String format;
|
||||
private Date expiresAt;
|
||||
private List<SkillImportCapabilityMapping> capabilityMappings = new ArrayList<>();
|
||||
private List<SkillValidationIssue> issues = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 获取导入 Skill 预览项。
|
||||
@@ -27,5 +34,15 @@ public class SkillImportPreview {
|
||||
public void setSkills(List<SkillImportPreviewItem> skills) {
|
||||
this.skills = skills == null ? new ArrayList<>() : skills;
|
||||
}
|
||||
}
|
||||
|
||||
public String getImportToken() { return importToken; }
|
||||
public void setImportToken(String importToken) { this.importToken = importToken; }
|
||||
public String getFormat() { return format; }
|
||||
public void setFormat(String format) { this.format = format; }
|
||||
public Date getExpiresAt() { return expiresAt; }
|
||||
public void setExpiresAt(Date expiresAt) { this.expiresAt = expiresAt; }
|
||||
public List<SkillImportCapabilityMapping> getCapabilityMappings() { return capabilityMappings; }
|
||||
public void setCapabilityMappings(List<SkillImportCapabilityMapping> capabilityMappings) { this.capabilityMappings = capabilityMappings == null ? new ArrayList<>() : new ArrayList<>(capabilityMappings); }
|
||||
public List<SkillValidationIssue> getIssues() { return issues; }
|
||||
public void setIssues(List<SkillValidationIssue> issues) { this.issues = issues == null ? new ArrayList<>() : new ArrayList<>(issues); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
/**
|
||||
* Skill 导入预览中的逻辑文件摘要,不包含文件正文、存储引用或物理路径。
|
||||
*/
|
||||
public class SkillImportPreviewFile {
|
||||
|
||||
private String path;
|
||||
private String kind;
|
||||
private String mediaType;
|
||||
private boolean text;
|
||||
private long size;
|
||||
|
||||
/**
|
||||
* 获取 Skill 根目录内的规范相对路径。
|
||||
*
|
||||
* @return 逻辑相对路径
|
||||
*/
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 Skill 根目录内的规范相对路径。
|
||||
*
|
||||
* @param path 逻辑相对路径
|
||||
*/
|
||||
public void setPath(String path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件语义类型。
|
||||
*
|
||||
* @return 文件语义类型
|
||||
*/
|
||||
public String getKind() {
|
||||
return kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置文件语义类型。
|
||||
*
|
||||
* @param kind 文件语义类型
|
||||
*/
|
||||
public void setKind(String kind) {
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取媒体类型。
|
||||
*
|
||||
* @return 媒体类型
|
||||
*/
|
||||
public String getMediaType() {
|
||||
return mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置媒体类型。
|
||||
*
|
||||
* @param mediaType 媒体类型
|
||||
*/
|
||||
public void setMediaType(String mediaType) {
|
||||
this.mediaType = mediaType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件是否为严格 UTF-8 文本。
|
||||
*
|
||||
* @return 文本文件时为 true
|
||||
*/
|
||||
public boolean isText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置文本标记。
|
||||
*
|
||||
* @param text 是否为严格 UTF-8 文本
|
||||
*/
|
||||
public void setText(boolean text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件字节数。
|
||||
*
|
||||
* @return 文件字节数
|
||||
*/
|
||||
public long getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置文件字节数。
|
||||
*
|
||||
* @param size 文件字节数
|
||||
*/
|
||||
public void setSize(long size) {
|
||||
this.size = size;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 导入预览项。
|
||||
*/
|
||||
@@ -12,6 +15,12 @@ public class SkillImportPreviewItem {
|
||||
private int scriptCount;
|
||||
private int assetCount;
|
||||
private boolean conflict;
|
||||
private Boolean overwriteAllowed;
|
||||
private String conflictReason;
|
||||
private String packageRoot;
|
||||
private int resourceCount;
|
||||
private String packageHash;
|
||||
private List<SkillImportPreviewFile> files = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 获取包内 Skill ID。
|
||||
@@ -43,5 +52,56 @@ public class SkillImportPreviewItem {
|
||||
public void setAssetCount(int assetCount) { this.assetCount = assetCount; }
|
||||
public boolean isConflict() { return conflict; }
|
||||
public void setConflict(boolean conflict) { this.conflict = conflict; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户是否允许覆盖同名 Skill。
|
||||
*
|
||||
* @return 存在冲突时的覆盖许可;无冲突时为空
|
||||
*/
|
||||
public Boolean getOverwriteAllowed() { return overwriteAllowed; }
|
||||
|
||||
/**
|
||||
* 设置当前用户是否允许覆盖同名 Skill。
|
||||
*
|
||||
* @param overwriteAllowed 覆盖许可
|
||||
*/
|
||||
public void setOverwriteAllowed(Boolean overwriteAllowed) { this.overwriteAllowed = overwriteAllowed; }
|
||||
|
||||
/**
|
||||
* 获取禁止覆盖的原因编码。
|
||||
*
|
||||
* @return 原因编码;允许覆盖或无冲突时为空
|
||||
*/
|
||||
public String getConflictReason() { return conflictReason; }
|
||||
|
||||
/**
|
||||
* 设置禁止覆盖的原因编码。
|
||||
*
|
||||
* @param conflictReason 原因编码
|
||||
*/
|
||||
public void setConflictReason(String conflictReason) { this.conflictReason = conflictReason; }
|
||||
public String getPackageRoot() { return packageRoot; }
|
||||
public void setPackageRoot(String packageRoot) { this.packageRoot = packageRoot; }
|
||||
public int getResourceCount() { return resourceCount; }
|
||||
public void setResourceCount(int resourceCount) { this.resourceCount = resourceCount; }
|
||||
public String getPackageHash() { return packageHash; }
|
||||
public void setPackageHash(String packageHash) { this.packageHash = packageHash; }
|
||||
|
||||
/**
|
||||
* 获取包内逻辑文件摘要。
|
||||
*
|
||||
* @return 按规范路径排序的文件摘要
|
||||
*/
|
||||
public List<SkillImportPreviewFile> getFiles() {
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置包内逻辑文件摘要。
|
||||
*
|
||||
* @param files 文件摘要
|
||||
*/
|
||||
public void setFiles(List<SkillImportPreviewFile> files) {
|
||||
this.files = files == null ? new ArrayList<>() : new ArrayList<>(files);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,8 @@ package tech.easyflow.skill.imports;
|
||||
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* Skill zip 导入服务。
|
||||
@@ -12,21 +11,26 @@ import java.util.List;
|
||||
public interface SkillImportService {
|
||||
|
||||
/**
|
||||
* 预览 zip 中的 Skill 包。
|
||||
* 上传并创建可单次确认的导入预览。
|
||||
*
|
||||
* @param inputStream zip 输入流
|
||||
* @return 导入预览
|
||||
* @param file 标准 ZIP 或 .efskill
|
||||
* @return 导入预览与 importToken
|
||||
*/
|
||||
SkillImportPreview preview(InputStream inputStream);
|
||||
SkillImportPreview preview(MultipartFile file);
|
||||
|
||||
/**
|
||||
* 确认导入 zip 中的 Skill 包。
|
||||
* 使用单次 importToken 确认导入。
|
||||
*
|
||||
* @param inputStream zip 输入流
|
||||
* @param categoryId 目标分类 ID,可为空
|
||||
* @param overwriteDraft 是否覆盖同名草稿
|
||||
* @return 已保存 Skill 列表
|
||||
* @param request 导入确认请求
|
||||
* @return 已保存 Skill
|
||||
*/
|
||||
List<Skill> importZip(InputStream inputStream, BigInteger categoryId, boolean overwriteDraft);
|
||||
}
|
||||
List<Skill> confirm(SkillImportConfirmRequest request);
|
||||
|
||||
/**
|
||||
* 取消导入预览并清理临时包。
|
||||
*
|
||||
* @param importToken 导入令牌
|
||||
*/
|
||||
void cancel(String importToken);
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,263 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import com.alicp.jetcache.AutoReleaseLock;
|
||||
import com.alicp.jetcache.Cache;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.filestorage.FileStorageService;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.SkillImportStage;
|
||||
import tech.easyflow.skill.mapper.SkillImportStageMapper;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.Duration;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 基于数据库临时索引、JetCache 单次锁与文件存储的 Skill 导入会话仓库。
|
||||
*/
|
||||
@Service
|
||||
public class SkillImportStageStore {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SkillImportStageStore.class);
|
||||
private static final Duration SESSION_TTL = Duration.ofMinutes(30);
|
||||
private static final Duration PROCESSING_TTL = Duration.ofHours(2);
|
||||
private static final String CACHE_PREFIX = "skill:import:";
|
||||
|
||||
private final Cache<String, Object> defaultCache;
|
||||
private final SkillImportStageMapper stageMapper;
|
||||
private final FileStorageService fileStorageService;
|
||||
|
||||
/**
|
||||
* 创建 Skill 导入会话仓库。
|
||||
*
|
||||
* @param defaultCache 平台默认缓存
|
||||
* @param stageMapper 临时包 Mapper
|
||||
* @param fileStorageService 文件存储
|
||||
*/
|
||||
public SkillImportStageStore(@Qualifier("defaultCache") Cache<String, Object> defaultCache,
|
||||
SkillImportStageMapper stageMapper,
|
||||
@Qualifier("default") FileStorageService fileStorageService) {
|
||||
this.defaultCache = defaultCache;
|
||||
this.stageMapper = stageMapper;
|
||||
this.fileStorageService = fileStorageService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登记临时包并返回单次令牌。
|
||||
*
|
||||
* @param filePath 临时包存储路径
|
||||
* @param originalName 原始文件名
|
||||
* @param format 包格式
|
||||
* @return 临时包索引
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SkillImportStage create(String filePath, String originalName, SkillImportFormat format) {
|
||||
LoginAccount account = requireAccount();
|
||||
Date now = new Date();
|
||||
SkillImportStage stage = new SkillImportStage();
|
||||
stage.setImportToken(UUID.randomUUID().toString().replace("-", ""));
|
||||
stage.setTenantId(account.getTenantId());
|
||||
stage.setAccountId(account.getId());
|
||||
stage.setFilePath(filePath);
|
||||
stage.setOriginalName(originalName);
|
||||
stage.setFormat(format.name());
|
||||
stage.setStatus("PENDING");
|
||||
stage.setCreated(now);
|
||||
stage.setExpiresAt(new Date(now.getTime() + SESSION_TTL.toMillis()));
|
||||
if (stageMapper.insert(stage) != 1) {
|
||||
throw new BusinessException(500, 500, "创建 Skill 导入会话失败,请稍后重试");
|
||||
}
|
||||
// 缓存只保存小型索引;完整包始终留在受控文件存储中。
|
||||
defaultCache.put(cacheKey(stage.getImportToken()), stage, SESSION_TTL.toMinutes(), TimeUnit.MINUTES);
|
||||
return stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 原子消费导入令牌。令牌一旦消费,即使业务导入失败也不能重复执行。
|
||||
*
|
||||
* @param token 导入令牌
|
||||
* @return 被消费的临时包索引
|
||||
*/
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
|
||||
public SkillImportStage consume(String token) {
|
||||
validateToken(token);
|
||||
LoginAccount account = requireAccount();
|
||||
try (AutoReleaseLock lock = defaultCache.tryLock(lockKey(token), 60, TimeUnit.SECONDS)) {
|
||||
if (lock == null) {
|
||||
throw new BusinessException("Skill 导入正在处理中,请勿重复提交");
|
||||
}
|
||||
SkillImportStage stage = findOwnedStage(token, account);
|
||||
assertOwner(stage, account);
|
||||
Date now = new Date();
|
||||
Date processingExpiresAt = new Date(now.getTime() + PROCESSING_TTL.toMillis());
|
||||
if (stageMapper.consume(token, account.getTenantId(), account.getId(), now, processingExpiresAt) != 1) {
|
||||
throw new BusinessException("Skill 导入令牌已过期或已被使用,请重新预览");
|
||||
}
|
||||
stage.setStatus("PROCESSING");
|
||||
stage.setExpiresAt(processingExpiresAt);
|
||||
defaultCache.remove(cacheKey(token));
|
||||
return stage;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消尚未消费的导入会话并释放临时包。
|
||||
*
|
||||
* @param token 导入令牌
|
||||
*/
|
||||
public void cancel(String token) {
|
||||
validateToken(token);
|
||||
LoginAccount account = requireAccount();
|
||||
try (AutoReleaseLock lock = defaultCache.tryLock(lockKey(token), 30, TimeUnit.SECONDS)) {
|
||||
if (lock == null) {
|
||||
throw new BusinessException("Skill 导入正在处理中,暂时无法取消");
|
||||
}
|
||||
SkillImportStage stage = findOwnedStage(token, account);
|
||||
assertOwner(stage, account);
|
||||
if (!"PENDING".equals(stage.getStatus())) {
|
||||
throw new BusinessException("Skill 导入正在处理中,不能取消");
|
||||
}
|
||||
Date now = new Date();
|
||||
if (stageMapper.beginCancel(token, account.getTenantId(), account.getId(), now) != 1) {
|
||||
throw new BusinessException("Skill 导入状态已变化,请刷新后重试");
|
||||
}
|
||||
stage.setStatus("PROCESSING");
|
||||
stage.setExpiresAt(now);
|
||||
defaultCache.remove(cacheKey(token));
|
||||
deleteFile(stage);
|
||||
if (stageMapper.finishCancel(token, account.getTenantId(), account.getId()) != 1) {
|
||||
throw new BusinessException("Skill 导入状态已变化,请刷新后重试");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完成导入后释放临时包和索引。
|
||||
*
|
||||
* @param stage 临时包索引
|
||||
*/
|
||||
public void complete(SkillImportStage stage) {
|
||||
if (stage != null) {
|
||||
cleanup(stage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时清理过期或已消费但未完成清理的临时包。
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "${easyflow.skill.import-cleanup-delay-ms:300000}")
|
||||
public void cleanupExpired() {
|
||||
List<SkillImportStage> expired = stageMapper.selectListByQuery(QueryWrapper.create()
|
||||
.le(SkillImportStage::getExpiresAt, new Date())
|
||||
.orderBy("expires_at asc")
|
||||
.limit(100));
|
||||
for (SkillImportStage stage : expired) {
|
||||
try (AutoReleaseLock lock = defaultCache.tryLock(lockKey(stage.getImportToken()), 30, TimeUnit.SECONDS)) {
|
||||
if (lock == null) {
|
||||
continue;
|
||||
}
|
||||
SkillImportStage current = stageMapper.selectOneById(stage.getImportToken());
|
||||
if (current != null && current.getExpiresAt() != null && !current.getExpiresAt().after(new Date())) {
|
||||
cleanup(current);
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
LOG.error("清理过期 Skill 导入临时包失败,token={}", stage.getImportToken(), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanup(SkillImportStage stage) {
|
||||
deleteFile(stage);
|
||||
stageMapper.deleteById(stage.getImportToken());
|
||||
defaultCache.remove(cacheKey(stage.getImportToken()));
|
||||
}
|
||||
|
||||
private void deleteFile(SkillImportStage stage) {
|
||||
try {
|
||||
fileStorageService.delete(stage.getFilePath());
|
||||
} catch (RuntimeException exception) {
|
||||
if (isFileAlreadyAbsent(exception)) {
|
||||
return;
|
||||
}
|
||||
LOG.error("删除 Skill 导入临时包失败,token={}, path={}",
|
||||
stage.getImportToken(), stage.getFilePath(), exception);
|
||||
throw new BusinessException(500, 500, "清理 Skill 导入临时包失败,请稍后重试", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断存储异常是否表示目标文件已经不存在。
|
||||
*
|
||||
* @param exception 存储删除异常
|
||||
* @return 文件已不存在时为 true
|
||||
*/
|
||||
private boolean isFileAlreadyAbsent(RuntimeException exception) {
|
||||
Throwable current = exception;
|
||||
while (current != null) {
|
||||
if (current instanceof java.io.FileNotFoundException
|
||||
|| current instanceof java.nio.file.NoSuchFileException) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assertOwner(SkillImportStage stage, LoginAccount account) {
|
||||
if (stage == null) {
|
||||
throw new BusinessException(404, 404, "Skill 导入令牌不存在或已过期");
|
||||
}
|
||||
if (!account.getId().equals(stage.getAccountId()) || !account.getTenantId().equals(stage.getTenantId())) {
|
||||
throw new BusinessException(403, 403, "无权限使用该 Skill 导入令牌");
|
||||
}
|
||||
if (stage.getExpiresAt() == null || !stage.getExpiresAt().after(new Date())) {
|
||||
throw new BusinessException("Skill 导入令牌已过期,请重新预览");
|
||||
}
|
||||
}
|
||||
|
||||
private LoginAccount requireAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
private void validateToken(String token) {
|
||||
if (token == null || !token.matches("^[a-fA-F0-9]{32}$")) {
|
||||
throw new BusinessException("Skill 导入令牌格式不正确");
|
||||
}
|
||||
}
|
||||
|
||||
private SkillImportStage findOwnedStage(String token, LoginAccount account) {
|
||||
SkillImportStage stage = stageMapper.selectOneByQuery(QueryWrapper.create()
|
||||
.eq(SkillImportStage::getImportToken, token)
|
||||
.eq(SkillImportStage::getTenantId, account.getTenantId())
|
||||
.eq(SkillImportStage::getAccountId, account.getId()));
|
||||
if (stage == null && stageMapper.selectCountByQuery(QueryWrapper.create()
|
||||
.eq(SkillImportStage::getImportToken, token)) > 0) {
|
||||
throw new BusinessException(403, 403, "无权限使用该 Skill 导入令牌");
|
||||
}
|
||||
return stage;
|
||||
}
|
||||
|
||||
private String cacheKey(String token) {
|
||||
return CACHE_PREFIX + token;
|
||||
}
|
||||
|
||||
private String lockKey(String token) {
|
||||
return CACHE_PREFIX + "lock:" + token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
/**
|
||||
* 携带结构化问题码和字段路径的 EasyFlow Skill manifest 校验异常。
|
||||
*/
|
||||
public class SkillManifestValidationException extends BusinessException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String validationCode;
|
||||
private final String path;
|
||||
|
||||
/**
|
||||
* 创建 manifest 校验异常。
|
||||
*
|
||||
* @param validationCode 稳定问题码
|
||||
* @param path manifest 字段路径
|
||||
* @param message 不包含原始敏感值的安全消息
|
||||
*/
|
||||
public SkillManifestValidationException(String validationCode, String path, String message) {
|
||||
super(400, 4001, message);
|
||||
this.validationCode = validationCode;
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取稳定问题码。
|
||||
*
|
||||
* @return 问题码
|
||||
*/
|
||||
public String getValidationCode() {
|
||||
return validationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 manifest 字段路径。
|
||||
*
|
||||
* @return 字段路径
|
||||
*/
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import tech.easyflow.skill.entity.SkillAssetContent;
|
||||
|
||||
/**
|
||||
* Skill asset 内容索引 Mapper。
|
||||
*/
|
||||
public interface SkillAssetContentMapper extends BaseMapper<SkillAssetContent> {
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
|
||||
/**
|
||||
* Skill asset Mapper。
|
||||
*/
|
||||
public interface SkillAssetMapper extends BaseMapper<SkillAsset> {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
|
||||
/**
|
||||
* Skill 能力绑定 Mapper。
|
||||
*/
|
||||
public interface SkillCapabilityBindingMapper extends BaseMapper<SkillCapabilityBinding> {
|
||||
}
|
||||
@@ -1,10 +1,27 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import tech.easyflow.skill.entity.SkillCategory;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 分类 Mapper。
|
||||
*/
|
||||
public interface SkillCategoryMapper extends BaseMapper<SkillCategory> {
|
||||
|
||||
/**
|
||||
* 按稳定顺序锁定租户内完整分类树,串行化分类结构变更。
|
||||
*
|
||||
* @param tenantId 租户 ID
|
||||
* @return 已锁定的分类列表
|
||||
*/
|
||||
@Select("SELECT id,tenant_id AS tenantId,parent_id AS parentId,category_name AS categoryName," +
|
||||
"level_no AS levelNo,ancestors,sort_no AS sortNo,status,created,created_by AS createdBy," +
|
||||
"modified,modified_by AS modifiedBy FROM tb_skill_category " +
|
||||
"WHERE tenant_id=#{tenantId} ORDER BY id FOR UPDATE")
|
||||
List<SkillCategory> selectTenantTreeForUpdate(@Param("tenantId") BigInteger tenantId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import tech.easyflow.skill.entity.SkillContent;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 二进制内容 Mapper。
|
||||
*/
|
||||
public interface SkillContentMapper extends BaseMapper<SkillContent> {
|
||||
|
||||
/**
|
||||
* 原子增加与内容引用、大小及哈希均匹配的正式内容引用计数。
|
||||
*
|
||||
* <p>storage_locator 允许为 null 仅用于兼容迁移前正式内容;空定位符与旧 PENDING 路径
|
||||
* 均不会被视为活动内容。</p>
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param size 内容字节数
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content SET ref_count=ref_count+1,modified=CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref=#{contentRef} AND size=#{size} "
|
||||
+ "AND CONCAT('sha256:',content_hash)=#{contentRef} AND ref_count>0 "
|
||||
+ "AND file_path IS NOT NULL AND file_path<>'' AND file_path NOT LIKE '__PENDING__:%' "
|
||||
+ "AND (storage_locator IS NULL OR storage_locator<>'')")
|
||||
int retainMatching(@Param("contentRef") String contentRef, @Param("size") long size);
|
||||
|
||||
/**
|
||||
* 以当前读方式锁定并返回指定内容索引。
|
||||
*
|
||||
* <p>该查询用于引用计数状态转换,避免 MySQL REPEATABLE READ 下普通一致性读反复返回
|
||||
* 调用方事务早先建立的旧快照。</p>
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @return 当前内容索引;不存在时为 null
|
||||
*/
|
||||
@Select("SELECT content_ref AS contentRef,content_hash AS contentHash,file_path AS filePath," +
|
||||
"storage_locator AS storageLocator,media_type AS mediaType,size,ref_count AS refCount,created,modified "
|
||||
+ "FROM tb_skill_content WHERE content_ref=#{contentRef} FOR UPDATE")
|
||||
SkillContent selectForUpdate(@Param("contentRef") String contentRef);
|
||||
|
||||
/**
|
||||
* 将已经完成物理校验的旧版零引用内容恢复为一份活动引用。
|
||||
*
|
||||
* <p>仅允许恢复缺少稳定定位符的迁移前内容;读取路径、哈希、大小与零引用状态均须保持
|
||||
* 锁定读取时的值,避免复活正在由新流程清理的可恢复对象。</p>
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param contentHash 内容哈希
|
||||
* @param filePath 已校验的旧版读取路径
|
||||
* @param size 内容字节数
|
||||
* @return 成功恢复为 1,状态已变化为 0
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content SET ref_count=1,modified=CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref=#{contentRef} AND content_hash=#{contentHash} "
|
||||
+ "AND file_path=#{filePath} AND size=#{size} AND ref_count=0 "
|
||||
+ "AND storage_locator IS NULL AND file_path IS NOT NULL AND file_path<>'' "
|
||||
+ "AND file_path NOT LIKE '__PENDING__:%'")
|
||||
int resurrectVerifiedLegacy(@Param("contentRef") String contentRef,
|
||||
@Param("contentHash") String contentHash,
|
||||
@Param("filePath") String filePath,
|
||||
@Param("size") long size);
|
||||
|
||||
/**
|
||||
* 插入首个引用已经激活的正式内容索引。
|
||||
*
|
||||
* <p>新流程必须同时提供非空读取路径和稳定存储定位符,并保证内容引用与哈希一致。</p>
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param contentHash 内容哈希
|
||||
* @param filePath 文件读取路径
|
||||
* @param storageLocator 稳定存储定位符
|
||||
* @param mediaType 媒体类型
|
||||
* @param size 内容字节数
|
||||
* @return 成功插入为 1,参数不满足活动内容约束为 0
|
||||
* @throws org.springframework.dao.DuplicateKeyException 内容引用已经存在
|
||||
*/
|
||||
@Insert("INSERT INTO tb_skill_content("
|
||||
+ "content_ref,content_hash,file_path,storage_locator,media_type,size,ref_count,created,modified) "
|
||||
+ "SELECT #{contentRef},#{contentHash},#{filePath},#{storageLocator},#{mediaType},#{size},"
|
||||
+ "1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP "
|
||||
+ "WHERE #{filePath} IS NOT NULL AND #{filePath}<>'' "
|
||||
+ "AND #{filePath} NOT LIKE '__PENDING__:%' "
|
||||
+ "AND #{storageLocator} IS NOT NULL AND #{storageLocator}<>'' "
|
||||
+ "AND #{size}>=0 AND CONCAT('sha256:',#{contentHash})=#{contentRef}")
|
||||
int insertActive(@Param("contentRef") String contentRef,
|
||||
@Param("contentHash") String contentHash,
|
||||
@Param("filePath") String filePath,
|
||||
@Param("storageLocator") String storageLocator,
|
||||
@Param("mediaType") String mediaType,
|
||||
@Param("size") long size);
|
||||
|
||||
/**
|
||||
* 原子增加内容引用计数。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content SET ref_count = ref_count + 1, modified = CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref = #{contentRef} AND ref_count > 0 "
|
||||
+ "AND CONCAT('sha256:',content_hash)=#{contentRef} "
|
||||
+ "AND file_path IS NOT NULL AND file_path<>'' AND file_path NOT LIKE '__PENDING__:%' "
|
||||
+ "AND (storage_locator IS NULL OR storage_locator<>'')")
|
||||
int retain(String contentRef);
|
||||
|
||||
/**
|
||||
* 原子减少仍有多个持有者的内容引用计数。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content SET ref_count = ref_count - 1, modified = CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref = #{contentRef} AND ref_count > 1 "
|
||||
+ "AND file_path IS NOT NULL AND file_path<>'' AND file_path NOT LIKE '__PENDING__:%' "
|
||||
+ "AND (storage_locator IS NULL OR storage_locator<>'')")
|
||||
int releaseShared(String contentRef);
|
||||
|
||||
/**
|
||||
* 通过 INSERT IGNORE 原子抢占新内容 hash,避免跨实例 get-then-insert 竞态。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param contentHash 内容 hash
|
||||
* @param pendingPath 临时占位路径
|
||||
* @param mediaType 媒体类型
|
||||
* @param size 字节数
|
||||
* @return 抢占成功为 1,已有内容为 0
|
||||
*/
|
||||
@Insert("INSERT IGNORE INTO tb_skill_content(content_ref,content_hash,file_path,media_type,size,ref_count,created,modified) "
|
||||
+ "VALUES(#{contentRef},#{contentHash},#{pendingPath},#{mediaType},#{size},0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)")
|
||||
int reserve(@Param("contentRef") String contentRef,
|
||||
@Param("contentHash") String contentHash,
|
||||
@Param("pendingPath") String pendingPath,
|
||||
@Param("mediaType") String mediaType,
|
||||
@Param("size") long size);
|
||||
|
||||
/**
|
||||
* 完成内容物理路径写入。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param filePath 物理路径
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content SET file_path=#{filePath}, ref_count=1, modified=CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref=#{contentRef} AND ref_count=0 AND file_path LIKE '__PENDING__:%'")
|
||||
int finishReservation(@Param("contentRef") String contentRef, @Param("filePath") String filePath);
|
||||
|
||||
/**
|
||||
* 按读取路径和稳定定位符精确标记最后一份正式内容引用为待清理。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param filePath 当前文件读取路径
|
||||
* @param storageLocator 当前稳定存储定位符
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content SET ref_count=0,modified=CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref=#{contentRef} AND file_path=#{filePath} "
|
||||
+ "AND storage_locator<=>#{storageLocator} AND ref_count=1 "
|
||||
+ "AND file_path IS NOT NULL AND file_path<>'' AND file_path NOT LIKE '__PENDING__:%' "
|
||||
+ "AND (storage_locator IS NULL OR storage_locator<>'')")
|
||||
int markReleased(@Param("contentRef") String contentRef,
|
||||
@Param("filePath") String filePath,
|
||||
@Param("storageLocator") String storageLocator);
|
||||
|
||||
/**
|
||||
* 统计当前可读取的正式内容。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @return 可见内容数量
|
||||
*/
|
||||
@Select("SELECT COUNT(1) FROM tb_skill_content WHERE content_ref=#{contentRef} "
|
||||
+ "AND ref_count>0 AND file_path IS NOT NULL AND file_path<>'' "
|
||||
+ "AND file_path NOT LIKE '__PENDING__:%' "
|
||||
+ "AND (storage_locator IS NULL OR storage_locator<>'')")
|
||||
int countVisible(String contentRef);
|
||||
|
||||
/**
|
||||
* 查询超过保留期限的未完成占位记录。
|
||||
*
|
||||
* @param cutoff 截止时间
|
||||
* @param limit 最大返回数量
|
||||
* @return 待清理占位记录
|
||||
*/
|
||||
@Select("SELECT content_ref AS contentRef,content_hash AS contentHash,file_path AS filePath," +
|
||||
"storage_locator AS storageLocator,media_type AS mediaType,size,ref_count AS refCount,created,modified "
|
||||
+ "FROM tb_skill_content WHERE ref_count=0 AND file_path LIKE '__PENDING__:%' "
|
||||
+ "AND modified < #{cutoff} ORDER BY modified ASC LIMIT #{limit}")
|
||||
List<SkillContent> findStalePending(@Param("cutoff") Date cutoff, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 条件删除仍处于原占位状态的过期记录。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param pendingPath 原占位路径
|
||||
* @param cutoff 截止时间
|
||||
* @return 删除行数
|
||||
*/
|
||||
@Delete("DELETE FROM tb_skill_content WHERE content_ref=#{contentRef} AND file_path=#{pendingPath} "
|
||||
+ "AND ref_count=0 AND file_path LIKE '__PENDING__:%' AND modified < #{cutoff}")
|
||||
int deleteStalePending(@Param("contentRef") String contentRef,
|
||||
@Param("pendingPath") String pendingPath,
|
||||
@Param("cutoff") Date cutoff);
|
||||
|
||||
/**
|
||||
* 查询需要重试物理删除的零引用内容。
|
||||
*
|
||||
* @param cutoff 截止时间
|
||||
* @param limit 最大返回数量
|
||||
* @return 待清理内容
|
||||
*/
|
||||
@Select("SELECT content_ref AS contentRef,content_hash AS contentHash,file_path AS filePath," +
|
||||
"storage_locator AS storageLocator,media_type AS mediaType,size,ref_count AS refCount,created,modified "
|
||||
+ "FROM tb_skill_content WHERE ref_count=0 AND file_path NOT LIKE '__PENDING__:%' "
|
||||
+ "AND storage_locator IS NOT NULL AND storage_locator<>'' "
|
||||
+ "AND modified < #{cutoff} ORDER BY modified ASC LIMIT #{limit}")
|
||||
List<SkillContent> findReleasedBefore(@Param("cutoff") Date cutoff, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 按读取路径和稳定定位符精确删除已完成物理清理的零引用索引。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param filePath 原文件读取路径
|
||||
* @param storageLocator 原稳定存储定位符
|
||||
* @return 删除行数
|
||||
*/
|
||||
@Delete("DELETE FROM tb_skill_content WHERE content_ref=#{contentRef} "
|
||||
+ "AND file_path=#{filePath} AND storage_locator<=>#{storageLocator} AND ref_count=0")
|
||||
int deleteReleased(@Param("contentRef") String contentRef,
|
||||
@Param("filePath") String filePath,
|
||||
@Param("storageLocator") String storageLocator);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import tech.easyflow.skill.entity.SkillContentWriteIntent;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 二进制内容写入意图 Mapper。
|
||||
*/
|
||||
public interface SkillContentWriteIntentMapper extends BaseMapper<SkillContentWriteIntent> {
|
||||
|
||||
/**
|
||||
* 原子预留指定内容引用的写入意图。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param reservationToken 写入预留令牌
|
||||
* @param contentHash 内容哈希
|
||||
* @param storageLocator 稳定存储定位符
|
||||
* @param mediaType 媒体类型
|
||||
* @param size 内容字节数
|
||||
* @return 成功插入为 1,参数不满足约束为 0
|
||||
* @throws org.springframework.dao.DuplicateKeyException 内容引用已被其他写入意图预留
|
||||
*/
|
||||
@Insert("INSERT INTO tb_skill_content_write_intent("
|
||||
+ "content_ref,reservation_token,content_hash,storage_locator,media_type,size,state,created,modified) "
|
||||
+ "SELECT #{contentRef},#{reservationToken},#{contentHash},#{storageLocator},#{mediaType},#{size},"
|
||||
+ "'PENDING',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP "
|
||||
+ "WHERE #{storageLocator} IS NOT NULL AND #{storageLocator}<>'' "
|
||||
+ "AND CONCAT('sha256:',#{contentHash})=#{contentRef}")
|
||||
int reserve(@Param("contentRef") String contentRef,
|
||||
@Param("reservationToken") String reservationToken,
|
||||
@Param("contentHash") String contentHash,
|
||||
@Param("storageLocator") String storageLocator,
|
||||
@Param("mediaType") String mediaType,
|
||||
@Param("size") long size);
|
||||
|
||||
/**
|
||||
* 在调用方事务中将预留意图原子声明为正在写入。
|
||||
*
|
||||
* <p>UPDATE 会持有目标行的排他锁直至调用方事务结束;事务回滚后状态恢复为 PENDING。</p>
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param reservationToken 写入预留令牌
|
||||
* @return 成功声明为 1,令牌或状态不匹配为 0
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content_write_intent SET state='WRITING',modified=CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref=#{contentRef} AND reservation_token=#{reservationToken} AND state='PENDING'")
|
||||
int claimForWrite(@Param("contentRef") String contentRef,
|
||||
@Param("reservationToken") String reservationToken);
|
||||
|
||||
/**
|
||||
* 查询超过截止时间且尚未完成的写入意图。
|
||||
*
|
||||
* @param cutoff 截止时间
|
||||
* @param limit 最大返回数量
|
||||
* @return 按修改时间升序排列的过期意图
|
||||
*/
|
||||
@Select("SELECT content_ref AS contentRef,reservation_token AS reservationToken," +
|
||||
"content_hash AS contentHash,storage_locator AS storageLocator,media_type AS mediaType," +
|
||||
"size,state,created,modified "
|
||||
+ "FROM tb_skill_content_write_intent "
|
||||
+ "WHERE state IN ('PENDING','WRITING','CLEANING') AND modified<#{cutoff} "
|
||||
+ "ORDER BY modified ASC LIMIT #{limit}")
|
||||
List<SkillContentWriteIntent> findStale(@Param("cutoff") Date cutoff, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 将过期意图原子声明为清理中。
|
||||
*
|
||||
* <p>expectedState 构成状态 CAS。传入 CLEANING 时,同一令牌可幂等重试;存在正式活动内容时
|
||||
* 不允许取得清理权。</p>
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param reservationToken 写入预留令牌
|
||||
* @param expectedState 查询时观察到的状态
|
||||
* @param cutoff 截止时间
|
||||
* @return 成功声明为 1,状态已变化或存在活动内容为 0
|
||||
*/
|
||||
@Update("UPDATE tb_skill_content_write_intent SET state='CLEANING',modified=CURRENT_TIMESTAMP "
|
||||
+ "WHERE content_ref=#{contentRef} AND reservation_token=#{reservationToken} "
|
||||
+ "AND state=#{expectedState} AND state IN ('PENDING','WRITING','CLEANING') "
|
||||
+ "AND modified<#{cutoff} AND NOT EXISTS ("
|
||||
+ "SELECT 1 FROM tb_skill_content active_content "
|
||||
+ "WHERE active_content.content_ref=tb_skill_content_write_intent.content_ref "
|
||||
+ "AND active_content.ref_count>0)")
|
||||
int claimForCleanup(@Param("contentRef") String contentRef,
|
||||
@Param("reservationToken") String reservationToken,
|
||||
@Param("expectedState") String expectedState,
|
||||
@Param("cutoff") Date cutoff);
|
||||
|
||||
/**
|
||||
* 删除当前令牌已经取得清理权的写入意图。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param reservationToken 写入预留令牌
|
||||
* @return 删除行数
|
||||
*/
|
||||
@Delete("DELETE FROM tb_skill_content_write_intent WHERE content_ref=#{contentRef} "
|
||||
+ "AND reservation_token=#{reservationToken} AND state='CLEANING'")
|
||||
int deleteClaimed(@Param("contentRef") String contentRef,
|
||||
@Param("reservationToken") String reservationToken);
|
||||
|
||||
/**
|
||||
* 正式内容已激活时删除残留写入意图。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param reservationToken 写入预留令牌
|
||||
* @return 删除行数
|
||||
*/
|
||||
@Delete("DELETE FROM tb_skill_content_write_intent WHERE content_ref=#{contentRef} "
|
||||
+ "AND reservation_token=#{reservationToken} AND EXISTS ("
|
||||
+ "SELECT 1 FROM tb_skill_content active_content "
|
||||
+ "WHERE active_content.content_ref=tb_skill_content_write_intent.content_ref "
|
||||
+ "AND active_content.ref_count>0)")
|
||||
int deleteIfActiveExists(@Param("contentRef") String contentRef,
|
||||
@Param("reservationToken") String reservationToken);
|
||||
|
||||
/**
|
||||
* 删除调用方尚未声明写入、且确认不会产生物理对象的预留意图。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @param reservationToken 写入预留令牌
|
||||
* @return 删除行数
|
||||
*/
|
||||
@Delete("DELETE FROM tb_skill_content_write_intent WHERE content_ref=#{contentRef} "
|
||||
+ "AND reservation_token=#{reservationToken} AND state='PENDING'")
|
||||
int deletePending(@Param("contentRef") String contentRef,
|
||||
@Param("reservationToken") String reservationToken);
|
||||
|
||||
/**
|
||||
* 按内容引用读取完整写入意图。
|
||||
*
|
||||
* @param contentRef 内容引用
|
||||
* @return 写入意图,不存在时为 null
|
||||
*/
|
||||
@Select("SELECT content_ref AS contentRef,reservation_token AS reservationToken," +
|
||||
"content_hash AS contentHash,storage_locator AS storageLocator,media_type AS mediaType," +
|
||||
"size,state,created,modified "
|
||||
+ "FROM tb_skill_content_write_intent WHERE content_ref=#{contentRef}")
|
||||
SkillContentWriteIntent getIntent(@Param("contentRef") String contentRef);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import tech.easyflow.skill.entity.SkillImportStage;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Skill 导入临时包 Mapper。
|
||||
*/
|
||||
public interface SkillImportStageMapper extends BaseMapper<SkillImportStage> {
|
||||
|
||||
/**
|
||||
* 原子消费仍有效的导入令牌。
|
||||
*
|
||||
* @param token 导入令牌
|
||||
* @param tenantId 租户 ID
|
||||
* @param accountId 用户 ID
|
||||
* @param now 当前时间
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_import_stage SET status='PROCESSING', expires_at=#{processingExpiresAt} "
|
||||
+ "WHERE import_token=#{token} AND tenant_id=#{tenantId} AND account_id=#{accountId} "
|
||||
+ "AND status='PENDING' AND expires_at>#{now}")
|
||||
int consume(@Param("token") String token,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("accountId") BigInteger accountId,
|
||||
@Param("now") Date now,
|
||||
@Param("processingExpiresAt") Date processingExpiresAt);
|
||||
|
||||
/**
|
||||
* 将待确认令牌原子转为已过期的处理中状态,阻止删除文件期间被并发消费。
|
||||
*
|
||||
* @param token 导入令牌
|
||||
* @param tenantId 租户 ID
|
||||
* @param accountId 用户 ID
|
||||
* @param now 当前时间,同时作为立即清理截止时间
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill_import_stage SET status='PROCESSING', expires_at=#{now} "
|
||||
+ "WHERE import_token=#{token} AND tenant_id=#{tenantId} AND account_id=#{accountId} "
|
||||
+ "AND status='PENDING'")
|
||||
int beginCancel(@Param("token") String token,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("accountId") BigInteger accountId,
|
||||
@Param("now") Date now);
|
||||
|
||||
/**
|
||||
* 删除已原子进入取消流程且属于当前用户的令牌。
|
||||
*
|
||||
* @param token 导入令牌
|
||||
* @param tenantId 租户 ID
|
||||
* @param accountId 用户 ID
|
||||
* @return 删除行数
|
||||
*/
|
||||
@Delete("DELETE FROM tb_skill_import_stage WHERE import_token=#{token} AND tenant_id=#{tenantId} "
|
||||
+ "AND account_id=#{accountId} AND status='PROCESSING'")
|
||||
int finishCancel(@Param("token") String token,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("accountId") BigInteger accountId);
|
||||
}
|
||||
@@ -1,10 +1,106 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Skill Mapper。
|
||||
*/
|
||||
public interface SkillMapper extends BaseMapper<Skill> {
|
||||
|
||||
/**
|
||||
* 在租户边界内更新审批中的发布状态,并显式写入或清空审批实例 ID。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @param publishStatus 发布状态
|
||||
* @param approvalInstanceId 当前审批实例 ID,可为空
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill SET publish_status=#{publishStatus}, "
|
||||
+ "current_approval_instance_id=#{approvalInstanceId} "
|
||||
+ "WHERE id=#{id} AND tenant_id=#{tenantId}")
|
||||
int updateApprovalState(@Param("id") BigInteger id,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("publishStatus") String publishStatus,
|
||||
@Param("approvalInstanceId") BigInteger approvalInstanceId);
|
||||
|
||||
/**
|
||||
* 在租户边界内持久化已发布快照,并原子清空审批实例 ID。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @param snapshot 已发布快照
|
||||
* @param publishedAt 发布时间
|
||||
* @param publishedBy 发布人
|
||||
* @param snapshotHash 快照哈希
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill SET publish_status='PUBLISHED', "
|
||||
+ "published_snapshot_json=#{snapshot,typeHandler=com.mybatisflex.core.handler.FastjsonTypeHandler}, "
|
||||
+ "published_at=#{publishedAt}, published_by=#{publishedBy}, "
|
||||
+ "snapshot_hash=#{snapshotHash}, current_approval_instance_id=NULL "
|
||||
+ "WHERE id=#{id} AND tenant_id=#{tenantId}")
|
||||
int publish(@Param("id") BigInteger id,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("snapshot") Map<String, Object> snapshot,
|
||||
@Param("publishedAt") Date publishedAt,
|
||||
@Param("publishedBy") BigInteger publishedBy,
|
||||
@Param("snapshotHash") String snapshotHash);
|
||||
|
||||
/**
|
||||
* 在租户边界内将 Skill 标记为下线,并清空审批实例 ID。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill SET publish_status='OFFLINE', current_approval_instance_id=NULL "
|
||||
+ "WHERE id=#{id} AND tenant_id=#{tenantId}")
|
||||
int markOffline(@Param("id") BigInteger id, @Param("tenantId") BigInteger tenantId);
|
||||
|
||||
/**
|
||||
* 无审计污染地回填迁移后缺失的包摘要,仅处理 package_hash 为空的旧记录。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @param packageHash 包哈希
|
||||
* @param resourceCount 资源总数
|
||||
* @param referenceCount 引用数
|
||||
* @param scriptCount 脚本数
|
||||
* @param assetCount 二进制资源数
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill SET package_hash=#{packageHash}, resource_count=#{resourceCount}, "
|
||||
+ "reference_count=#{referenceCount}, script_count=#{scriptCount}, asset_count=#{assetCount}, "
|
||||
+ "modified=modified, modified_by=modified_by "
|
||||
+ "WHERE id=#{id} AND tenant_id=#{tenantId} AND package_hash IS NULL")
|
||||
int backfillPackageSummary(@Param("id") BigInteger id,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("packageHash") String packageHash,
|
||||
@Param("resourceCount") Integer resourceCount,
|
||||
@Param("referenceCount") Integer referenceCount,
|
||||
@Param("scriptCount") Integer scriptCount,
|
||||
@Param("assetCount") Integer assetCount);
|
||||
|
||||
/**
|
||||
* 无审计污染地回填迁移后缺失的能力哈希。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @param capabilityHash 能力哈希
|
||||
* @return 更新行数
|
||||
*/
|
||||
@Update("UPDATE tb_skill SET capability_hash=#{capabilityHash}, modified=modified, modified_by=modified_by "
|
||||
+ "WHERE id=#{id} AND tenant_id=#{tenantId} AND capability_hash IS NULL")
|
||||
int backfillCapabilityHash(@Param("id") BigInteger id,
|
||||
@Param("tenantId") BigInteger tenantId,
|
||||
@Param("capabilityHash") String capabilityHash);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
|
||||
/**
|
||||
* Skill reference Mapper。
|
||||
*/
|
||||
public interface SkillReferenceMapper extends BaseMapper<SkillReference> {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
|
||||
/**
|
||||
* Skill 通用资源 Mapper。
|
||||
*/
|
||||
public interface SkillResourceMapper extends BaseMapper<SkillResource> {
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.mapper;
|
||||
|
||||
import com.mybatisflex.core.BaseMapper;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
|
||||
/**
|
||||
* Skill script Mapper。
|
||||
*/
|
||||
public interface SkillScriptMapper extends BaseMapper<SkillScript> {
|
||||
}
|
||||
@@ -2,12 +2,19 @@ package tech.easyflow.skill.publish;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import tech.easyflow.ai.enums.PublishStatus;
|
||||
import tech.easyflow.ai.publish.AbstractAiResourceLifecycleHandler;
|
||||
import tech.easyflow.approval.entity.ApprovalInstance;
|
||||
import tech.easyflow.approval.entity.vo.ApprovalSubmitRequest;
|
||||
import tech.easyflow.approval.enums.ApprovalActionType;
|
||||
import tech.easyflow.approval.enums.ApprovalResourceType;
|
||||
import tech.easyflow.approval.service.ApprovalInstanceService;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.service.SkillService;
|
||||
import tech.easyflow.system.enums.CategoryResourceType;
|
||||
import tech.easyflow.system.enums.ResourceAction;
|
||||
@@ -24,7 +31,9 @@ import java.util.Map;
|
||||
public class SkillApprovalSubjectHandler extends AbstractAiResourceLifecycleHandler<Skill> {
|
||||
|
||||
private final SkillService skillService;
|
||||
private final SkillMapper skillMapper;
|
||||
private final ResourceAccessService resourceAccessService;
|
||||
private final ApprovalInstanceService approvalInstanceService;
|
||||
|
||||
/**
|
||||
* 创建 Skill 审批资源处理器。
|
||||
@@ -32,15 +41,19 @@ public class SkillApprovalSubjectHandler extends AbstractAiResourceLifecycleHand
|
||||
* @param approvalInstanceService 审批实例服务
|
||||
* @param objectMapper JSON 映射器
|
||||
* @param skillService Skill 服务
|
||||
* @param skillMapper Skill Mapper
|
||||
* @param resourceAccessService 资源访问服务
|
||||
*/
|
||||
public SkillApprovalSubjectHandler(ApprovalInstanceService approvalInstanceService,
|
||||
ObjectMapper objectMapper,
|
||||
SkillService skillService,
|
||||
SkillMapper skillMapper,
|
||||
ResourceAccessService resourceAccessService) {
|
||||
super(approvalInstanceService, objectMapper);
|
||||
this.skillService = skillService;
|
||||
this.skillMapper = skillMapper;
|
||||
this.resourceAccessService = resourceAccessService;
|
||||
this.approvalInstanceService = approvalInstanceService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,18 +69,31 @@ public class SkillApprovalSubjectHandler extends AbstractAiResourceLifecycleHand
|
||||
*/
|
||||
@Override
|
||||
public void assertPublishedAccess(Object identifier, String denyMessage) {
|
||||
Skill skill = skillService.getById(String.valueOf(identifier));
|
||||
Skill skill = findCurrentTenantSkill(new BigInteger(String.valueOf(identifier)), false);
|
||||
if (skill == null || !PublishStatus.from(skill.getPublishStatus()).isExternallyVisible()
|
||||
|| skill.getPublishedSnapshotJson() == null || skill.getPublishedSnapshotJson().isEmpty()) {
|
||||
throw new BusinessException(denyMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public ApprovalSubmitRequest buildSubmitRequest(BigInteger resourceId, String actionType, BigInteger operatorId) {
|
||||
ApprovalSubmitRequest request = super.buildSubmitRequest(resourceId, actionType, operatorId);
|
||||
if (ApprovalActionType.PUBLISH.getCode().equals(request.getActionType())) {
|
||||
skillService.retainSnapshotContents(readResourceSnapshot(request.getSnapshotJson()));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Skill requireResource(BigInteger resourceId) {
|
||||
Skill skill = skillService.getById(resourceId);
|
||||
// 生命周期提交与审批决策均在事务中执行,行锁串行化同一 Skill 的状态迁移。
|
||||
Skill skill = findCurrentTenantSkill(resourceId, true);
|
||||
if (skill == null) {
|
||||
throw new BusinessException("Skill 不存在");
|
||||
throw new BusinessException(404, 404, "Skill 不存在");
|
||||
}
|
||||
return skill;
|
||||
}
|
||||
@@ -109,44 +135,108 @@ public class SkillApprovalSubjectHandler extends AbstractAiResourceLifecycleHand
|
||||
return skillService.buildPublishSnapshot(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除审批只记录最小治理信息,避免失效能力阻断删除或把提示词、资源内容及能力配置写入审批快照。
|
||||
*
|
||||
* @param resource Skill
|
||||
* @return 删除审批治理快照
|
||||
*/
|
||||
@Override
|
||||
protected Map<String, Object> buildDeleteResourceSnapshot(Skill resource) {
|
||||
return skillService.buildGovernanceSnapshot(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 优先使用稳定快照 hash 判断内容是否变化,兼容旧快照中的时间字段。
|
||||
*
|
||||
* @param currentSnapshot 当前草稿快照
|
||||
* @param publishedSnapshot 已发布快照
|
||||
* @return 内容一致时为 true
|
||||
*/
|
||||
@Override
|
||||
protected boolean isSameSnapshot(Map<String, Object> currentSnapshot, Map<String, Object> publishedSnapshot) {
|
||||
Object currentHash = currentSnapshot == null ? null : currentSnapshot.get("snapshotHash");
|
||||
Object publishedHash = publishedSnapshot == null ? null : publishedSnapshot.get("snapshotHash");
|
||||
if (currentHash != null && publishedHash != null) {
|
||||
return currentHash.equals(publishedHash);
|
||||
}
|
||||
return super.isSameSnapshot(currentSnapshot, publishedSnapshot);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void persistResourceState(BigInteger resourceId, PublishStatus publishStatus, BigInteger currentApprovalInstanceId) {
|
||||
Skill skill = new Skill();
|
||||
skill.setId(resourceId);
|
||||
skill.setPublishStatus(publishStatus.getCode());
|
||||
skill.setCurrentApprovalInstanceId(currentApprovalInstanceId);
|
||||
skillService.updateById(skill);
|
||||
Skill existing = requireResource(resourceId);
|
||||
if (skillMapper.updateApprovalState(resourceId, existing.getTenantId(), publishStatus.getCode(),
|
||||
currentApprovalInstanceId) != 1) {
|
||||
throw new BusinessException(500, 500, "更新 Skill 审批状态失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void publishResource(BigInteger resourceId, Map<String, Object> resourceSnapshot, BigInteger operatorId) {
|
||||
Skill skill = new Skill();
|
||||
skill.setId(resourceId);
|
||||
skill.setPublishStatus(PublishStatus.PUBLISHED.getCode());
|
||||
skill.setPublishedSnapshotJson(resourceSnapshot);
|
||||
skill.setPublishedAt(new Date());
|
||||
skill.setPublishedBy(operatorId);
|
||||
skill.setCurrentApprovalInstanceId(null);
|
||||
skillService.updateById(skill);
|
||||
Skill existing = requireResource(resourceId);
|
||||
if (skillMapper.publish(resourceId, existing.getTenantId(), resourceSnapshot, new Date(), operatorId,
|
||||
stringValue(resourceSnapshot.get("snapshotHash"))) != 1) {
|
||||
throw new BusinessException(500, 500, "发布 Skill 失败,请稍后重试");
|
||||
}
|
||||
skillService.releaseSnapshotContents(existing.getPublishedSnapshotJson());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void markResourceOffline(BigInteger resourceId) {
|
||||
Skill skill = new Skill();
|
||||
skill.setId(resourceId);
|
||||
skill.setPublishStatus(PublishStatus.OFFLINE.getCode());
|
||||
skill.setCurrentApprovalInstanceId(null);
|
||||
skillService.updateById(skill);
|
||||
Skill existing = requireResource(resourceId);
|
||||
if (skillMapper.markOffline(resourceId, existing.getTenantId()) != 1) {
|
||||
throw new BusinessException(500, 500, "下线 Skill 失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void removeResource(BigInteger resourceId) {
|
||||
skillService.removeAggregate(resourceId);
|
||||
skillService.removeLifecycleAggregate(resourceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String resourceLabel() {
|
||||
return "Skill";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 审批驳回或撤回时释放发布候选快照持有的二进制内容。
|
||||
*
|
||||
* @param resourceId Skill ID
|
||||
* @param previousStatus 审批前发布状态
|
||||
*/
|
||||
@Override
|
||||
public void restoreState(BigInteger resourceId, PublishStatus previousStatus) {
|
||||
Skill skill = requireResource(resourceId);
|
||||
BigInteger instanceId = skill.getCurrentApprovalInstanceId();
|
||||
if (instanceId != null) {
|
||||
ApprovalInstance instance = approvalInstanceService.getById(instanceId);
|
||||
if (instance == null) {
|
||||
throw new BusinessException(500, 500, "Skill 审批状态异常,无法安全恢复内容引用");
|
||||
}
|
||||
if (ApprovalActionType.PUBLISH.getCode().equals(instance.getActionType())) {
|
||||
skillService.releaseSnapshotContents(readResourceSnapshot(instance.getSnapshotJson()));
|
||||
}
|
||||
}
|
||||
super.restoreState(resourceId, previousStatus);
|
||||
}
|
||||
|
||||
private String stringValue(Object value) {
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
private Skill findCurrentTenantSkill(BigInteger id, boolean forUpdate) {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
QueryWrapper query = QueryWrapper.create()
|
||||
.eq(Skill::getId, id)
|
||||
.eq(Skill::getTenantId, account.getTenantId());
|
||||
if (forUpdate) {
|
||||
query.forUpdate();
|
||||
}
|
||||
return skillMapper.selectOneByQuery(query);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,12 +61,15 @@ public class SkillPublishAppService {
|
||||
if (id == null) {
|
||||
throw new BusinessException("Skill 审批时资源ID不能为空");
|
||||
}
|
||||
tech.easyflow.common.entity.LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return aiResourceLifecycleService.submitAction(
|
||||
ApprovalResourceType.SKILL.getCode(),
|
||||
id,
|
||||
actionType.getCode(),
|
||||
SaTokenUtil.getLoginAccount().getId()
|
||||
account.getId()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,13 +4,21 @@ import com.easyagents.skill.model.SkillDescriptor;
|
||||
import com.easyagents.skill.repository.SkillRepository;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
import tech.easyflow.skill.service.SkillService;
|
||||
import tech.easyflow.skill.security.SkillVisibilityQueryHelper;
|
||||
import tech.easyflow.skill.store.DBSkillContentStore;
|
||||
import tech.easyflow.skill.support.SkillModelConverter;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -20,24 +28,45 @@ import java.util.Optional;
|
||||
public class DBSkillRepository implements SkillRepository {
|
||||
|
||||
private final SkillService skillService;
|
||||
private final DBSkillContentStore contentStore;
|
||||
private final SkillVisibilityQueryHelper visibilityQueryHelper;
|
||||
|
||||
/**
|
||||
* 创建数据库 Skill 仓储。
|
||||
*
|
||||
* @param skillService Skill 服务
|
||||
* @param contentStore 二进制内容仓库
|
||||
* @param visibilityQueryHelper 可见性查询助手
|
||||
*/
|
||||
public DBSkillRepository(SkillService skillService) {
|
||||
public DBSkillRepository(SkillService skillService,
|
||||
DBSkillContentStore contentStore,
|
||||
SkillVisibilityQueryHelper visibilityQueryHelper) {
|
||||
this.skillService = skillService;
|
||||
this.contentStore = contentStore;
|
||||
this.visibilityQueryHelper = visibilityQueryHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* 保存 Skill,并转移新增二进制内容引用的所有权。
|
||||
*
|
||||
* <p>调用方在新增 Skill 或为已有 Skill 增加二进制资源前,必须通过内容仓库的
|
||||
* {@code put}/{@code commit} 为每个新增资源取得一份引用。保存成功后,这些新增引用转由
|
||||
* Skill 聚合持有;保存失败时不发生所有权转移,本方法产生的引用计数变更随事务回滚,
|
||||
* 调用方仍负责释放在外部事务中预先取得的新引用。更新时,旧、新资源多重集的交集复用旧
|
||||
* 聚合已有所有权,本适配器会在替换前 retain 相同次数,以抵消资源替换对旧聚合的 release;
|
||||
* 仅出现在新聚合中的引用直接接管调用方已取得的引用。</p>
|
||||
*
|
||||
* @param skill 待保存的 Skill 聚合
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void save(com.easyagents.skill.model.Skill skill) {
|
||||
requireAccount();
|
||||
Skill entity = SkillModelConverter.fromAgentSkill(skill);
|
||||
BigInteger parsedId = tryParseId(skill.getId());
|
||||
if (parsedId != null && skillService.getById(parsedId) != null) {
|
||||
if (parsedId != null && findReadable(parsedId) != null) {
|
||||
Skill existing = skillService.getDetail(parsedId);
|
||||
retainReusedContentRefs(existing.getResources(), entity.getResources());
|
||||
entity.setId(parsedId);
|
||||
skillService.updateDraft(entity);
|
||||
return;
|
||||
@@ -45,12 +74,62 @@ public class DBSkillRepository implements SkillRepository {
|
||||
skillService.saveDraft(entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为旧、新资源多重集的交集增加临时持有,抵消替换流程对旧聚合引用的统一释放。
|
||||
*
|
||||
* @param existingResources 旧聚合资源
|
||||
* @param incomingResources 新聚合资源
|
||||
*/
|
||||
private void retainReusedContentRefs(List<SkillResource> existingResources,
|
||||
List<SkillResource> incomingResources) {
|
||||
Map<String, Integer> remainingOldRefs = contentRefCounts(existingResources);
|
||||
if (incomingResources == null || incomingResources.isEmpty() || remainingOldRefs.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (SkillResource resource : incomingResources) {
|
||||
String contentRef = resource == null ? null : resource.getContentRef();
|
||||
Integer remaining = remainingOldRefs.get(contentRef);
|
||||
if (remaining == null || remaining <= 0) {
|
||||
continue;
|
||||
}
|
||||
contentStore.retain(contentRef);
|
||||
if (remaining == 1) {
|
||||
remainingOldRefs.remove(contentRef);
|
||||
} else {
|
||||
remainingOldRefs.put(contentRef, remaining - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计二进制内容引用多重集。
|
||||
*
|
||||
* @param resources Skill 资源
|
||||
* @return contentRef 到出现次数的映射
|
||||
*/
|
||||
private Map<String, Integer> contentRefCounts(List<SkillResource> resources) {
|
||||
Map<String, Integer> counts = new HashMap<>();
|
||||
if (resources == null) {
|
||||
return counts;
|
||||
}
|
||||
for (SkillResource resource : resources) {
|
||||
String contentRef = resource == null ? null : resource.getContentRef();
|
||||
if (contentRef != null && !contentRef.isBlank()) {
|
||||
counts.merge(contentRef, 1, Integer::sum);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Optional<com.easyagents.skill.model.Skill> get(String skillId) {
|
||||
BigInteger id = parseId(skillId);
|
||||
if (findReadable(id) == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Skill skill = skillService.getDetail(id);
|
||||
return Optional.of(SkillModelConverter.toAgentSkill(skill));
|
||||
}
|
||||
@@ -61,7 +140,9 @@ public class DBSkillRepository implements SkillRepository {
|
||||
@Override
|
||||
public Optional<SkillDescriptor> getDescriptor(String skillId) {
|
||||
BigInteger id = parseId(skillId);
|
||||
Skill skill = skillService.getById(id);
|
||||
QueryWrapper query = descriptorQuery().eq(Skill::getId, id);
|
||||
visibilityQueryHelper.applyReadableAccess(query);
|
||||
Skill skill = skillService.getOne(query);
|
||||
if (skill == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -74,7 +155,10 @@ public class DBSkillRepository implements SkillRepository {
|
||||
*/
|
||||
@Override
|
||||
public List<SkillDescriptor> listDescriptors() {
|
||||
return skillService.list().stream()
|
||||
requireAccount();
|
||||
QueryWrapper query = descriptorQuery();
|
||||
visibilityQueryHelper.applyReadableAccess(query);
|
||||
return skillService.list(query).stream()
|
||||
.map(skill -> new SkillDescriptor(String.valueOf(skill.getId()), skill.getName(), skill.getDescription(),
|
||||
new com.easyagents.skill.model.SkillMetadata(skill.getMetadataJson())))
|
||||
.toList();
|
||||
@@ -94,14 +178,41 @@ public class DBSkillRepository implements SkillRepository {
|
||||
@Override
|
||||
public boolean exists(String skillId) {
|
||||
BigInteger id = parseId(skillId);
|
||||
return skillService.count(QueryWrapper.create().eq(Skill::getId, id)) > 0;
|
||||
QueryWrapper query = QueryWrapper.create().eq(Skill::getId, id);
|
||||
visibilityQueryHelper.applyReadableAccess(query);
|
||||
return skillService.count(query) > 0;
|
||||
}
|
||||
|
||||
private Skill findReadable(BigInteger id) {
|
||||
QueryWrapper query = QueryWrapper.create().eq(Skill::getId, id);
|
||||
visibilityQueryHelper.applyReadableAccess(query);
|
||||
return skillService.getOne(query);
|
||||
}
|
||||
|
||||
private QueryWrapper descriptorQuery() {
|
||||
return QueryWrapper.create().select(
|
||||
"id", "tenant_id", "dept_id", "category_id", "name", "description", "metadata_json",
|
||||
"visibility_scope", "created_by");
|
||||
}
|
||||
|
||||
private LoginAccount requireAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
private BigInteger parseId(String skillId) {
|
||||
requireAccount();
|
||||
if (skillId == null || skillId.isBlank()) {
|
||||
throw new BusinessException("Skill ID 不能为空");
|
||||
}
|
||||
return new BigInteger(skillId);
|
||||
try {
|
||||
return new BigInteger(skillId);
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new BusinessException("Skill ID 格式不正确");
|
||||
}
|
||||
}
|
||||
|
||||
private BigInteger tryParseId(String skillId) {
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
package tech.easyflow.skill.security;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.Normalizer;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* EasyFlow 平台附加配置中的高置信凭据值检测器。
|
||||
*
|
||||
* <p>该检测器只用于能力配置和增强包元数据,不应用于标准 Skill 文档或资源正文。</p>
|
||||
*/
|
||||
public final class SkillCredentialValueGuard {
|
||||
|
||||
private static final int MAX_PERCENT_DECODE_PASSES = 5;
|
||||
private static final Pattern URI_USER_INFO = Pattern.compile(
|
||||
"(?i)\\b[a-z][a-z0-9+.-]*://([^\\s/?#@]+)@");
|
||||
private static final Pattern ASSIGNMENT = Pattern.compile(
|
||||
"(?i)(?:^|[\\s?&#{\\[,;])['\"]?([A-Z0-9_.\\[\\]-]{1,160})['\"]?\\s*[:=]\\s*");
|
||||
private static final Pattern AUTHORIZATION_SCHEME = Pattern.compile("(?i)^(?:bearer|basic)\\s+");
|
||||
private static final Pattern STANDALONE_AUTHORIZATION_SCHEME = Pattern.compile(
|
||||
"(?i)(?<![A-Za-z0-9])(bearer|basic)\\s+");
|
||||
private static final Pattern PRIVATE_KEY_MARKER = Pattern.compile(
|
||||
"(?i)-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----");
|
||||
private static final Pattern COMMON_TOKEN_PREFIX = Pattern.compile(
|
||||
"(?<![A-Za-z0-9])(?:sk-proj-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{20,}|"
|
||||
+ "gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{20,}|"
|
||||
+ "glpat-[A-Za-z0-9_-]{20,}|hf_[A-Za-z0-9]{20,}|"
|
||||
+ "(?:sk|pk)_(?:live|test)_[A-Za-z0-9]{16,}|npm_[A-Za-z0-9]{20,}|"
|
||||
+ "AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,})(?![A-Za-z0-9])");
|
||||
private static final Pattern JWT = Pattern.compile(
|
||||
"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]{8,}"
|
||||
+ "(?![A-Za-z0-9_-])");
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile(
|
||||
"(?i)^(?:\\$\\{[A-Z0-9_.:-]+}|\\{\\{\\s*[A-Z0-9_.:-]+\\s*}}|"
|
||||
+ "<[A-Z0-9_.:-]+>|\\[(?:REDACTED|MASKED|HIDDEN|TOKEN|API[-_]?KEY|SECRET|PASSWORD)]|"
|
||||
+ "\\*{3,})$");
|
||||
private static final Pattern SAFE_SENTINEL = Pattern.compile(
|
||||
"(?i)^(?:none|null|unset|disabled|not[-_ ]?set|n/?a)$");
|
||||
private static final Set<String> AUTH_PROSE_WORDS = Set.of(
|
||||
"authentication", "authorization", "credentials", "credential", "information",
|
||||
"header", "scheme", "token", "example", "placeholder");
|
||||
|
||||
/**
|
||||
* 禁止实例化纯静态安全工具。
|
||||
*/
|
||||
private SkillCredentialValueGuard() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否包含可识别的实际凭据材料。
|
||||
*
|
||||
* @param value 待检查的平台附加配置值
|
||||
* @return 检测到实际凭据时为 true
|
||||
*/
|
||||
public static boolean containsCredential(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String candidate = normalize(value);
|
||||
for (int pass = 0; pass <= MAX_PERCENT_DECODE_PASSES; pass++) {
|
||||
if (containsCredentialNormalized(candidate)) {
|
||||
return true;
|
||||
}
|
||||
String decoded = percentDecode(candidate);
|
||||
if (decoded.equals(candidate)) {
|
||||
return false;
|
||||
}
|
||||
if (pass == MAX_PERCENT_DECODE_PASSES) {
|
||||
// 超过有界规范化深度仍持续变化时按高风险输入处理,避免任意层编码绕过。
|
||||
return true;
|
||||
}
|
||||
candidate = normalize(decoded);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对单层规范化文本执行结构化凭据检测。
|
||||
*
|
||||
* @param value 已规范化文本
|
||||
* @return 检测到凭据时为 true
|
||||
*/
|
||||
private static boolean containsCredentialNormalized(String value) {
|
||||
if (PRIVATE_KEY_MARKER.matcher(value).find()
|
||||
|| COMMON_TOKEN_PREFIX.matcher(value).find()
|
||||
|| JWT.matcher(value).find()) {
|
||||
return true;
|
||||
}
|
||||
Matcher userInfoMatcher = URI_USER_INFO.matcher(value);
|
||||
while (userInfoMatcher.find()) {
|
||||
String userInfo = stripWrappingQuotes(userInfoMatcher.group(1));
|
||||
int separator = userInfo.lastIndexOf(':');
|
||||
if (separator >= 0 && !isSafeCredentialScalar(userInfo.substring(separator + 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Matcher assignmentMatcher = ASSIGNMENT.matcher(value);
|
||||
while (assignmentMatcher.find()) {
|
||||
if (!isSensitiveKey(assignmentMatcher.group(1))) {
|
||||
continue;
|
||||
}
|
||||
String assignedValue = extractAssignedValue(value, assignmentMatcher.end());
|
||||
if (assignedValue.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (!isSafeCredentialScalar(assignedValue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Matcher schemeMatcher = STANDALONE_AUTHORIZATION_SCHEME.matcher(value);
|
||||
while (schemeMatcher.find()) {
|
||||
String payload = extractAuthorizationPayload(value, schemeMatcher.end());
|
||||
if (looksLikeAuthorizationPayload(schemeMatcher.group(1), payload)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从赋值分隔符后提取一个受限标量,支持常见引号和占位符形式。
|
||||
*
|
||||
* @param source 完整文本
|
||||
* @param start 值起始位置
|
||||
* @return 去除外层引号的标量
|
||||
*/
|
||||
private static String extractAssignedValue(String source, int start) {
|
||||
int cursor = start;
|
||||
while (cursor < source.length() && Character.isWhitespace(source.charAt(cursor))) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor >= source.length()) {
|
||||
return "";
|
||||
}
|
||||
char first = source.charAt(cursor);
|
||||
if (first == '\'' || first == '"') {
|
||||
int quoteEnd = findClosingQuote(source, cursor, first);
|
||||
if (quoteEnd < 0) {
|
||||
return stripWrappingQuotes(source.substring(cursor));
|
||||
}
|
||||
int end = extendScalarTail(source, quoteEnd + 1);
|
||||
return stripWrappingQuotes(source.substring(cursor, end));
|
||||
}
|
||||
Matcher schemeMatcher = AUTHORIZATION_SCHEME.matcher(source.substring(cursor));
|
||||
if (schemeMatcher.find()) {
|
||||
String payload = extractAssignedValue(source, cursor + schemeMatcher.end());
|
||||
return source.substring(cursor, cursor + schemeMatcher.end()) + payload;
|
||||
}
|
||||
int placeholderEnd = findPairedPlaceholderEnd(source, cursor);
|
||||
if (placeholderEnd >= 0) {
|
||||
return source.substring(cursor, extendScalarTail(source, placeholderEnd)).trim();
|
||||
}
|
||||
int end = cursor;
|
||||
while (end < source.length() && !isScalarDelimiter(source.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return stripWrappingQuotes(source.substring(cursor, end));
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取认证方案后的值;普通说明句保留为整体,供结构化判定区分 Token 与文案。
|
||||
*
|
||||
* @param source 完整文本
|
||||
* @param start 认证值起始位置
|
||||
* @return 认证载荷
|
||||
*/
|
||||
private static String extractAuthorizationPayload(String source, int start) {
|
||||
int cursor = start;
|
||||
while (cursor < source.length() && Character.isWhitespace(source.charAt(cursor))) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor >= source.length()) {
|
||||
return "";
|
||||
}
|
||||
int placeholderEnd = findPairedPlaceholderEnd(source, cursor);
|
||||
if (placeholderEnd >= 0) {
|
||||
return source.substring(cursor, extendScalarTail(source, placeholderEnd)).trim();
|
||||
}
|
||||
int end = cursor;
|
||||
while (end < source.length()
|
||||
&& !Character.isWhitespace(source.charAt(end))
|
||||
&& !isScalarDelimiter(source.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return stripWrappingQuotes(source.substring(cursor, end));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找当前位置开始的成对占位符结束位置。
|
||||
*
|
||||
* @param source 完整文本
|
||||
* @param start 起始位置
|
||||
* @return 占位符结束位置(不含);当前位置不是完整占位符时返回 -1
|
||||
*/
|
||||
private static int findPairedPlaceholderEnd(String source, int start) {
|
||||
String closing;
|
||||
if (source.startsWith("${", start)) {
|
||||
closing = "}";
|
||||
} else if (source.startsWith("{{", start)) {
|
||||
closing = "}}";
|
||||
} else if (source.startsWith("<", start)) {
|
||||
closing = ">";
|
||||
} else if (source.startsWith("[", start)) {
|
||||
closing = "]";
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
int end = source.indexOf(closing, start + 1);
|
||||
return end < 0 ? -1 : end + closing.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找未转义的结束引号。
|
||||
*
|
||||
* @param source 完整文本
|
||||
* @param start 起始引号位置
|
||||
* @param quote 引号字符
|
||||
* @return 结束引号位置;未闭合时返回 -1
|
||||
*/
|
||||
private static int findClosingQuote(String source, int start, char quote) {
|
||||
boolean escaped = false;
|
||||
for (int index = start + 1; index < source.length(); index++) {
|
||||
char current = source.charAt(index);
|
||||
if (current == quote && !escaped) {
|
||||
return index;
|
||||
}
|
||||
escaped = current == '\\' && !escaped;
|
||||
if (current != '\\') {
|
||||
escaped = false;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将紧邻占位符或引号的尾随字符纳入同一标量,避免占位符前缀绕过。
|
||||
*
|
||||
* @param source 完整文本
|
||||
* @param start 尾随内容起始位置
|
||||
* @return 标量结束位置
|
||||
*/
|
||||
private static int extendScalarTail(String source, int start) {
|
||||
int end = start;
|
||||
while (end < source.length() && !isScalarDelimiter(source.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符是否结束当前凭据标量。
|
||||
*
|
||||
* @param value 待判断字符
|
||||
* @return 属于结构分隔符时为 true
|
||||
*/
|
||||
private static boolean isScalarDelimiter(char value) {
|
||||
return value == ',' || value == ';' || value == '}' || value == ']'
|
||||
|| value == '&' || value == '#';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断提取值是否为明确的非凭据占位符。
|
||||
*
|
||||
* @param value 提取值
|
||||
* @return 属于允许占位符时为 true
|
||||
*/
|
||||
private static boolean isPlaceholder(String value) {
|
||||
return PLACEHOLDER.matcher(stripWrappingQuotes(value).trim()).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断赋值或认证方案后的标量是否明确不含真实凭据。
|
||||
*
|
||||
* @param value 原始标量
|
||||
* @return 完整占位符或明确空值哨兵时为 true
|
||||
*/
|
||||
private static boolean isSafeCredentialScalar(String value) {
|
||||
String scalar = stripWrappingQuotes(value).trim();
|
||||
if ("bearer".equalsIgnoreCase(scalar) || "basic".equalsIgnoreCase(scalar)) {
|
||||
return true;
|
||||
}
|
||||
Matcher schemeMatcher = AUTHORIZATION_SCHEME.matcher(scalar);
|
||||
if (schemeMatcher.find()) {
|
||||
String scheme = scalar.substring(0, schemeMatcher.end()).trim();
|
||||
String payload = scalar.substring(schemeMatcher.end()).trim();
|
||||
return !looksLikeAuthorizationPayload(scheme, payload);
|
||||
}
|
||||
return isPlaceholder(scalar) || SAFE_SENTINEL.matcher(scalar).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断认证方案后的载荷是否具有实际凭据结构。
|
||||
*
|
||||
* @param scheme 认证方案
|
||||
* @param value 认证载荷
|
||||
* @return 具有实际凭据结构时为 true
|
||||
*/
|
||||
private static boolean looksLikeAuthorizationPayload(String scheme, String value) {
|
||||
String payload = stripWrappingQuotes(value).trim();
|
||||
if (payload.isEmpty() || isPlaceholder(payload) || SAFE_SENTINEL.matcher(payload).matches()) {
|
||||
return false;
|
||||
}
|
||||
int placeholderEnd = findPairedPlaceholderEnd(payload, 0);
|
||||
if (placeholderEnd > 0 && !payload.substring(placeholderEnd).trim().isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
if (payload.chars().anyMatch(Character::isWhitespace)) {
|
||||
return false;
|
||||
}
|
||||
if (AUTH_PROSE_WORDS.contains(payload.toLowerCase(Locale.ROOT))) {
|
||||
return false;
|
||||
}
|
||||
if ("basic".equalsIgnoreCase(scheme)) {
|
||||
return isBasicCredential(payload);
|
||||
}
|
||||
return payload.length() >= 12 && payload.matches("[A-Za-z0-9._~+/=-]+");
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 Basic 载荷是否能解码为 user:secret 结构。
|
||||
*
|
||||
* @param payload Base64 载荷
|
||||
* @return 符合 Basic 凭据结构时为 true
|
||||
*/
|
||||
private static boolean isBasicCredential(String payload) {
|
||||
if (payload.length() < 8 || !payload.matches("[A-Za-z0-9+/]+={0,2}")) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(payload);
|
||||
String text = new String(decoded, StandardCharsets.UTF_8);
|
||||
int separator = text.indexOf(':');
|
||||
return separator > 0 && separator < text.length() - 1
|
||||
&& text.chars().noneMatch(Character::isISOControl);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断赋值左侧字段是否属于凭据语义。
|
||||
*
|
||||
* @param key 原始字段名
|
||||
* @return 敏感字段时为 true
|
||||
*/
|
||||
private static boolean isSensitiveKey(String key) {
|
||||
String normalized = normalize(key).toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", "");
|
||||
return normalized.equals("key")
|
||||
|| normalized.endsWith("authorization")
|
||||
|| normalized.endsWith("apikey")
|
||||
|| normalized.endsWith("accesskey")
|
||||
|| normalized.endsWith("secretaccesskey")
|
||||
|| normalized.endsWith("accesstoken")
|
||||
|| normalized.endsWith("refreshtoken")
|
||||
|| normalized.endsWith("idtoken")
|
||||
|| normalized.endsWith("authtoken")
|
||||
|| normalized.endsWith("token")
|
||||
|| normalized.endsWith("clientsecret")
|
||||
|| normalized.endsWith("password")
|
||||
|| normalized.endsWith("passwd")
|
||||
|| normalized.endsWith("secret")
|
||||
|| normalized.endsWith("cookie")
|
||||
|| normalized.endsWith("session")
|
||||
|| normalized.endsWith("sessionid")
|
||||
|| normalized.endsWith("credential")
|
||||
|| normalized.endsWith("signature");
|
||||
}
|
||||
|
||||
/**
|
||||
* 去除成对单引号或双引号。
|
||||
*
|
||||
* @param value 原始标量
|
||||
* @return 去除外层引号的标量
|
||||
*/
|
||||
private static String stripWrappingQuotes(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
if (trimmed.length() >= 2) {
|
||||
char first = trimmed.charAt(0);
|
||||
char last = trimmed.charAt(trimmed.length() - 1);
|
||||
if ((first == '\'' && last == '\'') || (first == '"' && last == '"')) {
|
||||
return trimmed.substring(1, trimmed.length() - 1).trim();
|
||||
}
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 Unicode 兼容规范化。
|
||||
*
|
||||
* @param value 原始文本
|
||||
* @return NFKC 文本
|
||||
*/
|
||||
private static String normalize(String value) {
|
||||
String normalized = Normalizer.normalize(value, Normalizer.Form.NFKC);
|
||||
StringBuilder visible = new StringBuilder(normalized.length());
|
||||
normalized.codePoints()
|
||||
.filter(codePoint -> Character.getType(codePoint) != Character.FORMAT)
|
||||
.filter(codePoint -> !Character.isISOControl(codePoint))
|
||||
.forEach(visible::appendCodePoint);
|
||||
return visible.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试解码一层百分号转义,非法转义保持原文。
|
||||
*
|
||||
* @param value 原始文本
|
||||
* @return 解码结果或原文
|
||||
*/
|
||||
private static String percentDecode(String value) {
|
||||
try {
|
||||
StringBuilder escapedInvalidPercent = new StringBuilder(value.length());
|
||||
for (int index = 0; index < value.length(); index++) {
|
||||
char current = value.charAt(index);
|
||||
if (current == '%' && (index + 2 >= value.length()
|
||||
|| !isHexDigit(value.charAt(index + 1))
|
||||
|| !isHexDigit(value.charAt(index + 2)))) {
|
||||
escapedInvalidPercent.append("%25");
|
||||
} else {
|
||||
escapedInvalidPercent.append(current);
|
||||
}
|
||||
}
|
||||
return URLDecoder.decode(escapedInvalidPercent.toString(), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符是否为十六进制数字。
|
||||
*
|
||||
* @param value 待判断字符
|
||||
* @return 十六进制数字时为 true
|
||||
*/
|
||||
private static boolean isHexDigit(char value) {
|
||||
return value >= '0' && value <= '9'
|
||||
|| value >= 'a' && value <= 'f'
|
||||
|| value >= 'A' && value <= 'F';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package tech.easyflow.skill.security;
|
||||
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Skill 跨环境目标引用和展示元数据的安全校验器。
|
||||
*/
|
||||
public final class SkillPortableTargetSanitizer {
|
||||
|
||||
private static final Pattern LOGICAL_SEGMENT = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,199}");
|
||||
private static final Pattern URI_USER_INFO = Pattern.compile(
|
||||
"(?i)\\b[a-z][a-z0-9+.-]*://[^\\s/?#]*@");
|
||||
private static final Pattern CREDENTIAL_QUERY = Pattern.compile(
|
||||
"(?i)[?&;](?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|key|"
|
||||
+ "secret|client[_-]?secret|password|passwd|authorization|auth|"
|
||||
+ "(?:x-amz-)?signature|credential)\\s*=");
|
||||
private static final Pattern ABSOLUTE_PATH = Pattern.compile(
|
||||
"(?:^|[^A-Za-z0-9_.:/-])(?:/(?!/)[^\\s]+|\\\\\\\\[^\\s]+|"
|
||||
+ "[A-Za-z]:[\\\\/][^\\s]+|~[\\\\/][^\\s]+)");
|
||||
private static final Pattern FILE_URI = Pattern.compile("(?i)\\bfile:(?://)?[/\\\\]");
|
||||
|
||||
/**
|
||||
* 禁止实例化纯静态安全工具。
|
||||
*/
|
||||
private SkillPortableTargetSanitizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断逻辑引用是否符合当前能力类型的严格可移植语法。
|
||||
*
|
||||
* @param type 能力类型
|
||||
* @param logicalRef 待校验逻辑引用
|
||||
* @return 符合安全语法时为 true
|
||||
*/
|
||||
public static boolean isSafeLogicalRef(SkillCapabilityType type, String logicalRef) {
|
||||
if (type == null || logicalRef == null || logicalRef.isBlank()
|
||||
|| SkillCredentialValueGuard.containsCredential(logicalRef)) {
|
||||
return false;
|
||||
}
|
||||
if (unresolvedRef(type).equals(logicalRef)) {
|
||||
return true;
|
||||
}
|
||||
return switch (type) {
|
||||
case WORKFLOW -> hasSingleSafeSegment(logicalRef, "workflow:");
|
||||
case MCP -> hasSingleSafeSegment(logicalRef, "mcp:");
|
||||
case PLUGIN_ITEM -> hasTwoSafeSegments(logicalRef, "plugin-item:");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回安全逻辑引用;历史脏值统一降级为不可解析引用。
|
||||
*
|
||||
* @param type 能力类型
|
||||
* @param logicalRef 原始逻辑引用
|
||||
* @return 安全逻辑引用
|
||||
*/
|
||||
public static String safeLogicalRefOrUnresolved(SkillCapabilityType type, String logicalRef) {
|
||||
return isSafeLogicalRef(type, logicalRef) ? logicalRef : unresolvedRef(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造能力类型对应的不可解析逻辑引用。
|
||||
*
|
||||
* @param type 能力类型
|
||||
* @return 不可解析逻辑引用
|
||||
*/
|
||||
public static String unresolvedRef(SkillCapabilityType type) {
|
||||
return "unresolved:" + type.name().toLowerCase(Locale.ROOT).replace('_', '-');
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断展示元数据是否不含凭据式 URI、认证查询参数和绝对路径。
|
||||
*
|
||||
* @param value 待校验元数据
|
||||
* @return 可安全写入增强包时为 true
|
||||
*/
|
||||
public static boolean isSafePortableMetadata(String value) {
|
||||
if (value == null) {
|
||||
return true;
|
||||
}
|
||||
String normalized = value;
|
||||
for (int pass = 0; pass < 3; pass++) {
|
||||
if (!isSafePortableMetadataValue(normalized)) {
|
||||
return false;
|
||||
}
|
||||
String decoded = percentDecode(normalized);
|
||||
if (decoded.equals(normalized)) {
|
||||
return true;
|
||||
}
|
||||
normalized = decoded;
|
||||
}
|
||||
return isSafePortableMetadataValue(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回安全展示元数据;空白或不安全内容返回 null。
|
||||
*
|
||||
* @param value 原始元数据
|
||||
* @return 安全元数据或 null
|
||||
*/
|
||||
public static String safePortableMetadataOrNull(String value) {
|
||||
return value == null || value.isBlank() || !isSafePortableMetadata(value) ? null : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单段类型逻辑引用。
|
||||
*
|
||||
* @param logicalRef 逻辑引用
|
||||
* @param prefix 类型前缀
|
||||
* @return 单段符合安全语法时为 true
|
||||
*/
|
||||
private static boolean hasSingleSafeSegment(String logicalRef, String prefix) {
|
||||
return logicalRef.startsWith(prefix)
|
||||
&& LOGICAL_SEGMENT.matcher(logicalRef.substring(prefix.length())).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验插件与工具组成的双段逻辑引用。
|
||||
*
|
||||
* @param logicalRef 逻辑引用
|
||||
* @param prefix 类型前缀
|
||||
* @return 两段均符合安全语法时为 true
|
||||
*/
|
||||
private static boolean hasTwoSafeSegments(String logicalRef, String prefix) {
|
||||
if (!logicalRef.startsWith(prefix)) {
|
||||
return false;
|
||||
}
|
||||
String value = logicalRef.substring(prefix.length());
|
||||
int separator = value.indexOf('/');
|
||||
return separator > 0 && separator == value.lastIndexOf('/')
|
||||
&& LOGICAL_SEGMENT.matcher(value.substring(0, separator)).matches()
|
||||
&& LOGICAL_SEGMENT.matcher(value.substring(separator + 1)).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对单次规范化后的元数据执行危险内容检测。
|
||||
*
|
||||
* @param value 元数据
|
||||
* @return 未发现危险内容时为 true
|
||||
*/
|
||||
private static boolean isSafePortableMetadataValue(String value) {
|
||||
return value.chars().noneMatch(Character::isISOControl)
|
||||
&& !SkillCredentialValueGuard.containsCredential(value)
|
||||
&& !URI_USER_INFO.matcher(value).find()
|
||||
&& !CREDENTIAL_QUERY.matcher(value).find()
|
||||
&& !ABSOLUTE_PATH.matcher(value).find()
|
||||
&& !FILE_URI.matcher(value).find();
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试解码一层百分号转义,非法转义保持原文。
|
||||
*
|
||||
* @param value 原始值
|
||||
* @return 解码结果或原文
|
||||
*/
|
||||
private static String percentDecode(String value) {
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
// 非法百分号转义不能安全规范化,按原文继续检查并由调用方的字段语法约束处理。
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package tech.easyflow.skill.security;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Skill 平台配置的敏感字段白名单清洗器。
|
||||
*/
|
||||
public final class SkillSensitiveConfigSanitizer {
|
||||
|
||||
private static final Set<String> HITL_ALLOWED_KEYS = Set.of(
|
||||
"prompt", "title", "description", "confirmLabel", "cancelLabel"
|
||||
);
|
||||
private static final Set<String> OPTIONS_ALLOWED_KEYS = Set.of(
|
||||
"timeoutMs", "retryCount", "async", "readOnly"
|
||||
);
|
||||
|
||||
private SkillSensitiveConfigSanitizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅保留已定义的非敏感 HITL 展示配置。
|
||||
*
|
||||
* @param source 原始 HITL 配置
|
||||
* @return 白名单配置
|
||||
*/
|
||||
public static Map<String, Object> sanitizeHitl(Map<String, Object> source) {
|
||||
return sanitizeAllowed(source, HITL_ALLOWED_KEYS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅保留已定义的非敏感执行选项。
|
||||
*
|
||||
* @param source 原始执行选项
|
||||
* @return 白名单配置
|
||||
*/
|
||||
public static Map<String, Object> sanitizeOptions(Map<String, Object> source) {
|
||||
return sanitizeAllowed(source, OPTIONS_ALLOWED_KEYS);
|
||||
}
|
||||
|
||||
private static Map<String, Object> sanitizeAllowed(Map<String, Object> source, Set<String> allowedKeys) {
|
||||
if (source == null || source.isEmpty()) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
Map<String, Object> sanitized = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> entry : source.entrySet()) {
|
||||
if (entry.getKey() == null || !allowedKeys.contains(entry.getKey())) {
|
||||
continue;
|
||||
}
|
||||
Object value = sanitizeScalar(entry.getValue());
|
||||
if (value != null) {
|
||||
sanitized.put(entry.getKey(), value);
|
||||
}
|
||||
}
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
private static Object sanitizeScalar(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof String || value instanceof Number || value instanceof Boolean) {
|
||||
return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package tech.easyflow.skill.security;
|
||||
|
||||
import com.mybatisflex.core.query.QueryCondition;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.system.entity.vo.RoleCategoryAccessSnapshot;
|
||||
import tech.easyflow.system.enums.CategoryResourceType;
|
||||
import tech.easyflow.system.enums.VisibilityScope;
|
||||
import tech.easyflow.system.service.CategoryPermissionService;
|
||||
import tech.easyflow.system.service.SysDeptService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
import static tech.easyflow.skill.entity.table.SkillTableDef.SKILL;
|
||||
|
||||
/**
|
||||
* 将 Skill 的分类、归属人与可见范围权限转换为数据库可执行的读取条件。
|
||||
*/
|
||||
@Component
|
||||
public class SkillVisibilityQueryHelper {
|
||||
|
||||
private final CategoryPermissionService categoryPermissionService;
|
||||
private final SysDeptService sysDeptService;
|
||||
|
||||
/**
|
||||
* 创建 Skill 可见性查询助手。
|
||||
*
|
||||
* @param categoryPermissionService 分类权限服务
|
||||
* @param sysDeptService 部门服务
|
||||
*/
|
||||
public SkillVisibilityQueryHelper(CategoryPermissionService categoryPermissionService,
|
||||
SysDeptService sysDeptService) {
|
||||
this.categoryPermissionService = categoryPermissionService;
|
||||
this.sysDeptService = sysDeptService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将当前登录用户的 Skill 读取权限追加到查询条件。
|
||||
*
|
||||
* @param queryWrapper 查询条件
|
||||
*/
|
||||
public void applyReadableAccess(QueryWrapper queryWrapper) {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
BigInteger accountId = account == null ? null : account.getId();
|
||||
BigInteger tenantId = account == null ? null : account.getTenantId();
|
||||
if (accountId == null || tenantId == null) {
|
||||
queryWrapper.and(SKILL.ID.eq(BigInteger.valueOf(-1)));
|
||||
return;
|
||||
}
|
||||
// 超级管理员也只能读取当前租户;项目未启用 MyBatis-Flex 全局租户过滤器。
|
||||
queryWrapper.and(SKILL.TENANT_ID.eq(tenantId));
|
||||
RoleCategoryAccessSnapshot access = categoryPermissionService.getCurrentAccess(CategoryResourceType.SKILL.getCode());
|
||||
if (access.isSuperAdmin()) {
|
||||
return;
|
||||
}
|
||||
QueryCondition owner = SKILL.CREATED_BY.eq(accountId);
|
||||
if (access.isRestricted() && access.getCategoryIds().isEmpty()) {
|
||||
queryWrapper.and(owner);
|
||||
return;
|
||||
}
|
||||
Set<BigInteger> readableDeptIds = account.getDeptId() == null
|
||||
? Collections.emptySet() : sysDeptService.getSelfAndAncestorDeptIds(account.getDeptId());
|
||||
QueryCondition visible = SKILL.VISIBILITY_SCOPE.eq(VisibilityScope.PUBLIC.name());
|
||||
if (!readableDeptIds.isEmpty()) {
|
||||
visible = visible.or(SKILL.VISIBILITY_SCOPE.eq(VisibilityScope.DEPT.name())
|
||||
.and(SKILL.DEPT_ID.in(readableDeptIds)));
|
||||
}
|
||||
if (access.isRestricted()) {
|
||||
visible = SKILL.CATEGORY_ID.in(access.getCategoryIds()).and(visible);
|
||||
}
|
||||
QueryCondition readable = owner.or(visible);
|
||||
if (access.isAllAccess()) {
|
||||
// L13 明确约定 ALL 分类范围可以读取未分类 Skill,包括其他创建者的私有草稿。
|
||||
readable = readable.or(SKILL.CATEGORY_ID.isNull());
|
||||
}
|
||||
queryWrapper.and(readable);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.service;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.SkillAssetContent;
|
||||
|
||||
/**
|
||||
* Skill asset 内容索引服务。
|
||||
*/
|
||||
public interface SkillAssetContentService extends IService<SkillAssetContent> {
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.service;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
|
||||
/**
|
||||
* Skill asset 服务。
|
||||
*/
|
||||
public interface SkillAssetService extends IService<SkillAsset> {
|
||||
}
|
||||
@@ -16,4 +16,15 @@ public interface SkillCategoryService extends IService<SkillCategory> {
|
||||
* @param categoryId 分类 ID,可为空
|
||||
*/
|
||||
void validateUsableCategory(BigInteger categoryId);
|
||||
|
||||
/**
|
||||
* 锁定当前租户完整分类树,并校验目标分类可供 Skill 使用。
|
||||
*
|
||||
* <p>Skill 新建、改分类和移出分类必须在同一事务内先调用此方法,再写入
|
||||
* {@code tb_skill.category_id},从而与分类删除形成统一的行锁顺序。</p>
|
||||
*
|
||||
* @param categoryId 分类 ID;为空时仍锁定分类树,以保护从原分类移出的并发操作
|
||||
* @throws tech.easyflow.common.web.exceptions.BusinessException 分类不存在、不可用或登录态无效
|
||||
*/
|
||||
void lockAndValidateUsableCategory(BigInteger categoryId);
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.service;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
|
||||
/**
|
||||
* Skill reference 服务。
|
||||
*/
|
||||
public interface SkillReferenceService extends IService<SkillReference> {
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package tech.easyflow.skill.service;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 通用资源服务。
|
||||
*/
|
||||
public interface SkillResourceService extends IService<SkillResource> {
|
||||
|
||||
/**
|
||||
* 查询资源描述信息,不加载文本正文或二进制内容引用。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @return 按显示顺序排列的资源描述列表
|
||||
*/
|
||||
List<SkillResource> listDescriptors(BigInteger skillId, BigInteger tenantId);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package tech.easyflow.skill.service;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
|
||||
/**
|
||||
* Skill script 服务。
|
||||
*/
|
||||
public interface SkillScriptService extends IService<SkillScript> {
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package tech.easyflow.skill.service;
|
||||
|
||||
import com.mybatisflex.core.service.IService;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Map;
|
||||
@@ -19,6 +20,22 @@ public interface SkillService extends IService<Skill> {
|
||||
*/
|
||||
Skill getDetail(BigInteger id);
|
||||
|
||||
/**
|
||||
* 获取管理端详情,资源仅返回描述字段,不预加载全部文件正文。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @return Skill 管理详情
|
||||
*/
|
||||
Skill getManagementDetail(BigInteger id);
|
||||
|
||||
/**
|
||||
* 获取仅包含标准 Skill 包内容的授权详情,不解析平台能力目标。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @return Skill 包内容详情
|
||||
*/
|
||||
Skill getPackageDetail(BigInteger id);
|
||||
|
||||
/**
|
||||
* 保存 Skill 草稿。
|
||||
*
|
||||
@@ -35,6 +52,50 @@ public interface SkillService extends IService<Skill> {
|
||||
*/
|
||||
Skill updateDraft(Skill skill);
|
||||
|
||||
/**
|
||||
* 覆盖导入内容,并在锁定目标行后再次确认目标仍为草稿。
|
||||
*
|
||||
* @param skill 导入后的 Skill 草稿
|
||||
* @return 更新后的 Skill
|
||||
*/
|
||||
Skill overwriteImportedDraft(Skill skill);
|
||||
|
||||
/**
|
||||
* 按客户端读取到的 SKILL.md 内容 hash 原子更新草稿,防止并发覆盖。
|
||||
*
|
||||
* @param skill Skill 草稿
|
||||
* @param expectedSkillContentHash 客户端读取到的 SKILL.md SHA-256
|
||||
* @return 更新后的 Skill
|
||||
*/
|
||||
Skill updateDraftIfContentMatches(Skill skill, String expectedSkillContentHash);
|
||||
|
||||
/**
|
||||
* 复制一个可读 Skill 为当前用户拥有的新草稿。
|
||||
*
|
||||
* @param sourceId 源 Skill ID
|
||||
* @param name 新 Skill 标准名称
|
||||
* @param displayName 新 Skill 展示名称
|
||||
* @param categoryId 目标分类 ID,可为空
|
||||
* @return 新建的 Skill 草稿
|
||||
*/
|
||||
Skill copyDraft(BigInteger sourceId, String name, String displayName, BigInteger categoryId);
|
||||
|
||||
/**
|
||||
* 对当前 Skill 包和能力绑定执行全量校验。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param publishValidation 是否执行发布级能力解析
|
||||
* @return 结构化校验结果
|
||||
*/
|
||||
SkillValidationResult validateSkill(BigInteger id, boolean publishValidation);
|
||||
|
||||
/**
|
||||
* 在文件级修改后重新计算资源计数和包 hash。
|
||||
*
|
||||
* @param id Skill ID
|
||||
*/
|
||||
void refreshPackageState(BigInteger id);
|
||||
|
||||
/**
|
||||
* 构建发布快照。
|
||||
*
|
||||
@@ -43,6 +104,28 @@ public interface SkillService extends IService<Skill> {
|
||||
*/
|
||||
Map<String, Object> buildPublishSnapshot(Skill skill);
|
||||
|
||||
/**
|
||||
* 构建删除审批使用的最小治理快照。
|
||||
*
|
||||
* @param skill Skill
|
||||
* @return 不含提示词、资源内容和能力配置的治理快照
|
||||
*/
|
||||
Map<String, Object> buildGovernanceSnapshot(Skill skill);
|
||||
|
||||
/**
|
||||
* 为发布候选或已发布快照中的每个二进制资源增加一份持有引用。
|
||||
*
|
||||
* @param snapshot Skill 发布快照
|
||||
*/
|
||||
void retainSnapshotContents(Map<String, Object> snapshot);
|
||||
|
||||
/**
|
||||
* 释放发布候选或已发布快照中的每个二进制资源持有引用。
|
||||
*
|
||||
* @param snapshot Skill 发布快照
|
||||
*/
|
||||
void releaseSnapshotContents(Map<String, Object> snapshot);
|
||||
|
||||
/**
|
||||
* 从发布快照还原 Skill。
|
||||
*
|
||||
@@ -52,9 +135,23 @@ public interface SkillService extends IService<Skill> {
|
||||
Skill fromSnapshot(Map<String, Object> snapshot);
|
||||
|
||||
/**
|
||||
* 删除 Skill 聚合。
|
||||
* 删除草稿或已下线的 Skill 聚合。
|
||||
*
|
||||
* <p>已发布记录必须先下线,任何审批中记录都不能通过此普通仓储入口删除。</p>
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @throws tech.easyflow.common.web.exceptions.BusinessException Skill 不存在、无权限或当前状态不可删除
|
||||
*/
|
||||
void removeAggregate(BigInteger id);
|
||||
|
||||
/**
|
||||
* 由统一发布生命周期删除 Skill 聚合。
|
||||
*
|
||||
* <p>该入口允许删除审批已经进入 {@code DELETE_PENDING} 的记录,也兼容未配置审批流时
|
||||
* 直接删除草稿或已下线记录。普通仓储删除必须使用 {@link #removeAggregate(BigInteger)}。</p>
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @throws tech.easyflow.common.web.exceptions.BusinessException Skill 不存在、无权限或当前状态不可删除
|
||||
*/
|
||||
void removeLifecycleAggregate(BigInteger id);
|
||||
}
|
||||
|
||||
@@ -86,11 +86,17 @@ public class SkillApprovalStateServiceImpl implements SkillApprovalStateService
|
||||
.map(Skill::getCurrentApprovalInstanceId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
if (instanceIds.isEmpty()) {
|
||||
Set<BigInteger> tenantIds = skills.stream()
|
||||
.map(Skill::getTenantId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
if (instanceIds.isEmpty() || tenantIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
List<ApprovalInstance> instances = approvalInstanceMapper.selectListByQuery(
|
||||
QueryWrapper.create().in(ApprovalInstance::getId, instanceIds)
|
||||
QueryWrapper.create()
|
||||
.in(ApprovalInstance::getId, instanceIds)
|
||||
.in(ApprovalInstance::getTenantId, tenantIds)
|
||||
);
|
||||
return instances.stream().collect(Collectors.toMap(ApprovalInstance::getId, Function.identity()));
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.skill.entity.SkillAssetContent;
|
||||
import tech.easyflow.skill.mapper.SkillAssetContentMapper;
|
||||
import tech.easyflow.skill.service.SkillAssetContentService;
|
||||
|
||||
/**
|
||||
* Skill asset 内容索引服务实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillAssetContentServiceImpl extends ServiceImpl<SkillAssetContentMapper, SkillAssetContent> implements SkillAssetContentService {
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
import tech.easyflow.skill.mapper.SkillAssetMapper;
|
||||
import tech.easyflow.skill.service.SkillAssetService;
|
||||
|
||||
/**
|
||||
* Skill asset 服务实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillAssetServiceImpl extends ServiceImpl<SkillAssetMapper, SkillAsset> implements SkillAssetService {
|
||||
}
|
||||
@@ -2,16 +2,24 @@ package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.SkillCategory;
|
||||
import tech.easyflow.skill.mapper.SkillCategoryMapper;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.service.SkillCategoryService;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 分类服务实现。
|
||||
@@ -21,6 +29,9 @@ public class SkillCategoryServiceImpl extends ServiceImpl<SkillCategoryMapper, S
|
||||
|
||||
private static final int MAX_LEVEL = 3;
|
||||
|
||||
@Resource
|
||||
private SkillMapper skillMapper;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@@ -29,10 +40,33 @@ public class SkillCategoryServiceImpl extends ServiceImpl<SkillCategoryMapper, S
|
||||
if (categoryId == null) {
|
||||
return;
|
||||
}
|
||||
SkillCategory category = getById(categoryId);
|
||||
if (category == null) {
|
||||
throw new BusinessException("Skill 分类不存在");
|
||||
validateUsableCategory(requireTenantCategory(categoryId));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(propagation = Propagation.MANDATORY, rollbackFor = Exception.class)
|
||||
public void lockAndValidateUsableCategory(BigInteger categoryId) {
|
||||
LoginAccount account = requireAccount();
|
||||
List<SkillCategory> lockedCategories = lockTenantTree(account.getTenantId());
|
||||
if (categoryId == null) {
|
||||
return;
|
||||
}
|
||||
SkillCategory category = lockedCategories == null
|
||||
? requireTenantCategory(categoryId)
|
||||
: requireLockedCategory(lockedCategories, categoryId, account.getTenantId());
|
||||
validateUsableCategory(category);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验已按租户边界读取的分类状态。
|
||||
*
|
||||
* @param category Skill 分类
|
||||
* @throws BusinessException 分类层级超限或已停用
|
||||
*/
|
||||
private void validateUsableCategory(SkillCategory category) {
|
||||
if (category.getLevelNo() != null && category.getLevelNo() > MAX_LEVEL) {
|
||||
throw new BusinessException("Skill 分类最多支持三级");
|
||||
}
|
||||
@@ -45,18 +79,68 @@ public class SkillCategoryServiceImpl extends ServiceImpl<SkillCategoryMapper, S
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean save(SkillCategory entity) {
|
||||
applyCategoryFields(entity);
|
||||
return super.save(entity);
|
||||
LoginAccount account = requireAccount();
|
||||
List<SkillCategory> lockedCategories = lockTenantTree(account.getTenantId());
|
||||
applyCategoryFields(entity, lockedCategories);
|
||||
assertUniqueCategoryName(entity);
|
||||
try {
|
||||
return super.save(entity);
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw new BusinessException(409, 4094, "同级分类下已存在同名 Skill 分类");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateById(SkillCategory entity) {
|
||||
applyCategoryFields(entity);
|
||||
return super.updateById(entity);
|
||||
LoginAccount account = requireAccount();
|
||||
List<SkillCategory> lockedCategories = lockTenantTree(account.getTenantId());
|
||||
SkillCategory before = entity == null || entity.getId() == null ? null
|
||||
: (lockedCategories == null
|
||||
? copyCategoryState(entity)
|
||||
: requireLockedCategory(lockedCategories, entity.getId(), account.getTenantId()));
|
||||
if (before == null) {
|
||||
throw new BusinessException("Skill 分类不存在");
|
||||
}
|
||||
if (getMapper() != null) {
|
||||
entity.setTenantId(before.getTenantId());
|
||||
entity.setCreated(before.getCreated());
|
||||
entity.setCreatedBy(before.getCreatedBy());
|
||||
}
|
||||
applyCategoryFields(entity, lockedCategories);
|
||||
assertUniqueCategoryName(entity);
|
||||
List<SkillCategory> descendants = entity.getId() == null ? List.of()
|
||||
: lockedCategories == null
|
||||
? listDescendants(entity.getId())
|
||||
: listDescendants(lockedCategories, entity.getId());
|
||||
int previousLevel = before == null || before.getLevelNo() == null ? entity.getLevelNo() : before.getLevelNo();
|
||||
int levelDelta = entity.getLevelNo() - previousLevel;
|
||||
int deepestLevel = descendants.stream()
|
||||
.map(SkillCategory::getLevelNo)
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.mapToInt(Integer::intValue)
|
||||
.max().orElse(previousLevel) + levelDelta;
|
||||
if (deepestLevel > MAX_LEVEL) {
|
||||
throw new BusinessException("移动后子分类将超过三级限制");
|
||||
}
|
||||
boolean updated;
|
||||
try {
|
||||
updated = getMapper() == null || getMapper().updateByQuery(entity, QueryWrapper.create()
|
||||
.eq(SkillCategory::getId, entity.getId())
|
||||
.eq(SkillCategory::getTenantId, account.getTenantId())) == 1;
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw new BusinessException(409, 4094, "同级分类下已存在同名 Skill 分类");
|
||||
}
|
||||
if (!updated) {
|
||||
return false;
|
||||
}
|
||||
updateDescendantPaths(entity, before, descendants, levelDelta);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,36 +153,113 @@ public class SkillCategoryServiceImpl extends ServiceImpl<SkillCategoryMapper, S
|
||||
if (categoryId == null) {
|
||||
return false;
|
||||
}
|
||||
return count(QueryWrapper.create().eq(SkillCategory::getParentId, categoryId)) > 0;
|
||||
return count(QueryWrapper.create()
|
||||
.eq(SkillCategory::getTenantId, requireAccount().getTenantId())
|
||||
.eq(SkillCategory::getParentId, categoryId)) > 0;
|
||||
}
|
||||
|
||||
private void applyCategoryFields(SkillCategory category) {
|
||||
/**
|
||||
* 删除分类前在服务层校验子分类和 Skill 占用,避免绕过控制器。
|
||||
*
|
||||
* @param id 分类 ID
|
||||
* @return 删除结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean removeById(Serializable id) {
|
||||
BigInteger categoryId;
|
||||
try {
|
||||
categoryId = id instanceof BigInteger value ? value : new BigInteger(String.valueOf(id));
|
||||
} catch (RuntimeException exception) {
|
||||
throw new BusinessException("Skill 分类 ID 格式不正确");
|
||||
}
|
||||
LoginAccount account = requireAccount();
|
||||
List<SkillCategory> lockedCategories = lockTenantTree(account.getTenantId());
|
||||
if (lockedCategories == null) {
|
||||
requireTenantCategory(categoryId);
|
||||
} else {
|
||||
requireLockedCategory(lockedCategories, categoryId, account.getTenantId());
|
||||
}
|
||||
boolean occupiedByChildren = lockedCategories == null
|
||||
? hasChildren(categoryId)
|
||||
: lockedCategories.stream().anyMatch(category -> categoryId.equals(category.getParentId()));
|
||||
if (occupiedByChildren) {
|
||||
throw new BusinessException("请先删除子分类");
|
||||
}
|
||||
if (skillMapper != null && skillMapper.selectCountByQuery(
|
||||
QueryWrapper.create().eq("tenant_id", account.getTenantId())
|
||||
.eq("category_id", categoryId)) > 0) {
|
||||
throw new BusinessException("请先迁移或删除该分类下的 Skill");
|
||||
}
|
||||
return getMapper() == null || getMapper().deleteByQuery(QueryWrapper.create()
|
||||
.eq(SkillCategory::getId, categoryId)
|
||||
.eq(SkillCategory::getTenantId, account.getTenantId())) == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除时逐项执行分类占用约束。
|
||||
*
|
||||
* @param ids 分类 ID 集合
|
||||
* @return 全部删除成功时为 true
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean removeByIds(Collection<? extends Serializable> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (Serializable id : ids) {
|
||||
removeById(id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用分类字段,并优先从当前事务已锁定的分类树解析父级。
|
||||
*
|
||||
* @param category 待保存分类
|
||||
* @param lockedCategories 已锁定分类树;无数据库 Mapper 的单元场景可为 null
|
||||
*/
|
||||
private void applyCategoryFields(SkillCategory category, List<SkillCategory> lockedCategories) {
|
||||
if (category == null) {
|
||||
throw new BusinessException("Skill 分类不能为空");
|
||||
}
|
||||
if (category.getCategoryName() == null || category.getCategoryName().isBlank()) {
|
||||
throw new BusinessException("Skill 分类名称不能为空");
|
||||
}
|
||||
category.setCategoryName(category.getCategoryName().trim());
|
||||
if (category.getCategoryName().length() > 128) {
|
||||
throw new BusinessException("Skill 分类名称不能超过 128 个字符");
|
||||
}
|
||||
SkillCategory parent = null;
|
||||
if (category.getParentId() != null) {
|
||||
parent = getById(category.getParentId());
|
||||
if (parent == null) {
|
||||
throw new BusinessException("父级 Skill 分类不存在");
|
||||
}
|
||||
LoginAccount account = requireAccount();
|
||||
parent = lockedCategories == null
|
||||
? requireTenantCategory(category.getParentId())
|
||||
: requireLockedCategory(lockedCategories, category.getParentId(), account.getTenantId());
|
||||
if (category.getId() != null && category.getId().equals(category.getParentId())) {
|
||||
throw new BusinessException("父级分类不能是自身");
|
||||
}
|
||||
if (category.getId() != null && containsAncestor(parent.getAncestors(), category.getId())) {
|
||||
throw new BusinessException("父级分类不能是当前分类的后代");
|
||||
}
|
||||
}
|
||||
int level = parent == null ? 1 : (parent.getLevelNo() == null ? 1 : parent.getLevelNo()) + 1;
|
||||
if (level > MAX_LEVEL) {
|
||||
throw new BusinessException("Skill 分类最多支持三级");
|
||||
}
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
LoginAccount account = requireAccount();
|
||||
Date now = new Date();
|
||||
category.setLevelNo(level);
|
||||
category.setAncestors(parent == null ? "" : appendAncestor(parent));
|
||||
category.setStatus(category.getStatus() == null ? 1 : category.getStatus());
|
||||
if (category.getStatus() != 0 && category.getStatus() != 1) {
|
||||
throw new BusinessException("Skill 分类状态只支持 0 或 1");
|
||||
}
|
||||
category.setSortNo(category.getSortNo() == null ? 0 : category.getSortNo());
|
||||
if (category.getSortNo() < -999_999 || category.getSortNo() > 999_999) {
|
||||
throw new BusinessException("Skill 分类排序值超出允许范围");
|
||||
}
|
||||
if (category.getId() == null) {
|
||||
category.setTenantId(account.getTenantId());
|
||||
category.setCreated(now);
|
||||
@@ -117,4 +278,147 @@ public class SkillCategoryServiceImpl extends ServiceImpl<SkillCategoryMapper, S
|
||||
}
|
||||
return ancestors;
|
||||
}
|
||||
|
||||
private List<SkillCategory> listDescendants(BigInteger categoryId) {
|
||||
return list(QueryWrapper.create()
|
||||
.eq(SkillCategory::getTenantId, requireAccount().getTenantId())
|
||||
.and("FIND_IN_SET(?, ancestors)", categoryId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已锁定分类树中提取当前分类的全部后代。
|
||||
*
|
||||
* @param lockedCategories 已锁定分类树
|
||||
* @param categoryId 当前分类 ID
|
||||
* @return 后代分类列表
|
||||
*/
|
||||
private List<SkillCategory> listDescendants(List<SkillCategory> lockedCategories, BigInteger categoryId) {
|
||||
return lockedCategories.stream()
|
||||
.filter(category -> containsAncestor(category.getAncestors(), categoryId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void updateDescendantPaths(SkillCategory category,
|
||||
SkillCategory before,
|
||||
List<SkillCategory> descendants,
|
||||
int levelDelta) {
|
||||
if (descendants.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String oldPrefix = before == null || before.getAncestors() == null || before.getAncestors().isBlank()
|
||||
? String.valueOf(category.getId()) : before.getAncestors() + "," + category.getId();
|
||||
String newPrefix = category.getAncestors() == null || category.getAncestors().isBlank()
|
||||
? String.valueOf(category.getId()) : category.getAncestors() + "," + category.getId();
|
||||
for (SkillCategory descendant : descendants) {
|
||||
String ancestors = descendant.getAncestors();
|
||||
if (ancestors == null || (!ancestors.equals(oldPrefix) && !ancestors.startsWith(oldPrefix + ","))) {
|
||||
throw new BusinessException(500, 500, "Skill 分类层级数据异常,请联系管理员处理");
|
||||
}
|
||||
descendant.setAncestors(newPrefix + ancestors.substring(oldPrefix.length()));
|
||||
descendant.setLevelNo(descendant.getLevelNo() + levelDelta);
|
||||
descendant.setModified(category.getModified());
|
||||
descendant.setModifiedBy(category.getModifiedBy());
|
||||
if (getMapper().updateByQuery(descendant, QueryWrapper.create()
|
||||
.eq(SkillCategory::getId, descendant.getId())
|
||||
.eq(SkillCategory::getTenantId, category.getTenantId())) != 1) {
|
||||
throw new BusinessException(500, 500, "更新 Skill 子分类层级失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean containsAncestor(String ancestors, BigInteger categoryId) {
|
||||
if (ancestors == null || ancestors.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String expected = String.valueOf(categoryId);
|
||||
for (String ancestor : ancestors.split(",")) {
|
||||
if (expected.equals(ancestor.trim())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private SkillCategory copyCategoryState(SkillCategory source) {
|
||||
SkillCategory copy = new SkillCategory();
|
||||
copy.setId(source.getId());
|
||||
copy.setParentId(source.getParentId());
|
||||
copy.setLevelNo(source.getLevelNo());
|
||||
copy.setAncestors(source.getAncestors());
|
||||
copy.setTenantId(source.getTenantId());
|
||||
return copy;
|
||||
}
|
||||
|
||||
private SkillCategory requireTenantCategory(BigInteger categoryId) {
|
||||
if (categoryId == null) {
|
||||
throw new BusinessException("Skill 分类 ID 不能为空");
|
||||
}
|
||||
LoginAccount account = requireAccount();
|
||||
SkillCategory category = getMapper() == null ? getById(categoryId) : getOne(QueryWrapper.create()
|
||||
.eq(SkillCategory::getId, categoryId)
|
||||
.eq(SkillCategory::getTenantId, account.getTenantId()));
|
||||
if (category == null || !account.getTenantId().equals(category.getTenantId())) {
|
||||
throw new BusinessException(404, 404, "Skill 分类不存在");
|
||||
}
|
||||
return category;
|
||||
}
|
||||
|
||||
/**
|
||||
* 锁定租户完整分类树。所有结构写操作都使用同一锁顺序,防止并发移动形成循环或孤儿节点。
|
||||
*
|
||||
* @param tenantId 租户 ID
|
||||
* @return 已锁定分类树;无 Mapper 的隔离单元场景返回 null
|
||||
*/
|
||||
private List<SkillCategory> lockTenantTree(BigInteger tenantId) {
|
||||
if (getMapper() == null) {
|
||||
return null;
|
||||
}
|
||||
List<SkillCategory> categories = getMapper().selectTenantTreeForUpdate(tenantId);
|
||||
return categories == null ? List.of() : categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已锁定分类树中读取同租户分类。
|
||||
*
|
||||
* @param lockedCategories 已锁定分类树
|
||||
* @param categoryId 分类 ID
|
||||
* @param tenantId 租户 ID
|
||||
* @return 分类实体
|
||||
*/
|
||||
private SkillCategory requireLockedCategory(List<SkillCategory> lockedCategories,
|
||||
BigInteger categoryId,
|
||||
BigInteger tenantId) {
|
||||
if (categoryId == null) {
|
||||
throw new BusinessException("Skill 分类 ID 不能为空");
|
||||
}
|
||||
return lockedCategories.stream()
|
||||
.filter(category -> categoryId.equals(category.getId()) && tenantId.equals(category.getTenantId()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException(404, 404, "Skill 分类不存在"));
|
||||
}
|
||||
|
||||
private void assertUniqueCategoryName(SkillCategory category) {
|
||||
QueryWrapper query = QueryWrapper.create()
|
||||
.eq(SkillCategory::getTenantId, category.getTenantId())
|
||||
.eq(SkillCategory::getCategoryName, category.getCategoryName());
|
||||
if (category.getParentId() == null) {
|
||||
query.isNull(SkillCategory::getParentId);
|
||||
} else {
|
||||
query.eq(SkillCategory::getParentId, category.getParentId());
|
||||
}
|
||||
if (category.getId() != null) {
|
||||
query.ne(SkillCategory::getId, category.getId());
|
||||
}
|
||||
if (getMapper() != null && count(query) > 0) {
|
||||
throw new BusinessException(409, 4094, "同级分类下已存在同名 Skill 分类");
|
||||
}
|
||||
}
|
||||
|
||||
private LoginAccount requireAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
import tech.easyflow.skill.mapper.SkillReferenceMapper;
|
||||
import tech.easyflow.skill.service.SkillReferenceService;
|
||||
|
||||
/**
|
||||
* Skill reference 服务实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillReferenceServiceImpl extends ServiceImpl<SkillReferenceMapper, SkillReference> implements SkillReferenceService {
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
import tech.easyflow.skill.mapper.SkillResourceMapper;
|
||||
import tech.easyflow.skill.service.SkillResourceService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 通用资源服务实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillResourceServiceImpl extends ServiceImpl<SkillResourceMapper, SkillResource>
|
||||
implements SkillResourceService {
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<SkillResource> listDescriptors(BigInteger skillId, BigInteger tenantId) {
|
||||
return list(descriptorQuery(skillId, tenantId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建轻量资源描述查询,避免文件树和管理详情加载全部正文。
|
||||
*
|
||||
* @param skillId Skill ID
|
||||
* @param tenantId 租户 ID
|
||||
* @return 资源描述查询
|
||||
*/
|
||||
QueryWrapper descriptorQuery(BigInteger skillId, BigInteger tenantId) {
|
||||
return QueryWrapper.create()
|
||||
.select("id", "tenant_id", "skill_id", "path", "normalized_path", "kind", "language",
|
||||
"media_type", "is_text", "content_hash", "size", "metadata_json", "sort_no")
|
||||
.eq(SkillResource::getTenantId, tenantId)
|
||||
.eq(SkillResource::getSkillId, skillId)
|
||||
.orderBy("sort_no asc, normalized_path asc");
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
import tech.easyflow.skill.mapper.SkillScriptMapper;
|
||||
import tech.easyflow.skill.service.SkillScriptService;
|
||||
|
||||
/**
|
||||
* Skill script 服务实现。
|
||||
*/
|
||||
@Service
|
||||
public class SkillScriptServiceImpl extends ServiceImpl<SkillScriptMapper, SkillScript> implements SkillScriptService {
|
||||
}
|
||||
@@ -2,23 +2,36 @@ package tech.easyflow.skill.service.impl;
|
||||
|
||||
import com.easyagents.skill.exception.SkillException;
|
||||
import com.easyagents.skill.factory.SkillFactory;
|
||||
import com.easyagents.skill.model.SkillDocument;
|
||||
import com.easyagents.skill.util.SkillFrontmatter;
|
||||
import com.easyagents.skill.util.SkillHashes;
|
||||
import com.easyagents.skill.util.SkillPaths;
|
||||
import com.easyagents.skill.validation.defaults.DefaultSkillValidator;
|
||||
import com.easyagents.skill.validation.SkillValidationMode;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import com.mybatisflex.spring.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tech.easyflow.ai.enums.PublishStatus;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.capability.SkillCapabilityBindingService;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.service.*;
|
||||
import tech.easyflow.skill.service.SkillCategoryService;
|
||||
import tech.easyflow.skill.service.SkillResourceService;
|
||||
import tech.easyflow.skill.service.SkillService;
|
||||
import tech.easyflow.skill.store.DBSkillContentStore;
|
||||
import tech.easyflow.skill.support.SkillModelConverter;
|
||||
import tech.easyflow.skill.support.SkillResourceModelAdapter;
|
||||
import tech.easyflow.skill.validation.SkillValidationIssue;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
import tech.easyflow.system.entity.vo.RoleCategoryAccessSnapshot;
|
||||
import tech.easyflow.system.enums.CategoryResourceType;
|
||||
import tech.easyflow.system.enums.ResourceAction;
|
||||
@@ -26,11 +39,19 @@ import tech.easyflow.system.enums.VisibilityScope;
|
||||
import tech.easyflow.system.service.CategoryPermissionService;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.Normalizer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* Skill 业务服务实现。
|
||||
@@ -39,21 +60,40 @@ import java.util.Map;
|
||||
public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements SkillService {
|
||||
|
||||
private final DefaultSkillValidator skillValidator = new DefaultSkillValidator();
|
||||
private final SkillCategoryService skillCategoryService;
|
||||
private final SkillResourceService skillResourceService;
|
||||
private final SkillCapabilityBindingService capabilityBindingService;
|
||||
private final DBSkillContentStore contentStore;
|
||||
private final ResourceAccessService resourceAccessService;
|
||||
private final CategoryPermissionService categoryPermissionService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Resource
|
||||
private SkillCategoryService skillCategoryService;
|
||||
@Resource
|
||||
private SkillReferenceService skillReferenceService;
|
||||
@Resource
|
||||
private SkillScriptService skillScriptService;
|
||||
@Resource
|
||||
private SkillAssetService skillAssetService;
|
||||
@Resource
|
||||
private ResourceAccessService resourceAccessService;
|
||||
@Resource
|
||||
private CategoryPermissionService categoryPermissionService;
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
/**
|
||||
* 创建 Skill 业务服务。
|
||||
*
|
||||
* @param skillCategoryService Skill 分类服务
|
||||
* @param skillResourceService 通用资源服务
|
||||
* @param capabilityBindingService 能力绑定服务
|
||||
* @param contentStore 二进制内容仓库
|
||||
* @param resourceAccessService 资源访问服务
|
||||
* @param categoryPermissionService 分类权限服务
|
||||
* @param objectMapper JSON 映射器
|
||||
*/
|
||||
public SkillServiceImpl(SkillCategoryService skillCategoryService,
|
||||
SkillResourceService skillResourceService,
|
||||
SkillCapabilityBindingService capabilityBindingService,
|
||||
DBSkillContentStore contentStore,
|
||||
ResourceAccessService resourceAccessService,
|
||||
CategoryPermissionService categoryPermissionService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.skillCategoryService = skillCategoryService;
|
||||
this.skillResourceService = skillResourceService;
|
||||
this.capabilityBindingService = capabilityBindingService;
|
||||
this.contentStore = contentStore;
|
||||
this.resourceAccessService = resourceAccessService;
|
||||
this.categoryPermissionService = categoryPermissionService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
@@ -63,6 +103,44 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
Skill skill = requireSkill(id);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill, ResourceAction.READ, "无权限查看该 Skill");
|
||||
fillResources(skill);
|
||||
fillCapabilityBindings(skill);
|
||||
return skill;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Skill getManagementDetail(BigInteger id) {
|
||||
Skill skill = requireSkill(id);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill, ResourceAction.READ, "无权限查看该 Skill");
|
||||
fillResourceDescriptors(skill);
|
||||
fillCapabilityBindings(skill);
|
||||
return skill;
|
||||
}
|
||||
|
||||
private void fillCapabilityBindings(Skill skill) {
|
||||
List<tech.easyflow.skill.entity.SkillCapabilityBinding> bindings =
|
||||
capabilityBindingService.listBindings(skill.getId());
|
||||
skill.setCapabilityBindings(bindings);
|
||||
boolean containsRedactedTarget = bindings.stream()
|
||||
.anyMatch(binding -> "NO_PERMISSION".equals(binding.getTargetStatus()));
|
||||
if (!containsRedactedTarget && (skill.getCapabilityHash() == null || skill.getCapabilityHash().isBlank())) {
|
||||
String capabilityHash = capabilityBindingService.calculateStoredHash(skill.getId());
|
||||
skill.setCapabilityHash(capabilityHash);
|
||||
getMapper().backfillCapabilityHash(skill.getId(), skill.getTenantId(), capabilityHash);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Skill getPackageDetail(BigInteger id) {
|
||||
Skill skill = requireSkill(id);
|
||||
resourceAccessService.assertAccess(
|
||||
CategoryResourceType.SKILL, skill, ResourceAction.READ, "无权限查看该 Skill");
|
||||
fillResources(skill);
|
||||
return skill;
|
||||
}
|
||||
|
||||
@@ -72,10 +150,27 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Skill saveDraft(Skill skill) {
|
||||
if (skill == null) {
|
||||
throw new BusinessException("Skill 不能为空");
|
||||
}
|
||||
skillCategoryService.lockAndValidateUsableCategory(skill.getCategoryId());
|
||||
validateDraft(skill);
|
||||
assertUniqueName(skill.getName(), null);
|
||||
List<SkillResource> resources = SkillResourceModelAdapter.toResources(skill);
|
||||
applyDraftDefaults(skill);
|
||||
save(skill);
|
||||
replaceResources(skill);
|
||||
normalizeResources(skill, resources);
|
||||
skill.setPackageHash(calculatePackageHash(skill.getSkillContent(), resources));
|
||||
skill.setResources(resources);
|
||||
syncCounts(skill, resources);
|
||||
try {
|
||||
if (!save(skill)) {
|
||||
throw new BusinessException(500, 500, "保存 Skill 失败,请稍后重试");
|
||||
}
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw new BusinessException(409, 4092, "当前租户已存在同名 Skill");
|
||||
}
|
||||
resources.forEach(resource -> resource.setSkillId(skill.getId()));
|
||||
replaceResources(skill, resources);
|
||||
return getDetail(skill.getId());
|
||||
}
|
||||
|
||||
@@ -85,26 +180,201 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Skill updateDraft(Skill skill) {
|
||||
return updateDraftInternal(skill, null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Skill overwriteImportedDraft(Skill skill) {
|
||||
return updateDraftInternal(skill, null, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Skill updateDraftIfContentMatches(Skill skill, String expectedSkillContentHash) {
|
||||
if (expectedSkillContentHash == null || !expectedSkillContentHash.matches("^[a-f0-9]{64}$")) {
|
||||
throw new BusinessException(409, 4091, "缺少或无效的文件版本,请重新加载后再保存");
|
||||
}
|
||||
return updateDraftInternal(skill, expectedSkillContentHash, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Skill copyDraft(BigInteger sourceId, String name, String displayName, BigInteger categoryId) {
|
||||
if (sourceId == null) {
|
||||
throw new BusinessException("源 Skill ID 不能为空");
|
||||
}
|
||||
String normalizedName = name == null ? "" : name.trim();
|
||||
if (!isCanonicalName(normalizedName)) {
|
||||
throw new BusinessException("新 Skill 名称仅支持小写字母、数字和连字符");
|
||||
}
|
||||
|
||||
Skill source = getDetail(sourceId);
|
||||
SkillDocument document;
|
||||
try {
|
||||
document = SkillFrontmatter.parseDocument(source.getSkillContent());
|
||||
document.putFrontmatter("name", normalizedName);
|
||||
} catch (SkillException exception) {
|
||||
throw new BusinessException("复制 Skill 时解析 SKILL.md 失败:" + exception.getMessage());
|
||||
}
|
||||
|
||||
List<SkillResource> resources = source.getResources() == null ? List.of()
|
||||
: source.getResources().stream().map(this::copyResource).toList();
|
||||
// 新草稿对每个二进制资源持有独立引用;外层事务失败时引用计数会随数据库事务回滚。
|
||||
resources.stream().map(SkillResource::getContentRef)
|
||||
.filter(contentRef -> contentRef != null && !contentRef.isBlank())
|
||||
.forEach(contentStore::retain);
|
||||
|
||||
Skill draft = new Skill();
|
||||
draft.setCategoryId(categoryId);
|
||||
draft.setDisplayName(displayName == null || displayName.isBlank()
|
||||
? normalizedName : displayName.trim());
|
||||
draft.setSkillContent(document.render());
|
||||
draft.setEnabled(true);
|
||||
draft.setVisibilityScope(VisibilityScope.PRIVATE.name());
|
||||
draft.setSourceType("MANUAL");
|
||||
draft.setResources(resources);
|
||||
Skill saved = saveDraft(draft);
|
||||
|
||||
List<SkillCapabilityBinding> bindings = source.getCapabilityBindings() == null ? List.of()
|
||||
: source.getCapabilityBindings().stream().map(this::copyBinding).toList();
|
||||
if (!bindings.isEmpty()) {
|
||||
capabilityBindingService.replaceBindings(saved.getId(), bindings, saved.getCapabilityHash());
|
||||
return getDetail(saved.getId());
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
private Skill updateDraftInternal(Skill skill,
|
||||
String expectedSkillContentHash,
|
||||
boolean requireDraftStatus) {
|
||||
if (skill == null || skill.getId() == null) {
|
||||
throw new BusinessException("Skill ID 不能为空");
|
||||
}
|
||||
Skill existing = requireSkill(skill.getId());
|
||||
// 与分类删除保持“分类树 -> Skill 行”的统一锁顺序,避免相反顺序形成死锁。
|
||||
skillCategoryService.lockAndValidateUsableCategory(skill.getCategoryId());
|
||||
Skill existing = requireSkill(skill.getId(), true);
|
||||
String originalSkillContent = existing.getSkillContent();
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, existing, ResourceAction.MANAGE, "无权限管理该 Skill");
|
||||
if (requireDraftStatus && PublishStatus.from(existing.getPublishStatus()) != PublishStatus.DRAFT) {
|
||||
throw new BusinessException(409, 4092, "仅允许覆盖草稿状态的 Skill:" + existing.getName());
|
||||
}
|
||||
if (skill.getSkillContent() == null) {
|
||||
skill.setSkillContent(existing.getSkillContent());
|
||||
}
|
||||
if (expectedSkillContentHash != null) {
|
||||
String actualHash = SkillHashes.sha256Hex((existing.getSkillContent() == null ? "" : existing.getSkillContent())
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
if (!expectedSkillContentHash.equals(actualHash)) {
|
||||
throw new BusinessException(409, 4091, "文件已被其他操作更新,请重新加载后合并内容");
|
||||
}
|
||||
}
|
||||
// 来源由服务端继承,使旧版下划线导入草稿可继续编辑,同时仍在发布校验中阻断。
|
||||
skill.setSourceType(existing.getSourceType());
|
||||
validateDraft(skill);
|
||||
assertUniqueName(skill.getName(), skill.getId());
|
||||
List<SkillResource> resources = hasResourcePayload(skill)
|
||||
? SkillResourceModelAdapter.toResources(skill)
|
||||
: listResources(skill.getId());
|
||||
normalizeResources(existing, resources);
|
||||
applyDraftUpdate(existing, skill);
|
||||
updateById(existing);
|
||||
replaceResources(existing);
|
||||
existing.setPackageHash(calculatePackageHash(existing.getSkillContent(), resources));
|
||||
existing.setResources(resources);
|
||||
syncCounts(existing, resources);
|
||||
try {
|
||||
QueryWrapper updateQuery = tenantSkillQuery(existing.getId());
|
||||
if (expectedSkillContentHash != null) {
|
||||
// BINARY 比较保证文本大小写变化也会使旧版本条件失效。
|
||||
updateQuery.and("BINARY skill_content = ?", originalSkillContent);
|
||||
}
|
||||
if (getMapper().updateByQuery(existing, updateQuery) != 1) {
|
||||
if (expectedSkillContentHash != null) {
|
||||
throw new BusinessException(409, 4091, "文件已被其他操作更新,请重新加载后合并内容");
|
||||
}
|
||||
throw new BusinessException(500, 500, "更新 Skill 失败,请稍后重试");
|
||||
}
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw new BusinessException(409, 4092, "当前租户已存在同名 Skill");
|
||||
}
|
||||
if (hasResourcePayload(skill)) {
|
||||
replaceResources(existing, resources);
|
||||
}
|
||||
return getDetail(existing.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SkillValidationResult validateSkill(BigInteger id, boolean publishValidation) {
|
||||
Skill detail = getDetail(id);
|
||||
if (publishValidation) {
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, detail, ResourceAction.MANAGE,
|
||||
"无权限管理该 Skill");
|
||||
}
|
||||
List<SkillValidationIssue> issues = new ArrayList<>();
|
||||
com.easyagents.skill.validation.SkillValidationReport packageReport =
|
||||
skillValidator.validateReport(
|
||||
SkillModelConverter.toAgentSkill(detail), null,
|
||||
publishValidation ? SkillValidationMode.STANDARD
|
||||
: SkillValidationMode.DRAFT_IMPORT);
|
||||
for (com.easyagents.skill.validation.SkillValidationIssue source : packageReport.getIssues()) {
|
||||
SkillValidationIssue issue = SkillValidationIssue.of(source.getSeverity().name(), source.getCode(),
|
||||
source.getMessage(), source.getPath());
|
||||
issue.setLine(source.getLine());
|
||||
issue.setColumn(source.getColumn());
|
||||
issue.setSuggestion(source.getSuggestion());
|
||||
issues.add(issue);
|
||||
}
|
||||
SkillValidationResult capabilityResult = capabilityBindingService.validateBindings(id, null, publishValidation);
|
||||
issues.addAll(capabilityResult.getIssues());
|
||||
SkillValidationResult result = new SkillValidationResult();
|
||||
result.setIssues(issues);
|
||||
result.setValid(issues.stream().noneMatch(issue -> "ERROR".equals(issue.getSeverity())));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void refreshPackageState(BigInteger id) {
|
||||
Skill skill = requireSkill(id);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill, ResourceAction.MANAGE,
|
||||
"无权限管理该 Skill");
|
||||
List<SkillResource> resources = listResources(id);
|
||||
syncCounts(skill, resources);
|
||||
skill.setPackageHash(calculatePackageHash(skill.getSkillContent(), resources));
|
||||
skill.setModified(new Date());
|
||||
skill.setModifiedBy(requireCurrentLoginAccount().getId());
|
||||
if (getMapper().updateByQuery(skill, tenantSkillQuery(skill.getId())) != 1) {
|
||||
throw new BusinessException(500, 500, "刷新 Skill 包状态失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> buildPublishSnapshot(Skill skill) {
|
||||
Skill detail = getDetail(skill.getId());
|
||||
com.easyagents.skill.model.Skill agentSkill = SkillModelConverter.toAgentSkill(detail);
|
||||
SkillValidationResult validation = validateSkill(detail.getId(), true);
|
||||
validation.getIssues().stream().filter(issue -> "ERROR".equals(issue.getSeverity())).findFirst()
|
||||
.ifPresent(issue -> {
|
||||
throw new BusinessException("Skill 发布校验失败:" + issue.getMessage());
|
||||
});
|
||||
Map<String, Object> snapshot = new LinkedHashMap<>();
|
||||
snapshot.put("schemaVersion", 1);
|
||||
snapshot.put("id", detail.getId());
|
||||
snapshot.put("tenantId", detail.getTenantId());
|
||||
snapshot.put("deptId", detail.getDeptId());
|
||||
@@ -119,13 +389,67 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
snapshot.put("visibilityScope", detail.getVisibilityScope());
|
||||
snapshot.put("sourceType", detail.getSourceType());
|
||||
snapshot.put("packageHash", detail.getPackageHash());
|
||||
snapshot.put("references", agentSkill.getReferences());
|
||||
snapshot.put("scripts", agentSkill.getScripts());
|
||||
snapshot.put("assets", agentSkill.getAssets());
|
||||
snapshot.put("snapshotAt", new Date());
|
||||
snapshot.put("resources", buildResourceSnapshot(detail.getResources()));
|
||||
List<Map<String, Object>> capabilitySnapshot = capabilityBindingService.buildPublishSnapshot(detail.getId());
|
||||
// 发布态 hash 覆盖解析后的目标版本和 MCP ALL 最终工具清单,目标变化会形成新快照。
|
||||
String capabilityHash = hashJson(capabilitySnapshot);
|
||||
snapshot.put("capabilityHash", capabilityHash);
|
||||
snapshot.put("capabilities", capabilitySnapshot);
|
||||
String snapshotHash = hashJson(snapshot);
|
||||
snapshot.put("snapshotHash", snapshotHash);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> buildGovernanceSnapshot(Skill skill) {
|
||||
if (skill == null || skill.getId() == null) {
|
||||
throw new BusinessException("Skill 治理快照缺少资源标识");
|
||||
}
|
||||
Map<String, Object> snapshot = new LinkedHashMap<>();
|
||||
snapshot.put("schemaVersion", 1);
|
||||
snapshot.put("id", skill.getId());
|
||||
snapshot.put("tenantId", skill.getTenantId());
|
||||
snapshot.put("deptId", skill.getDeptId());
|
||||
snapshot.put("categoryId", skill.getCategoryId());
|
||||
snapshot.put("name", skill.getName());
|
||||
snapshot.put("displayName", skill.getDisplayName());
|
||||
snapshot.put("publishStatus", skill.getPublishStatus());
|
||||
snapshot.put("enabled", skill.getEnabled());
|
||||
snapshot.put("visibilityScope", skill.getVisibilityScope());
|
||||
snapshot.put("sourceType", skill.getSourceType());
|
||||
snapshot.put("packageHash", skill.getPackageHash());
|
||||
snapshot.put("capabilityHash", skill.getCapabilityHash());
|
||||
snapshot.put("resourceCount", skill.getResourceCount());
|
||||
snapshot.put("capabilityCount", skill.getCapabilityCount());
|
||||
snapshot.put("createdBy", skill.getCreatedBy());
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void retainSnapshotContents(Map<String, Object> snapshot) {
|
||||
for (String contentRef : snapshotContentRefs(snapshot)) {
|
||||
contentStore.retain(contentRef);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void releaseSnapshotContents(Map<String, Object> snapshot) {
|
||||
for (String contentRef : snapshotContentRefs(snapshot)) {
|
||||
contentStore.release(contentRef);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@@ -142,6 +466,9 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
skill.setCategoryId(toBigInteger(snapshot.get("categoryId")));
|
||||
skill.setPublishStatus(PublishStatus.PUBLISHED.getCode());
|
||||
skill.setPublishedSnapshotJson(snapshot);
|
||||
if (skill.getResources() != null) {
|
||||
SkillResourceModelAdapter.fillCompatibilityViews(skill, skill.getResources());
|
||||
}
|
||||
return skill;
|
||||
}
|
||||
|
||||
@@ -151,17 +478,82 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void removeAggregate(BigInteger id) {
|
||||
removeAggregate(id, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void removeLifecycleAggregate(BigInteger id) {
|
||||
removeAggregate(id, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在锁定 Skill 主行后删除完整聚合并释放内容引用。
|
||||
*
|
||||
* @param id Skill ID
|
||||
* @param lifecycleDelete 是否来自统一发布生命周期
|
||||
* @throws BusinessException Skill 不存在、无权限、状态不可删除或聚合删除失败
|
||||
*/
|
||||
private void removeAggregate(BigInteger id, boolean lifecycleDelete) {
|
||||
if (id == null) {
|
||||
return;
|
||||
}
|
||||
removeResources(id);
|
||||
removeById(id);
|
||||
// 文件、资源和能力更新同样先锁 Skill 行;删除必须持有该锁直到引用计数变更完成。
|
||||
Skill skill = requireSkill(id, true);
|
||||
resourceAccessService.assertAccess(CategoryResourceType.SKILL, skill, ResourceAction.MANAGE, "无权限删除该 Skill");
|
||||
assertRemovableStatus(skill, lifecycleDelete);
|
||||
List<SkillResource> resources = listResources(id);
|
||||
if (!skillResourceService.remove(QueryWrapper.create()
|
||||
.eq(SkillResource::getTenantId, skill.getTenantId())
|
||||
.eq(SkillResource::getSkillId, id))) {
|
||||
if (!resources.isEmpty()) {
|
||||
throw new BusinessException(500, 500, "删除 Skill 资源失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
capabilityBindingService.removeBySkillId(id);
|
||||
if (getMapper().deleteByQuery(tenantSkillQuery(id)) != 1) {
|
||||
throw new BusinessException(500, 500, "删除 Skill 失败,请稍后重试");
|
||||
}
|
||||
releaseContents(resources);
|
||||
releaseSnapshotContents(skill.getPublishedSnapshotJson());
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验普通仓储删除与生命周期删除各自允许的发布状态。
|
||||
*
|
||||
* @param skill 已锁定的 Skill
|
||||
* @param lifecycleDelete 是否来自统一发布生命周期
|
||||
* @throws BusinessException Skill 已发布或处于当前删除入口不允许的审批状态
|
||||
*/
|
||||
private void assertRemovableStatus(Skill skill, boolean lifecycleDelete) {
|
||||
PublishStatus status = PublishStatus.from(skill.getPublishStatus());
|
||||
if (status == PublishStatus.PUBLISHED) {
|
||||
throw new BusinessException(409, 4092, "当前 Skill 已发布,请先下线后再删除");
|
||||
}
|
||||
if (status == PublishStatus.PUBLISH_PENDING || status == PublishStatus.OFFLINE_PENDING
|
||||
|| (!lifecycleDelete && status == PublishStatus.DELETE_PENDING)) {
|
||||
throw new BusinessException(409, 4092, "当前 Skill 存在进行中的审批,请先处理完成");
|
||||
}
|
||||
}
|
||||
|
||||
private Skill requireSkill(BigInteger id) {
|
||||
Skill skill = getById(id);
|
||||
return requireSkill(id, false);
|
||||
}
|
||||
|
||||
private Skill requireSkill(BigInteger id, boolean forUpdate) {
|
||||
if (id == null) {
|
||||
throw new BusinessException("Skill ID 不能为空");
|
||||
}
|
||||
QueryWrapper query = tenantSkillQuery(id);
|
||||
if (forUpdate) {
|
||||
query.forUpdate();
|
||||
}
|
||||
Skill skill = getOne(query);
|
||||
if (skill == null) {
|
||||
throw new BusinessException("Skill 不存在");
|
||||
throw new BusinessException(404, 404, "Skill 不存在");
|
||||
}
|
||||
return skill;
|
||||
}
|
||||
@@ -177,15 +569,32 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
if (skill.getDescription() == null || skill.getDescription().isBlank()) {
|
||||
throw new BusinessException("Skill 描述不能为空");
|
||||
}
|
||||
if (skill.getDisplayName() != null && skill.getDisplayName().length() > 128) {
|
||||
throw new BusinessException("Skill 展示名称不能超过 128 个字符");
|
||||
}
|
||||
if (skill.getSkillContent() == null || skill.getSkillContent().isBlank()) {
|
||||
throw new BusinessException("SKILL.md 内容不能为空");
|
||||
}
|
||||
skillCategoryService.validateUsableCategory(skill.getCategoryId());
|
||||
if (!isCanonicalName(skill.getName()) && !isLegacyImportName(skill)) {
|
||||
throw new BusinessException("Skill 名称仅支持小写字母、数字和连字符");
|
||||
}
|
||||
validateTargetCategoryVisible(skill.getCategoryId());
|
||||
skill.setVisibilityScope(VisibilityScope.fromOrDefault(skill.getVisibilityScope(), VisibilityScope.PRIVATE).name());
|
||||
validateSkillPackage(skill);
|
||||
}
|
||||
|
||||
private void assertUniqueName(String name, BigInteger excludeId) {
|
||||
QueryWrapper query = QueryWrapper.create()
|
||||
.eq(Skill::getTenantId, requireCurrentLoginAccount().getTenantId())
|
||||
.eq(Skill::getName, name);
|
||||
if (excludeId != null) {
|
||||
query.ne(Skill::getId, excludeId);
|
||||
}
|
||||
if (count(query) > 0) {
|
||||
throw new BusinessException(409, 4092, "当前租户已存在同名 Skill:" + name);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateTargetCategoryVisible(BigInteger categoryId) {
|
||||
if (categoryId == null) {
|
||||
return;
|
||||
@@ -208,7 +617,8 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
skill.setEnabled(skill.getEnabled() == null || skill.getEnabled());
|
||||
skill.setSourceType(skill.getSourceType() == null ? "MANUAL" : skill.getSourceType());
|
||||
skill.setPublishStatus(PublishStatus.DRAFT.getCode());
|
||||
syncCounts(skill);
|
||||
skill.setCapabilityCount(0);
|
||||
skill.setCapabilityHash(capabilityBindingService.calculateHash(List.of()));
|
||||
}
|
||||
|
||||
private void applyDraftUpdate(Skill existing, Skill incoming) {
|
||||
@@ -221,69 +631,206 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
existing.setSkillContent(incoming.getSkillContent());
|
||||
existing.setEnabled(incoming.getEnabled() == null || incoming.getEnabled());
|
||||
existing.setVisibilityScope(incoming.getVisibilityScope());
|
||||
existing.setSourceType(incoming.getSourceType());
|
||||
existing.setPackageHash(incoming.getPackageHash());
|
||||
existing.setReferences(incoming.getReferences());
|
||||
existing.setScripts(incoming.getScripts());
|
||||
existing.setAssets(incoming.getAssets());
|
||||
syncCounts(existing);
|
||||
if (incoming.getSourceType() != null && !incoming.getSourceType().isBlank()) {
|
||||
existing.setSourceType(incoming.getSourceType());
|
||||
}
|
||||
existing.setModified(new Date());
|
||||
existing.setModifiedBy(account.getId());
|
||||
}
|
||||
|
||||
private void syncCounts(Skill skill) {
|
||||
skill.setReferenceCount(skill.getReferences() == null ? 0 : skill.getReferences().size());
|
||||
skill.setScriptCount(skill.getScripts() == null ? 0 : skill.getScripts().size());
|
||||
skill.setAssetCount(skill.getAssets() == null ? 0 : skill.getAssets().size());
|
||||
private void syncCounts(Skill skill, List<SkillResource> resources) {
|
||||
int references = 0;
|
||||
int scripts = 0;
|
||||
int assets = 0;
|
||||
for (SkillResource resource : resources) {
|
||||
if ("REFERENCE".equals(resource.getKind())) {
|
||||
references++;
|
||||
} else if ("SCRIPT".equals(resource.getKind())) {
|
||||
scripts++;
|
||||
} else if (!Boolean.TRUE.equals(resource.getIsText())) {
|
||||
assets++;
|
||||
}
|
||||
}
|
||||
skill.setResourceCount(resources.size());
|
||||
skill.setReferenceCount(references);
|
||||
skill.setScriptCount(scripts);
|
||||
skill.setAssetCount(assets);
|
||||
}
|
||||
|
||||
private void fillResources(Skill skill) {
|
||||
skill.setReferences(skillReferenceService.list(QueryWrapper.create().eq(SkillReference::getSkillId, skill.getId()).orderBy("path asc")));
|
||||
skill.setScripts(skillScriptService.list(QueryWrapper.create().eq(SkillScript::getSkillId, skill.getId()).orderBy("path asc")));
|
||||
skill.setAssets(skillAssetService.list(QueryWrapper.create().eq(SkillAsset::getSkillId, skill.getId()).orderBy("path asc")));
|
||||
List<SkillResource> resources = listResources(skill.getId());
|
||||
skill.setResources(resources);
|
||||
refreshPackageSummary(skill, resources);
|
||||
SkillResourceModelAdapter.fillCompatibilityViews(skill, resources);
|
||||
}
|
||||
|
||||
private void replaceResources(Skill skill) {
|
||||
removeResources(skill.getId());
|
||||
BigInteger tenantId = skill.getTenantId();
|
||||
BigInteger skillId = skill.getId();
|
||||
if (skill.getReferences() != null) {
|
||||
for (SkillReference reference : skill.getReferences()) {
|
||||
reference.setTenantId(tenantId);
|
||||
reference.setSkillId(skillId);
|
||||
skillReferenceService.save(reference);
|
||||
private void fillResourceDescriptors(Skill skill) {
|
||||
List<SkillResource> resources = skillResourceService.listDescriptors(
|
||||
skill.getId(), requireCurrentLoginAccount().getTenantId());
|
||||
skill.setResources(resources);
|
||||
refreshPackageSummary(skill, resources);
|
||||
}
|
||||
|
||||
private void refreshPackageSummary(Skill skill, List<SkillResource> resources) {
|
||||
String previousHash = skill.getPackageHash();
|
||||
syncCounts(skill, resources);
|
||||
skill.setPackageHash(calculatePackageHash(skill.getSkillContent(), resources));
|
||||
if (previousHash == null || previousHash.isBlank()) {
|
||||
getMapper().backfillPackageSummary(skill.getId(), skill.getTenantId(), skill.getPackageHash(),
|
||||
skill.getResourceCount(), skill.getReferenceCount(), skill.getScriptCount(), skill.getAssetCount());
|
||||
}
|
||||
}
|
||||
|
||||
private List<SkillResource> listResources(BigInteger skillId) {
|
||||
return skillResourceService.list(QueryWrapper.create()
|
||||
.eq(SkillResource::getTenantId, requireCurrentLoginAccount().getTenantId())
|
||||
.eq(SkillResource::getSkillId, skillId)
|
||||
.orderBy("sort_no asc, normalized_path asc"));
|
||||
}
|
||||
|
||||
private void replaceResources(Skill skill, List<SkillResource> resources) {
|
||||
List<SkillResource> oldResources = listResources(skill.getId());
|
||||
if (!oldResources.isEmpty()) {
|
||||
if (!skillResourceService.remove(QueryWrapper.create()
|
||||
.eq(SkillResource::getTenantId, skill.getTenantId())
|
||||
.eq(SkillResource::getSkillId, skill.getId()))) {
|
||||
throw new BusinessException(500, 500, "替换 Skill 资源失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
if (skill.getScripts() != null) {
|
||||
for (SkillScript script : skill.getScripts()) {
|
||||
script.setTenantId(tenantId);
|
||||
script.setSkillId(skillId);
|
||||
skillScriptService.save(script);
|
||||
if (!resources.isEmpty()) {
|
||||
if (!skillResourceService.saveBatch(resources)) {
|
||||
throw new BusinessException(500, 500, "保存 Skill 资源失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
if (skill.getAssets() != null) {
|
||||
for (SkillAsset asset : skill.getAssets()) {
|
||||
asset.setTenantId(tenantId);
|
||||
asset.setSkillId(skillId);
|
||||
skillAssetService.save(asset);
|
||||
for (SkillResource oldResource : oldResources) {
|
||||
if (oldResource.getContentRef() != null) {
|
||||
contentStore.release(oldResource.getContentRef());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void removeResources(BigInteger skillId) {
|
||||
skillReferenceService.remove(QueryWrapper.create().eq(SkillReference::getSkillId, skillId));
|
||||
skillScriptService.remove(QueryWrapper.create().eq(SkillScript::getSkillId, skillId));
|
||||
skillAssetService.remove(QueryWrapper.create().eq(SkillAsset::getSkillId, skillId));
|
||||
/**
|
||||
* 复制通用资源配置,数据库归属和审计字段由新草稿保存流程重建。
|
||||
*
|
||||
* @param source 源资源
|
||||
* @return 无持久化标识的资源副本
|
||||
*/
|
||||
private SkillResource copyResource(SkillResource source) {
|
||||
SkillResource target = new SkillResource();
|
||||
target.setPath(source.getPath());
|
||||
target.setNormalizedPath(source.getNormalizedPath());
|
||||
target.setKind(source.getKind());
|
||||
target.setLanguage(source.getLanguage());
|
||||
target.setMediaType(source.getMediaType());
|
||||
target.setIsText(source.getIsText());
|
||||
target.setTextContent(source.getTextContent());
|
||||
target.setContentRef(source.getContentRef());
|
||||
target.setContentHash(source.getContentHash());
|
||||
target.setSize(source.getSize());
|
||||
target.setMetadataJson(new LinkedHashMap<>(source.getMetadataJson()));
|
||||
target.setSortNo(source.getSortNo());
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制能力绑定配置,目标授权和派生状态由替换流程重新解析。
|
||||
*
|
||||
* @param source 源能力绑定
|
||||
* @return 无持久化标识的绑定副本
|
||||
*/
|
||||
private SkillCapabilityBinding copyBinding(SkillCapabilityBinding source) {
|
||||
SkillCapabilityBinding target = new SkillCapabilityBinding();
|
||||
target.setCapabilityType(source.getCapabilityType());
|
||||
target.setTargetId(source.getTargetId());
|
||||
target.setTargetLogicalRef(source.getTargetLogicalRef());
|
||||
target.setRuntimeName(source.getRuntimeName());
|
||||
target.setEnabled(source.getEnabled());
|
||||
target.setSelectionMode(source.getSelectionMode());
|
||||
target.setSelectedToolNamesJson(source.getSelectedToolNamesJson());
|
||||
target.setExecutionMode(source.getExecutionMode());
|
||||
target.setHitlEnabled(source.getHitlEnabled());
|
||||
target.setHitlConfigJson(source.getHitlConfigJson() == null
|
||||
? Map.of() : new LinkedHashMap<>(source.getHitlConfigJson()));
|
||||
target.setOptionsJson(source.getOptionsJson() == null
|
||||
? Map.of() : new LinkedHashMap<>(source.getOptionsJson()));
|
||||
target.setSortNo(source.getSortNo());
|
||||
return target;
|
||||
}
|
||||
|
||||
private void normalizeResources(Skill skill, List<SkillResource> resources) {
|
||||
Set<String> paths = new HashSet<>();
|
||||
LoginAccount account = requireCurrentLoginAccount();
|
||||
Date now = new Date();
|
||||
for (int index = 0; index < resources.size(); index++) {
|
||||
SkillResource resource = resources.get(index);
|
||||
if (resource == null) {
|
||||
throw new BusinessException("Skill 资源不能为空");
|
||||
}
|
||||
String normalizedPath;
|
||||
try {
|
||||
normalizedPath = SkillPaths.normalize(resource.getPath() == null
|
||||
? resource.getNormalizedPath() : resource.getPath());
|
||||
} catch (SkillException exception) {
|
||||
throw new BusinessException("Skill 资源路径不合法:" + exception.getMessage());
|
||||
}
|
||||
if (SkillPaths.SKILL_FILE.equals(normalizedPath)) {
|
||||
throw new BusinessException("SKILL.md 必须保存在 Skill 主表中");
|
||||
}
|
||||
if (normalizedPath.split("/").length > 16) {
|
||||
throw new BusinessException("Skill 资源路径层级不能超过 16 层:" + normalizedPath);
|
||||
}
|
||||
if (!paths.add(collisionKey(normalizedPath))) {
|
||||
throw new BusinessException("Skill 资源路径重复:" + normalizedPath);
|
||||
}
|
||||
resource.setId(null);
|
||||
resource.setTenantId(skill.getTenantId());
|
||||
resource.setSkillId(skill.getId());
|
||||
resource.setPath(normalizedPath);
|
||||
resource.setNormalizedPath(normalizedPath);
|
||||
resource.setSortNo(resource.getSortNo() == null ? index : resource.getSortNo());
|
||||
resource.setCreated(now);
|
||||
resource.setCreatedBy(account.getId());
|
||||
resource.setModified(now);
|
||||
resource.setModifiedBy(account.getId());
|
||||
if (Boolean.TRUE.equals(resource.getIsText())) {
|
||||
byte[] bytes = (resource.getTextContent() == null ? "" : resource.getTextContent())
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
resource.setContentRef(null);
|
||||
resource.setContentHash(SkillHashes.sha256Hex(bytes));
|
||||
resource.setSize((long) bytes.length);
|
||||
} else {
|
||||
if (resource.getContentRef() == null || !contentStore.exists(resource.getContentRef())) {
|
||||
throw new BusinessException("Skill 二进制资源内容不存在:" + normalizedPath);
|
||||
}
|
||||
String expectedHash = resource.getContentRef().startsWith("sha256:")
|
||||
? resource.getContentRef().substring("sha256:".length()) : null;
|
||||
if (expectedHash == null || !expectedHash.equals(resource.getContentHash())) {
|
||||
throw new BusinessException("Skill 二进制资源 hash 不一致:" + normalizedPath);
|
||||
}
|
||||
resource.setTextContent(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasResourcePayload(Skill skill) {
|
||||
return skill.getResources() != null || skill.getReferences() != null
|
||||
|| skill.getScripts() != null || skill.getAssets() != null;
|
||||
}
|
||||
|
||||
private void releaseContents(List<SkillResource> resources) {
|
||||
for (SkillResource resource : resources) {
|
||||
if (resource.getContentRef() != null) {
|
||||
contentStore.release(resource.getContentRef());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void normalizeFromSkillContent(Skill skill) {
|
||||
try {
|
||||
com.easyagents.skill.model.Skill parsed = SkillFactory.create(
|
||||
com.easyagents.skill.model.Skill parsed = SkillFactory.createWithResources(
|
||||
skill.getId() == null ? "draft" : String.valueOf(skill.getId()),
|
||||
skill.getSkillContent(),
|
||||
SkillModelConverter.toAgentReferences(skill.getReferences()),
|
||||
SkillModelConverter.toAgentScripts(skill.getScripts()),
|
||||
SkillModelConverter.toAgentAssets(skill.getAssets())
|
||||
SkillModelConverter.toAgentResources(SkillResourceModelAdapter.toResources(skill))
|
||||
);
|
||||
skill.setName(parsed.getName());
|
||||
if (skill.getDisplayName() == null || skill.getDisplayName().isBlank()) {
|
||||
@@ -291,27 +838,136 @@ public class SkillServiceImpl extends ServiceImpl<SkillMapper, Skill> implements
|
||||
}
|
||||
skill.setDescription(parsed.getDescription());
|
||||
skill.setMetadataJson(parsed.getMetadata().getValues());
|
||||
} catch (SkillException e) {
|
||||
throw new BusinessException("SKILL.md frontmatter 不合法:" + e.getMessage());
|
||||
} catch (SkillException exception) {
|
||||
throw new BusinessException("SKILL.md frontmatter 不合法:" + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateSkillPackage(Skill skill) {
|
||||
try {
|
||||
skillValidator.validate(SkillModelConverter.toAgentSkill(skill));
|
||||
} catch (SkillException e) {
|
||||
throw new BusinessException("Skill 包校验失败:" + e.getMessage());
|
||||
} catch (SkillException exception) {
|
||||
throw new BusinessException("Skill 包校验失败:" + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String calculatePackageHash(String skillContent, List<SkillResource> resources) {
|
||||
StringBuilder canonical = new StringBuilder();
|
||||
canonical.append(SkillPaths.SKILL_FILE).append('\n')
|
||||
.append(SkillHashes.sha256Hex((skillContent == null ? "" : skillContent)
|
||||
.getBytes(StandardCharsets.UTF_8))).append('\n');
|
||||
resources.stream().sorted(Comparator.comparing(SkillResource::getNormalizedPath))
|
||||
.forEach(resource -> canonical.append(resource.getNormalizedPath()).append('\n')
|
||||
.append(resource.getContentHash()).append('\n'));
|
||||
return SkillHashes.sha256Hex(canonical.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> buildResourceSnapshot(List<SkillResource> resources) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
for (SkillResource resource : resources) {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("path", resource.getNormalizedPath());
|
||||
item.put("kind", resource.getKind());
|
||||
item.put("language", resource.getLanguage());
|
||||
item.put("mediaType", resource.getMediaType());
|
||||
item.put("text", resource.getIsText());
|
||||
item.put("textContent", resource.getTextContent());
|
||||
item.put("contentRef", resource.getContentRef());
|
||||
item.put("contentHash", resource.getContentHash());
|
||||
item.put("size", resource.getSize());
|
||||
item.put("metadata", resource.getMetadataJson());
|
||||
result.add(item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String hashJson(Object value) {
|
||||
try {
|
||||
return SkillHashes.sha256Hex(objectMapper.writeValueAsBytes(canonicalizeJson(value)));
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new BusinessException(500, 500, "计算 Skill 发布快照 hash 失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Object canonicalizeJson(Object value) {
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
Map<String, Object> sorted = new TreeMap<>();
|
||||
map.forEach((key, item) -> sorted.put(String.valueOf(key), canonicalizeJson(item)));
|
||||
return sorted;
|
||||
}
|
||||
if (value instanceof List<?> list) {
|
||||
return list.stream().map(this::canonicalizeJson).toList();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取新旧发布快照中的二进制内容引用。
|
||||
*
|
||||
* @param snapshot 发布或审批快照
|
||||
* @return 按资源出现次数保留的内容引用
|
||||
*/
|
||||
private List<String> snapshotContentRefs(Map<String, Object> snapshot) {
|
||||
if (snapshot == null) {
|
||||
return List.of();
|
||||
}
|
||||
Object resources = snapshot.get("resources");
|
||||
if (resources instanceof List<?> resourceList) {
|
||||
return collectSnapshotContentRefs(resourceList);
|
||||
}
|
||||
// V24 published snapshots stored binary resources in assets[]. Keep this fallback until
|
||||
// every legacy snapshot has naturally been replaced or removed through the lifecycle.
|
||||
Object assets = snapshot.get("assets");
|
||||
return assets instanceof List<?> assetList ? collectSnapshotContentRefs(assetList) : List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从资源数组中收集非空内容引用。
|
||||
*
|
||||
* @param resources 快照资源数组
|
||||
* @return 内容引用列表
|
||||
*/
|
||||
private List<String> collectSnapshotContentRefs(List<?> resources) {
|
||||
List<String> refs = new ArrayList<>();
|
||||
for (Object item : resources) {
|
||||
if (item instanceof Map<?, ?> resource) {
|
||||
Object contentRef = resource.get("contentRef");
|
||||
if (contentRef instanceof String value && !value.isBlank()) {
|
||||
refs.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
private boolean isCanonicalName(String name) {
|
||||
return name != null && name.matches("[a-z0-9]+(?:-[a-z0-9]+)*");
|
||||
}
|
||||
|
||||
private boolean isLegacyImportName(Skill skill) {
|
||||
String sourceType = skill.getSourceType();
|
||||
return ("STANDARD_ZIP".equals(sourceType) || "EASYFLOW_BUNDLE".equals(sourceType))
|
||||
&& skill.getName() != null && skill.getName().matches("[a-z0-9]+(?:[_-][a-z0-9]+)*");
|
||||
}
|
||||
|
||||
private String collisionKey(String path) {
|
||||
return Normalizer.normalize(path, Normalizer.Form.NFKC).toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private LoginAccount requireCurrentLoginAccount() {
|
||||
LoginAccount account = SaTokenUtil.getLoginAccount();
|
||||
if (account == null || account.getId() == null) {
|
||||
throw new BusinessException("未登录或登录态无效");
|
||||
if (account == null || account.getId() == null || account.getTenantId() == null) {
|
||||
throw new BusinessException(401, 401, "未登录或登录态无效");
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
private QueryWrapper tenantSkillQuery(BigInteger skillId) {
|
||||
return QueryWrapper.create()
|
||||
.eq(Skill::getId, skillId)
|
||||
.eq(Skill::getTenantId, requireCurrentLoginAccount().getTenantId());
|
||||
}
|
||||
|
||||
private BigInteger toBigInteger(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,7 @@ import com.easyagents.skill.model.SkillScriptLanguage;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
|
||||
import java.math.BigInteger;
|
||||
@@ -26,13 +27,14 @@ public final class SkillModelConverter {
|
||||
* @return easy-agents-skill 聚合
|
||||
*/
|
||||
public static com.easyagents.skill.model.Skill toAgentSkill(Skill skill) {
|
||||
return SkillFactory.create(
|
||||
com.easyagents.skill.model.Skill result = SkillFactory.createWithResources(
|
||||
String.valueOf(skill.getId()),
|
||||
skill.getSkillContent(),
|
||||
toAgentReferences(skill.getReferences()),
|
||||
toAgentScripts(skill.getScripts()),
|
||||
toAgentAssets(skill.getAssets())
|
||||
toAgentResources(skill.getResources() == null
|
||||
? SkillResourceModelAdapter.toResources(skill) : skill.getResources())
|
||||
);
|
||||
result.setPackageRoot(skill.getName());
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,6 +50,7 @@ public final class SkillModelConverter {
|
||||
skill.setDescription(imported.getDescription());
|
||||
skill.setMetadataJson(imported.getMetadata().getValues());
|
||||
skill.setSkillContent(imported.getSkillContent());
|
||||
skill.setResources(imported.getResources().stream().map(SkillModelConverter::fromAgentResource).toList());
|
||||
skill.setReferences(imported.getReferences().stream()
|
||||
.map(item -> fromAgentReference(null, null, item))
|
||||
.toList());
|
||||
@@ -64,61 +67,46 @@ public final class SkillModelConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换 reference 列表。
|
||||
* 转换通用资源列表到 M18 标准模型。
|
||||
*
|
||||
* @param references reference 实体
|
||||
* @return easy-agents-skill reference
|
||||
* @param resources EasyFlow 通用资源
|
||||
* @return M18 通用资源
|
||||
*/
|
||||
public static List<com.easyagents.skill.model.SkillReference> toAgentReferences(List<SkillReference> references) {
|
||||
return references == null ? List.of() : references.stream().map(item -> {
|
||||
com.easyagents.skill.model.SkillReference target = new com.easyagents.skill.model.SkillReference();
|
||||
target.setPath(item.getPath());
|
||||
target.setName(item.getName());
|
||||
target.setContent(item.getContent());
|
||||
target.setContentHash(item.getContentHash());
|
||||
target.setSize(item.getSize() == null ? 0L : item.getSize());
|
||||
target.setMetadata(new SkillMetadata(item.getMetadataJson()));
|
||||
public static List<com.easyagents.skill.model.SkillResource> toAgentResources(List<SkillResource> resources) {
|
||||
return resources == null ? List.of() : resources.stream().map(source -> {
|
||||
com.easyagents.skill.model.SkillResource target = new com.easyagents.skill.model.SkillResource();
|
||||
target.setPath(source.getNormalizedPath() == null ? source.getPath() : source.getNormalizedPath());
|
||||
target.setKind(parseResourceKind(source.getKind()));
|
||||
target.setMediaType(source.getMediaType());
|
||||
target.setTextContent(source.getTextContent());
|
||||
target.setContentRef(source.getContentRef());
|
||||
target.setContentHash(source.getContentHash());
|
||||
target.setSize(source.getSize() == null ? 0L : source.getSize());
|
||||
target.setMetadata(new SkillMetadata(source.getMetadataJson()));
|
||||
return target;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换 script 列表。
|
||||
* 转换 M18 通用资源到 EasyFlow 持久化模型。
|
||||
*
|
||||
* @param scripts script 实体
|
||||
* @return easy-agents-skill script
|
||||
* @param source M18 通用资源
|
||||
* @return EasyFlow 通用资源
|
||||
*/
|
||||
public static List<com.easyagents.skill.model.SkillScript> toAgentScripts(List<SkillScript> scripts) {
|
||||
return scripts == null ? List.of() : scripts.stream().map(item -> {
|
||||
com.easyagents.skill.model.SkillScript target = new com.easyagents.skill.model.SkillScript();
|
||||
target.setPath(item.getPath());
|
||||
target.setLanguage(parseLanguage(item.getLanguage()));
|
||||
target.setContent(item.getContent());
|
||||
target.setContentHash(item.getContentHash());
|
||||
target.setSize(item.getSize() == null ? 0L : item.getSize());
|
||||
target.setMetadata(new SkillMetadata(item.getMetadataJson()));
|
||||
return target;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换 asset 列表。
|
||||
*
|
||||
* @param assets asset 实体
|
||||
* @return easy-agents-skill asset
|
||||
*/
|
||||
public static List<com.easyagents.skill.model.SkillAsset> toAgentAssets(List<SkillAsset> assets) {
|
||||
return assets == null ? List.of() : assets.stream().map(item -> {
|
||||
com.easyagents.skill.model.SkillAsset target = new com.easyagents.skill.model.SkillAsset();
|
||||
target.setPath(item.getPath());
|
||||
target.setName(item.getName());
|
||||
target.setMediaType(item.getMediaType());
|
||||
target.setContentRef(item.getContentRef());
|
||||
target.setContentHash(item.getContentHash());
|
||||
target.setSize(item.getSize() == null ? 0L : item.getSize());
|
||||
target.setMetadata(new SkillMetadata(item.getMetadataJson()));
|
||||
return target;
|
||||
}).toList();
|
||||
public static SkillResource fromAgentResource(com.easyagents.skill.model.SkillResource source) {
|
||||
SkillResource target = new SkillResource();
|
||||
target.setPath(source.getPath());
|
||||
target.setNormalizedPath(source.getPath());
|
||||
target.setKind(source.getKind().name());
|
||||
target.setLanguage(resolveResourceLanguage(source));
|
||||
target.setMediaType(source.getMediaType());
|
||||
target.setIsText(source.isText());
|
||||
target.setTextContent(source.getTextContent());
|
||||
target.setContentRef(source.getContentRef());
|
||||
target.setContentHash(source.getContentHash());
|
||||
target.setSize(source.getSize());
|
||||
target.setMetadataJson(source.getMetadata().getValues());
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,14 +176,22 @@ public final class SkillModelConverter {
|
||||
return target;
|
||||
}
|
||||
|
||||
private static SkillScriptLanguage parseLanguage(String language) {
|
||||
if (language == null || language.isBlank()) {
|
||||
return SkillScriptLanguage.UNKNOWN;
|
||||
private static com.easyagents.skill.model.SkillResourceKind parseResourceKind(String kind) {
|
||||
if (kind == null || kind.isBlank()) {
|
||||
return com.easyagents.skill.model.SkillResourceKind.OTHER;
|
||||
}
|
||||
try {
|
||||
return SkillScriptLanguage.valueOf(language);
|
||||
return com.easyagents.skill.model.SkillResourceKind.valueOf(kind);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return SkillScriptLanguage.UNKNOWN;
|
||||
return com.easyagents.skill.model.SkillResourceKind.OTHER;
|
||||
}
|
||||
}
|
||||
|
||||
private static String resolveResourceLanguage(com.easyagents.skill.model.SkillResource resource) {
|
||||
if (resource.getKind() == com.easyagents.skill.model.SkillResourceKind.SCRIPT) {
|
||||
SkillScriptLanguage language = SkillScriptLanguage.fromPath(resource.getPath());
|
||||
return language == SkillScriptLanguage.UNKNOWN ? null : language.name();
|
||||
}
|
||||
return resource.getKind() == com.easyagents.skill.model.SkillResourceKind.REFERENCE ? "MARKDOWN" : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package tech.easyflow.skill.support;
|
||||
|
||||
import com.easyagents.skill.model.SkillResourceKind;
|
||||
import com.easyagents.skill.model.SkillScriptLanguage;
|
||||
import com.easyagents.skill.util.SkillPaths;
|
||||
import com.easyagents.skill.util.SkillResources;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillAsset;
|
||||
import tech.easyflow.skill.entity.SkillReference;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
import tech.easyflow.skill.entity.SkillScript;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 通用 Skill 资源与试验版三类资源视图之间的兼容适配器。
|
||||
*/
|
||||
public final class SkillResourceModelAdapter {
|
||||
|
||||
private SkillResourceModelAdapter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Skill 入参中的通用资源或旧资源视图归一化为通用资源。
|
||||
*
|
||||
* @param skill Skill 聚合
|
||||
* @return 通用资源列表
|
||||
*/
|
||||
public static List<SkillResource> toResources(Skill skill) {
|
||||
if (skill.getResources() != null) {
|
||||
return new ArrayList<>(skill.getResources());
|
||||
}
|
||||
List<SkillResource> resources = new ArrayList<>();
|
||||
if (skill.getReferences() != null) {
|
||||
for (SkillReference reference : skill.getReferences()) {
|
||||
SkillResource resource = textResource(reference.getPath(), SkillResourceKind.REFERENCE,
|
||||
"MARKDOWN", "text/markdown", reference.getContent(), reference.getContentHash(),
|
||||
reference.getSize(), reference.getMetadataJson());
|
||||
resources.add(resource);
|
||||
}
|
||||
}
|
||||
if (skill.getScripts() != null) {
|
||||
for (SkillScript script : skill.getScripts()) {
|
||||
SkillResource resource = textResource(script.getPath(), SkillResourceKind.SCRIPT,
|
||||
script.getLanguage(), "text/plain", script.getContent(), script.getContentHash(),
|
||||
script.getSize(), script.getMetadataJson());
|
||||
resources.add(resource);
|
||||
}
|
||||
}
|
||||
if (skill.getAssets() != null) {
|
||||
for (SkillAsset asset : skill.getAssets()) {
|
||||
SkillResource resource = new SkillResource();
|
||||
resource.setPath(asset.getPath());
|
||||
resource.setNormalizedPath(SkillPaths.normalize(asset.getPath()));
|
||||
resource.setKind(SkillResourceKind.ASSET.name());
|
||||
resource.setMediaType(asset.getMediaType());
|
||||
resource.setIsText(false);
|
||||
resource.setContentRef(asset.getContentRef());
|
||||
resource.setContentHash(asset.getContentHash());
|
||||
resource.setSize(asset.getSize());
|
||||
resource.setMetadataJson(asset.getMetadataJson());
|
||||
resources.add(resource);
|
||||
}
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据通用资源回填旧版 reference/script/asset 只读兼容视图。
|
||||
*
|
||||
* @param skill Skill 聚合
|
||||
* @param resources 通用资源
|
||||
*/
|
||||
public static void fillCompatibilityViews(Skill skill, List<SkillResource> resources) {
|
||||
List<SkillReference> references = new ArrayList<>();
|
||||
List<SkillScript> scripts = new ArrayList<>();
|
||||
List<SkillAsset> assets = new ArrayList<>();
|
||||
for (SkillResource resource : resources == null ? List.<SkillResource>of() : resources) {
|
||||
SkillResourceKind kind = parseKind(resource.getKind(), resource.getNormalizedPath());
|
||||
if (kind == SkillResourceKind.REFERENCE) {
|
||||
SkillReference reference = new SkillReference();
|
||||
reference.setId(resource.getId());
|
||||
reference.setTenantId(resource.getTenantId());
|
||||
reference.setSkillId(resource.getSkillId());
|
||||
reference.setPath(resource.getNormalizedPath());
|
||||
reference.setName(SkillPaths.fileName(resource.getNormalizedPath()));
|
||||
reference.setContent(resource.getTextContent());
|
||||
reference.setContentHash(resource.getContentHash());
|
||||
reference.setSize(resource.getSize());
|
||||
reference.setMetadataJson(resource.getMetadataJson());
|
||||
references.add(reference);
|
||||
} else if (kind == SkillResourceKind.SCRIPT) {
|
||||
SkillScript script = new SkillScript();
|
||||
script.setId(resource.getId());
|
||||
script.setTenantId(resource.getTenantId());
|
||||
script.setSkillId(resource.getSkillId());
|
||||
script.setPath(resource.getNormalizedPath());
|
||||
script.setLanguage(resource.getLanguage());
|
||||
script.setContent(resource.getTextContent());
|
||||
script.setContentHash(resource.getContentHash());
|
||||
script.setSize(resource.getSize());
|
||||
script.setMetadataJson(resource.getMetadataJson());
|
||||
scripts.add(script);
|
||||
} else if (!Boolean.TRUE.equals(resource.getIsText())) {
|
||||
SkillAsset asset = new SkillAsset();
|
||||
asset.setId(resource.getId());
|
||||
asset.setTenantId(resource.getTenantId());
|
||||
asset.setSkillId(resource.getSkillId());
|
||||
asset.setPath(resource.getNormalizedPath());
|
||||
asset.setName(SkillPaths.fileName(resource.getNormalizedPath()));
|
||||
asset.setMediaType(resource.getMediaType());
|
||||
asset.setContentRef(resource.getContentRef());
|
||||
asset.setContentHash(resource.getContentHash());
|
||||
asset.setSize(resource.getSize());
|
||||
asset.setMetadataJson(resource.getMetadataJson());
|
||||
assets.add(asset);
|
||||
}
|
||||
}
|
||||
references.sort(Comparator.comparing(SkillReference::getPath));
|
||||
scripts.sort(Comparator.comparing(SkillScript::getPath));
|
||||
assets.sort(Comparator.comparing(SkillAsset::getPath));
|
||||
skill.setReferences(references);
|
||||
skill.setScripts(scripts);
|
||||
skill.setAssets(assets);
|
||||
}
|
||||
|
||||
private static SkillResource textResource(String path,
|
||||
SkillResourceKind kind,
|
||||
String language,
|
||||
String mediaType,
|
||||
String content,
|
||||
String hash,
|
||||
Long size,
|
||||
java.util.Map<String, Object> metadata) {
|
||||
SkillResource resource = new SkillResource();
|
||||
resource.setPath(path);
|
||||
resource.setNormalizedPath(SkillPaths.normalize(path));
|
||||
resource.setKind(kind.name());
|
||||
resource.setLanguage(language);
|
||||
resource.setMediaType(mediaType);
|
||||
resource.setIsText(true);
|
||||
resource.setTextContent(content);
|
||||
resource.setContentHash(hash);
|
||||
resource.setSize(size);
|
||||
resource.setMetadataJson(metadata == null ? new LinkedHashMap<>() : metadata);
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static SkillResourceKind parseKind(String value, String path) {
|
||||
if (value != null) {
|
||||
try {
|
||||
return SkillResourceKind.valueOf(value);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// 旧数据或外部扩展类型按路径与文本属性安全降级。
|
||||
}
|
||||
}
|
||||
return SkillResources.classify(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package tech.easyflow.skill.validation;
|
||||
|
||||
/**
|
||||
* Skill 包或能力配置的结构化校验问题。
|
||||
*/
|
||||
public class SkillValidationIssue {
|
||||
|
||||
private String severity;
|
||||
private String code;
|
||||
private String message;
|
||||
private String path;
|
||||
private Integer line;
|
||||
private Integer column;
|
||||
private String suggestion;
|
||||
|
||||
/**
|
||||
* 创建校验问题。
|
||||
*
|
||||
* @param severity 严重级别
|
||||
* @param code 问题编码
|
||||
* @param message 可执行的错误说明
|
||||
* @param path 文件或配置路径
|
||||
* @return 校验问题
|
||||
*/
|
||||
public static SkillValidationIssue of(String severity, String code, String message, String path) {
|
||||
SkillValidationIssue issue = new SkillValidationIssue();
|
||||
issue.setSeverity(severity);
|
||||
issue.setCode(code);
|
||||
issue.setMessage(message);
|
||||
issue.setPath(path);
|
||||
return issue;
|
||||
}
|
||||
|
||||
public String getSeverity() { return severity; }
|
||||
public void setSeverity(String severity) { this.severity = severity; }
|
||||
public String getCode() { return code; }
|
||||
public void setCode(String code) { this.code = code; }
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
public String getPath() { return path; }
|
||||
public void setPath(String path) { this.path = path; }
|
||||
public Integer getLine() { return line; }
|
||||
public void setLine(Integer line) { this.line = line; }
|
||||
public Integer getColumn() { return column; }
|
||||
public void setColumn(Integer column) { this.column = column; }
|
||||
public String getSuggestion() { return suggestion; }
|
||||
public void setSuggestion(String suggestion) { this.suggestion = suggestion; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package tech.easyflow.skill.validation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Skill 全量校验结果。
|
||||
*/
|
||||
public class SkillValidationResult {
|
||||
|
||||
private boolean valid;
|
||||
private List<SkillValidationIssue> issues = new ArrayList<>();
|
||||
|
||||
public boolean isValid() { return valid; }
|
||||
public void setValid(boolean valid) { this.valid = valid; }
|
||||
public List<SkillValidationIssue> getIssues() { return issues; }
|
||||
public void setIssues(List<SkillValidationIssue> issues) { this.issues = issues == null ? new ArrayList<>() : new ArrayList<>(issues); }
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import tech.easyflow.ai.permission.McpAccessPermissionChecker;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.mapper.SkillCapabilityBindingMapper;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.validation.SkillValidationIssue;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
import tech.easyflow.system.enums.CategoryResourceType;
|
||||
import tech.easyflow.system.enums.ResourceAction;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.same;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link SkillCapabilityBindingServiceImpl} 能力命名、MCP 选择、安全配置和权限测试。
|
||||
*/
|
||||
public class SkillCapabilityBindingServiceImplTest {
|
||||
|
||||
private static final BigInteger SKILL_ID = BigInteger.valueOf(101);
|
||||
|
||||
private SkillMapper skillMapper;
|
||||
private SkillCapabilityTargetAccessService targetAccessService;
|
||||
private McpAccessPermissionChecker mcpAccessPermissionChecker;
|
||||
private ResourceAccessService resourceAccessService;
|
||||
private SkillCapabilityBindingServiceImpl service;
|
||||
private Skill skill;
|
||||
private MockedStatic<SaTokenUtil> saToken;
|
||||
|
||||
/**
|
||||
* 初始化能力绑定服务及默认可用目标。
|
||||
*/
|
||||
@Before
|
||||
public void setUp() {
|
||||
skillMapper = mock(SkillMapper.class);
|
||||
targetAccessService = mock(SkillCapabilityTargetAccessService.class);
|
||||
mcpAccessPermissionChecker = mock(McpAccessPermissionChecker.class);
|
||||
resourceAccessService = mock(ResourceAccessService.class);
|
||||
service = new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mcpAccessPermissionChecker,
|
||||
resourceAccessService, new ObjectMapper());
|
||||
skill = new Skill();
|
||||
skill.setId(SKILL_ID);
|
||||
skill.setTenantId(BigInteger.ONE);
|
||||
LoginAccount account = new LoginAccount();
|
||||
account.setId(BigInteger.valueOf(7));
|
||||
account.setTenantId(BigInteger.ONE);
|
||||
saToken = mockStatic(SaTokenUtil.class);
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
when(skillMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(skill);
|
||||
when(targetAccessService.requireUsableTarget(any(SkillCapabilityBinding.class), anyBoolean()))
|
||||
.thenReturn(target(List.of("alpha", "beta")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放静态登录态 Mock。
|
||||
*/
|
||||
@After
|
||||
public void tearDown() {
|
||||
saToken.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证非 MCP 能力的 runtimeName 按大小写不敏感规则判重。
|
||||
*/
|
||||
@Test
|
||||
public void duplicateRuntimeNamesAreRejectedCaseInsensitively() {
|
||||
SkillCapabilityBinding first = binding("WORKFLOW", 1, "RunFlow");
|
||||
SkillCapabilityBinding second = binding("PLUGIN_ITEM", 2, "runflow");
|
||||
|
||||
SkillValidationResult result = service.validateBindings(SKILL_ID, List.of(first, second), false);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(hasIssue(result, "RUNTIME_NAME_DUPLICATE"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 MCP SELECTED 工具会确定性去重、排序并固化最终工具名。
|
||||
*/
|
||||
@Test
|
||||
public void selectedMcpToolsAreDeduplicatedAndSorted() {
|
||||
SkillCapabilityBinding binding = mcpBinding("demo", List.of("beta", "alpha", "alpha"));
|
||||
|
||||
SkillValidationResult result = service.validateBindings(SKILL_ID, List.of(binding), true);
|
||||
|
||||
assertTrue(result.getIssues().toString(), result.isValid());
|
||||
assertEquals(List.of("alpha", "beta"), binding.getSelectedToolNamesJson());
|
||||
assertEquals(List.of("alpha", "beta"), binding.getResolvedToolNames());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证保存 MCP 绑定会重新校验目标权限,并在任何删除或写入发生前拒绝无权用户。
|
||||
*/
|
||||
@Test
|
||||
public void replacingMcpBindingsRejectsMissingTargetPermissionBeforePersistence() {
|
||||
SkillCapabilityBinding binding = mcpBinding("securedMcp", List.of("alpha"));
|
||||
when(targetAccessService.requireUsableTarget(binding, false))
|
||||
.thenThrow(new BusinessException(403, 403, "无权限查询或使用 MCP"));
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.replaceBindings(SKILL_ID, List.of(binding)));
|
||||
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
verify(mcpAccessPermissionChecker).assertCanUseMcp();
|
||||
verify(skillMapper, never()).updateByQuery(any(Skill.class), any(QueryWrapper.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证禁用且尚未映射的 MCP 绑定也不能绕过保存时的 MCP 模块权限。
|
||||
*/
|
||||
@Test
|
||||
public void disabledUnmappedMcpStillRequiresPermissionOnSave() {
|
||||
SkillCapabilityBinding binding = mcpBinding("securedMcp", List.of("alpha"));
|
||||
binding.setTargetId(null);
|
||||
binding.setTargetLogicalRef("mcp:unmapped");
|
||||
binding.setEnabled(false);
|
||||
doThrow(new BusinessException(403, 403, "无权限查询或使用 MCP"))
|
||||
.when(mcpAccessPermissionChecker).assertCanUseMcp();
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.replaceBindings(SKILL_ID, List.of(binding)));
|
||||
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
verify(targetAccessService, never()).requireUsableTarget(any(), anyBoolean());
|
||||
verify(skillMapper, never()).updateByQuery(any(Skill.class), any(QueryWrapper.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证发布快照会重新校验 MCP 权限,不能沿用保存时或前端传入的授权状态。
|
||||
*/
|
||||
@Test
|
||||
public void publishingMcpBindingRevalidatesTargetPermission() {
|
||||
SkillCapabilityBinding binding = mcpBinding("securedMcp", List.of("alpha"));
|
||||
SkillCapabilityBindingServiceImpl publishService = spy(service);
|
||||
doReturn(List.of(binding)).when(publishService).list(any(QueryWrapper.class));
|
||||
doThrow(new BusinessException(403, 403, "无权限查询或使用 MCP"))
|
||||
.when(mcpAccessPermissionChecker).assertCanUseMcp();
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> publishService.buildPublishSnapshot(SKILL_ID));
|
||||
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
verify(mcpAccessPermissionChecker).assertCanUseMcp();
|
||||
verify(targetAccessService, never()).requireUsableTarget(any(), anyBoolean());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证草稿能力 hash 只覆盖持久化配置,不受发布时解析工具清单影响。
|
||||
*/
|
||||
@Test
|
||||
public void draftCapabilityHashIgnoresTransientResolvedTools() {
|
||||
SkillCapabilityBinding saved = mcpBinding("demo", List.of("beta", "alpha"));
|
||||
saved.setSortNo(0);
|
||||
SkillValidationResult validation = service.validateBindings(SKILL_ID, List.of(saved), false);
|
||||
assertTrue(validation.getIssues().toString(), validation.isValid());
|
||||
String responseHash = service.calculateHash(List.of(saved));
|
||||
|
||||
SkillCapabilityBinding reloaded = mcpBinding("demo", List.of("alpha", "beta"));
|
||||
reloaded.setSortNo(0);
|
||||
// targetLogicalRef 是校验后持久化的稳定配置,模拟数据库回读时应与已保存值一致。
|
||||
reloaded.setTargetLogicalRef(saved.getTargetLogicalRef());
|
||||
reloaded.setHitlEnabled(saved.getHitlEnabled());
|
||||
reloaded.setResolvedToolNames(List.of());
|
||||
String persistedHash = service.calculateHash(List.of(reloaded));
|
||||
|
||||
assertEquals(responseHash, persistedHash);
|
||||
reloaded.setResolvedToolNames(List.of("changed-after-publish"));
|
||||
assertEquals(persistedHash, service.calculateHash(List.of(reloaded)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 能力批量写入失败属于服务端持久化故障,应返回 5xx。
|
||||
*/
|
||||
@Test
|
||||
public void replacePersistenceFailureUsesServerErrorStatus() {
|
||||
SkillCapabilityBindingServiceImpl failingService = spy(service);
|
||||
doReturn(0L).when(failingService).count(any(QueryWrapper.class));
|
||||
doReturn(false).when(failingService).saveBatch(any(List.class));
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> failingService.replaceBindings(
|
||||
SKILL_ID, List.of(binding("WORKFLOW", 1, "runFlow"))));
|
||||
|
||||
assertEquals(500, exception.getHttpStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空能力绑定时必须删除全部旧记录,并将能力摘要归零为确定性的空列表 hash。
|
||||
*/
|
||||
@Test
|
||||
public void clearingBindingsDeletesAllRowsAndResetsSummary() {
|
||||
SkillCapabilityBindingMapper bindingMapper = mock(SkillCapabilityBindingMapper.class);
|
||||
SkillCapabilityBindingServiceImpl clearingService = spy(service);
|
||||
String emptyCapabilityHash = "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945";
|
||||
doReturn(bindingMapper).when(clearingService).getMapper();
|
||||
doReturn(2L).when(clearingService).count(any(QueryWrapper.class));
|
||||
doReturn(List.of()).when(clearingService).list(any(QueryWrapper.class));
|
||||
when(bindingMapper.deleteByQuery(any(QueryWrapper.class))).thenReturn(2);
|
||||
when(skillMapper.updateByQuery(any(Skill.class), any(QueryWrapper.class))).thenReturn(1);
|
||||
|
||||
List<SkillCapabilityBinding> result = clearingService.replaceBindings(SKILL_ID, List.of());
|
||||
|
||||
ArgumentCaptor<Skill> updateCaptor = ArgumentCaptor.forClass(Skill.class);
|
||||
verify(clearingService, times(1)).count(any(QueryWrapper.class));
|
||||
verify(bindingMapper, times(1)).deleteByQuery(any(QueryWrapper.class));
|
||||
verify(skillMapper).updateByQuery(updateCaptor.capture(), any(QueryWrapper.class));
|
||||
assertTrue(result.isEmpty());
|
||||
assertEquals(Integer.valueOf(0), updateCaptor.getValue().getCapabilityCount());
|
||||
assertEquals(emptyCapabilityHash, updateCaptor.getValue().getCapabilityHash());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 MCP SELECTED 空选择和已消失工具都会返回明确结构化错误。
|
||||
*/
|
||||
@Test
|
||||
public void selectedMcpRequiresToolsAndRejectsMissingToolsOnPublish() {
|
||||
SkillCapabilityBinding empty = mcpBinding("empty", List.of());
|
||||
SkillValidationResult emptyResult = service.validateBindings(SKILL_ID, List.of(empty), false);
|
||||
assertTrue(hasIssue(emptyResult, "MCP_TOOL_SELECTION_EMPTY"));
|
||||
|
||||
when(targetAccessService.requireUsableTarget(any(SkillCapabilityBinding.class), eq(true)))
|
||||
.thenReturn(target(List.of("alpha")));
|
||||
SkillCapabilityBinding missing = mcpBinding("missing", List.of("alpha", "removed"));
|
||||
SkillValidationResult missingResult = service.validateBindings(SKILL_ID, List.of(missing), true);
|
||||
|
||||
assertFalse(missingResult.isValid());
|
||||
assertTrue(hasIssue(missingResult, "MCP_TOOL_MISSING"));
|
||||
assertFalse(issue(missingResult, "MCP_TOOL_MISSING").getMessage().contains("removed"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证客户端提交的敏感或未知 options 被拒绝,并只留下安全白名单字段。
|
||||
*/
|
||||
@Test
|
||||
public void sensitiveAndUnknownClientOptionsAreRejected() {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", 1, "safeFlow");
|
||||
Map<String, Object> options = new LinkedHashMap<>();
|
||||
options.put("timeoutMs", 2_000);
|
||||
options.put("token", "secret");
|
||||
options.put("customOption", true);
|
||||
options.put("readOnly", Map.of("nested", "unsafe"));
|
||||
binding.setOptionsJson(options);
|
||||
|
||||
SkillValidationResult result = service.validateBindings(SKILL_ID, List.of(binding), false);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(hasIssue(result, "CAPABILITY_OPTIONS_UNSAFE"));
|
||||
assertEquals(Map.of("timeoutMs", 2_000), binding.getOptionsJson());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证导入预览会报告 manifest 静态配置问题,同时不把待映射目标本身视为错误。
|
||||
*/
|
||||
@Test
|
||||
public void importPreviewReportsStaticErrorsWithoutBlockingUnresolvedTargets() {
|
||||
SkillCapabilityBinding first = unresolvedBinding("WORKFLOW", "workflow:first", "sharedName");
|
||||
first.setSelectionMode("SELECTED");
|
||||
first.setSelectedToolNamesJson(List.of("search"));
|
||||
first.setOptionsJson(Map.of("timeoutMs", 99, "retryCount", 11));
|
||||
SkillCapabilityBinding second = unresolvedBinding("PLUGIN_ITEM", "plugin-item:demo/tool", "sharedName");
|
||||
SkillCapabilityBinding mcp = unresolvedBinding("MCP", "mcp:demo", "mcpTools");
|
||||
mcp.setSelectionMode("SELECTED");
|
||||
mcp.setSelectedToolNamesJson(List.of());
|
||||
mcp.setExecutionMode("SYNC");
|
||||
|
||||
SkillValidationResult result = service.validateImportBindings(List.of(first, second, mcp));
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(hasIssue(result, "CAPABILITY_OPTION_VALUE_INVALID"));
|
||||
assertTrue(hasIssue(result, "RUNTIME_NAME_DUPLICATE"));
|
||||
assertTrue(hasIssue(result, "MCP_SELECTION_MODE_NOT_ALLOWED"));
|
||||
assertTrue(hasIssue(result, "MCP_TOOL_SELECTION_NOT_ALLOWED"));
|
||||
assertTrue(hasIssue(result, "MCP_EXECUTION_MODE_NOT_ALLOWED"));
|
||||
assertTrue(hasIssue(result, "MCP_TOOL_SELECTION_EMPTY"));
|
||||
assertFalse(hasIssue(result, "TARGET_UNRESOLVED"));
|
||||
verify(targetAccessService, never()).requireUsableTarget(any(), anyBoolean());
|
||||
verifyNoInteractions(skillMapper, resourceAccessService);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证有效的未映射能力可通过导入静态校验,留待映射步骤处理。
|
||||
*/
|
||||
@Test
|
||||
public void importPreviewAcceptsValidUnresolvedBinding() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding(
|
||||
"WORKFLOW", "workflow:portable-flow", "portableFlow");
|
||||
|
||||
SkillValidationResult result = service.validateImportBindings(List.of(binding));
|
||||
|
||||
assertTrue(result.getIssues().toString(), result.isValid());
|
||||
assertTrue(result.getIssues().isEmpty());
|
||||
verify(targetAccessService, never()).requireUsableTarget(any(), anyBoolean());
|
||||
verifyNoInteractions(skillMapper, resourceAccessService);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证自动映射成功的目标仍执行可用性和当前操作者授权校验。
|
||||
*/
|
||||
@Test
|
||||
public void importPreviewRevalidatesResolvedTargetPermission() {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", 92, "securedFlow");
|
||||
binding.setTargetLogicalRef("workflow:secured-flow");
|
||||
when(targetAccessService.requireUsableTarget(binding, false))
|
||||
.thenThrow(new BusinessException(403, 403, "无权限使用绑定工作流"));
|
||||
|
||||
SkillValidationResult result = service.validateImportBindings(List.of(binding));
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(hasIssue(result, "TARGET_NO_PERMISSION"));
|
||||
verify(targetAccessService).requireUsableTarget(binding, false);
|
||||
verifyNoInteractions(skillMapper, resourceAccessService);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证发布快照复用发布校验得到的目标摘要,并缓存同一目标的重复绑定查询。
|
||||
*/
|
||||
@Test
|
||||
public void publishSnapshotReusesValidatedTargetWithinRequest() {
|
||||
SkillCapabilityBinding first = binding("WORKFLOW", 93, "firstFlow");
|
||||
SkillCapabilityBinding second = binding("WORKFLOW", 93, "secondFlow");
|
||||
SkillCapabilityBindingServiceImpl publishService = spy(new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mcpAccessPermissionChecker,
|
||||
resourceAccessService, new ObjectMapper()));
|
||||
doReturn(List.of(first, second)).when(publishService).list(any(QueryWrapper.class));
|
||||
|
||||
List<Map<String, Object>> snapshots = publishService.buildPublishSnapshot(SKILL_ID);
|
||||
|
||||
assertEquals(2, snapshots.size());
|
||||
assertEquals("target", snapshots.get(0).get("targetName"));
|
||||
assertEquals("target", snapshots.get(1).get("targetName"));
|
||||
verify(targetAccessService, times(1)).requireUsableTarget(any(SkillCapabilityBinding.class), eq(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布快照必须移除凭据式目标元数据,并将非法逻辑引用降级为不可解析引用。
|
||||
*
|
||||
* @throws Exception JSON 序列化失败
|
||||
*/
|
||||
@Test
|
||||
public void publishSnapshotSanitizesPortableTargetMetadata() throws Exception {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", 94, "secureFlow");
|
||||
SkillCapabilityTarget unsafeTarget = target(List.of());
|
||||
unsafeTarget.setName("https://user:password@example.test/flow");
|
||||
unsafeTarget.setLogicalRef("workflow:../../private");
|
||||
unsafeTarget.setRevision("/Users/admin/.config/secret");
|
||||
when(targetAccessService.requireUsableTarget(binding, false)).thenReturn(unsafeTarget);
|
||||
SkillCapabilityBindingServiceImpl publishService = spy(new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mcpAccessPermissionChecker,
|
||||
resourceAccessService, new ObjectMapper()));
|
||||
doReturn(List.of(binding)).when(publishService).list(any(QueryWrapper.class));
|
||||
|
||||
Map<String, Object> snapshot = publishService.buildPublishSnapshot(SKILL_ID).get(0);
|
||||
String json = new ObjectMapper().writeValueAsString(snapshot);
|
||||
|
||||
assertNull(snapshot.get("targetName"));
|
||||
assertNull(snapshot.get("targetRevision"));
|
||||
assertEquals("unresolved:workflow", snapshot.get("targetLogicalRef"));
|
||||
assertFalse(json.contains("password"));
|
||||
assertFalse(json.contains("/Users/admin"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证单项配置 4 KiB 和 MCP 选择 200 项的计数限额。
|
||||
*/
|
||||
@Test
|
||||
public void capabilityConfigAndSelectedToolLimitsAreReported() {
|
||||
SkillCapabilityBinding oversizedConfig = binding("WORKFLOW", 1, "largeConfig");
|
||||
oversizedConfig.setOptionsJson(Map.of("timeoutMs", "x".repeat(5_000)));
|
||||
SkillValidationResult configResult = service.validateBindings(
|
||||
SKILL_ID, List.of(oversizedConfig), false);
|
||||
assertTrue(hasIssue(configResult, "CAPABILITY_CONFIG_TOO_LARGE"));
|
||||
|
||||
List<String> tools = IntStream.range(0, 201)
|
||||
.mapToObj(index -> String.format("tool%03d", index))
|
||||
.toList();
|
||||
SkillCapabilityBinding oversizedSelection = mcpBinding("many", tools);
|
||||
SkillValidationResult selectionResult = service.validateBindings(
|
||||
SKILL_ID, List.of(oversizedSelection), false);
|
||||
|
||||
assertTrue(hasIssue(selectionResult, "MCP_TOOL_SELECTION_LIMIT"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证保存、导入和发布共用的能力校验会精确报告 HITL 字符串中的凭据。
|
||||
*/
|
||||
@Test
|
||||
public void sensitiveHitlValueIsRejectedWithExactPath() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding(
|
||||
"WORKFLOW", "workflow:portable-flow", "portableFlow");
|
||||
binding.setHitlConfigJson(Map.of(
|
||||
"title", "人工确认",
|
||||
"prompt", "Authorization: Bearer actual-secret-value"));
|
||||
|
||||
SkillValidationResult result = service.validateImportBindings(List.of(binding));
|
||||
|
||||
assertFalse(result.isValid());
|
||||
SkillValidationIssue issue = result.getIssues().stream()
|
||||
.filter(item -> "SENSITIVE_VALUE_DETECTED".equals(item.getCode()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertEquals("capabilities[0].hitlConfigJson.prompt", issue.getPath());
|
||||
assertFalse(issue.getMessage().contains("actual-secret-value"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证保存、导入和发布共用校验覆盖运行时名称、目标引用和工具名。
|
||||
*/
|
||||
@Test
|
||||
public void sensitiveBindingStringsAreRejectedWithExactPaths() {
|
||||
SkillCapabilityBinding runtimeBinding = unresolvedBinding(
|
||||
"WORKFLOW", "workflow:portable-flow", "sk-proj-abcdefghijklmnopqrstuvwxyz123456");
|
||||
SkillCapabilityBinding targetBinding = unresolvedBinding(
|
||||
"WORKFLOW", "workflow:sk-proj-abcdefghijklmnopqrstuvwxyz123456", "portableFlow");
|
||||
SkillCapabilityBinding toolBinding = unresolvedBinding("MCP", "mcp:portable", "portableMcp");
|
||||
toolBinding.setEnabled(false);
|
||||
toolBinding.setSelectionMode("SELECTED");
|
||||
toolBinding.setSelectedToolNamesJson(List.of("sk-proj-abcdefghijklmnopqrstuvwxyz123456"));
|
||||
|
||||
SkillValidationResult result = service.validateImportBindings(
|
||||
List.of(runtimeBinding, targetBinding, toolBinding));
|
||||
|
||||
assertFalse(result.isValid());
|
||||
List<String> sensitivePaths = result.getIssues().stream()
|
||||
.filter(item -> "SENSITIVE_VALUE_DETECTED".equals(item.getCode()))
|
||||
.map(SkillValidationIssue::getPath)
|
||||
.toList();
|
||||
assertTrue(sensitivePaths.contains("capabilities[0].runtimeName"));
|
||||
assertTrue(sensitivePaths.contains("capabilities[1].targetLogicalRef"));
|
||||
assertTrue(sensitivePaths.contains("capabilities[2].selectedToolNamesJson[0]"));
|
||||
assertTrue(result.getIssues().stream().noneMatch(
|
||||
item -> item.getMessage().contains("sk-proj-")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证禁用能力也不能将凭据式工具名写入发布快照。
|
||||
*/
|
||||
@Test
|
||||
public void publishSnapshotRejectsCredentialInDisabledBinding() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding("MCP", "mcp:portable", "portableMcp");
|
||||
binding.setEnabled(false);
|
||||
binding.setSelectionMode("SELECTED");
|
||||
binding.setSelectedToolNamesJson(List.of("sk-proj-abcdefghijklmnopqrstuvwxyz123456"));
|
||||
SkillCapabilityBindingServiceImpl publishService = spy(service);
|
||||
doReturn(List.of(binding)).when(publishService).list(any(QueryWrapper.class));
|
||||
|
||||
BusinessException exception = assertThrows(
|
||||
BusinessException.class, () -> publishService.buildPublishSnapshot(SKILL_ID));
|
||||
|
||||
assertFalse(exception.getMessage().contains("sk-proj-"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证目标解析阶段返回的凭据式 MCP 工具名不能进入发布快照。
|
||||
*/
|
||||
@Test
|
||||
public void publishValidationRejectsCredentialFromResolvedMcpTools() {
|
||||
SkillCapabilityBinding binding = mcpBinding("portableMcp", List.of("alpha"));
|
||||
when(targetAccessService.requireUsableTarget(binding, true)).thenReturn(
|
||||
target(List.of("alpha", "sk-proj-abcdefghijklmnopqrstuvwxyz123456")));
|
||||
|
||||
SkillValidationResult result = service.validateBindings(SKILL_ID, List.of(binding), true);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
SkillValidationIssue issue = result.getIssues().stream()
|
||||
.filter(item -> "SENSITIVE_VALUE_DETECTED".equals(item.getCode()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertEquals("capabilities[0].resolvedToolNames[1]", issue.getPath());
|
||||
assertFalse(issue.getMessage().contains("sk-proj-"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证列表和详情读取边界会移除历史数据库中的凭据式展示值。
|
||||
*/
|
||||
@Test
|
||||
public void listBindingsRedactsLegacyCredentialValues() {
|
||||
SkillCapabilityBinding binding = binding(
|
||||
"WORKFLOW", 95, "sk-proj-abcdefghijklmnopqrstuvwxyz123456");
|
||||
binding.setSelectedToolNamesJson(List.of("sk-proj-abcdefghijklmnopqrstuvwxyz123456"));
|
||||
binding.setResolvedToolNames(List.of("sk-proj-abcdefghijklmnopqrstuvwxyz123456"));
|
||||
binding.setHitlConfigJson(Map.of("prompt", "Bearer actual-secret-value"));
|
||||
binding.setOptionsJson(Map.of("timeoutMs", "token=actual-secret-value"));
|
||||
SkillCapabilityBindingServiceImpl listService = spy(service);
|
||||
doReturn(List.of(binding)).when(listService).list(any(QueryWrapper.class));
|
||||
|
||||
SkillCapabilityBinding result = listService.listBindings(SKILL_ID).get(0);
|
||||
|
||||
assertNull(result.getRuntimeName());
|
||||
assertTrue(result.getSelectedToolNamesJson().isEmpty());
|
||||
assertTrue(result.getResolvedToolNames().isEmpty());
|
||||
assertTrue(result.getHitlConfigJson().isEmpty());
|
||||
assertTrue(result.getOptionsJson().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 replaceBindings 在进入持久化前拒绝超过 200 项的能力列表。
|
||||
*/
|
||||
@Test
|
||||
public void replaceRejectsMoreThanTwoHundredBindings() {
|
||||
List<SkillCapabilityBinding> bindings = new ArrayList<>();
|
||||
for (int index = 0; index < 201; index++) {
|
||||
bindings.add(binding("WORKFLOW", index + 1, "flow" + index));
|
||||
}
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.replaceBindings(SKILL_ID, bindings));
|
||||
verify(resourceAccessService).assertAccess(
|
||||
CategoryResourceType.SKILL, skill, ResourceAction.MANAGE, "无权限管理 Skill 能力绑定");
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证传入待保存 bindings 的校验必须执行 MANAGE 权限,不允许降级为 READ。
|
||||
*/
|
||||
@Test
|
||||
public void validatingClientBindingsRequiresManagePermission() {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", 1, "managedFlow");
|
||||
|
||||
service.validateBindings(SKILL_ID, List.of(binding), false);
|
||||
|
||||
verify(resourceAccessService).assertAccess(
|
||||
eq(CategoryResourceType.SKILL), same(skill), eq(ResourceAction.MANAGE), anyString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证只有 READ 权限的用户读取绑定时看不到当前环境目标 ID 和无权限目标残留名称。
|
||||
*/
|
||||
@Test
|
||||
public void visibleBindingsRedactTargetIdentityWithoutManagePermission() {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", 81, "readOnlyFlow");
|
||||
binding.setTargetLogicalRef("workflow:private-flow");
|
||||
binding.setTargetName("stale-private-name");
|
||||
binding.setSelectedToolNamesJson(List.of("stale-private-selected-tool"));
|
||||
binding.setResolvedToolNames(List.of("stale-private-tool"));
|
||||
SkillCapabilityBindingServiceImpl viewService = spy(new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mcpAccessPermissionChecker,
|
||||
resourceAccessService, new ObjectMapper()));
|
||||
doReturn(List.of(binding)).when(viewService).list(any(QueryWrapper.class));
|
||||
when(resourceAccessService.canAccess(
|
||||
CategoryResourceType.SKILL, skill, ResourceAction.MANAGE)).thenReturn(false);
|
||||
when(targetAccessService.requireUsableTarget(binding, false))
|
||||
.thenThrow(new BusinessException(403, 403, "无权限使用目标"));
|
||||
|
||||
List<SkillCapabilityBinding> result = viewService.listVisibleBindings(SKILL_ID);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertNull(result.get(0).getTargetId());
|
||||
assertNull(result.get(0).getTargetLogicalRef());
|
||||
assertNull(result.get(0).getTargetName());
|
||||
assertTrue(result.get(0).getSelectedToolNamesJson().isEmpty());
|
||||
assertTrue(result.get(0).getResolvedToolNames().isEmpty());
|
||||
assertEquals("NO_PERMISSION", result.get(0).getTargetStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证拥有 MANAGE 权限的用户读取绑定时仍可获得目标 ID 用于编辑。
|
||||
*/
|
||||
@Test
|
||||
public void visibleBindingsKeepTargetIdWithManagePermission() {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", 82, "managedFlow");
|
||||
SkillCapabilityBindingServiceImpl viewService = spy(new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mcpAccessPermissionChecker,
|
||||
resourceAccessService, new ObjectMapper()));
|
||||
doReturn(List.of(binding)).when(viewService).list(any(QueryWrapper.class));
|
||||
when(resourceAccessService.canAccess(
|
||||
CategoryResourceType.SKILL, skill, ResourceAction.MANAGE)).thenReturn(true);
|
||||
|
||||
List<SkillCapabilityBinding> result = viewService.listVisibleBindings(SKILL_ID);
|
||||
|
||||
assertEquals(BigInteger.valueOf(82), result.get(0).getTargetId());
|
||||
assertEquals("AVAILABLE", result.get(0).getTargetStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 Skill MANAGE 权限不能替代 MCP 查询权限,目标标识和工具元数据仍需脱敏。
|
||||
*/
|
||||
@Test
|
||||
public void visibleBindingsRedactMcpTargetWithoutTargetPermissionEvenWhenSkillManageable() {
|
||||
SkillCapabilityBinding binding = mcpBinding("privateMcp", List.of("private_tool"));
|
||||
binding.setTargetLogicalRef("mcp:private-server");
|
||||
binding.setTargetName("private-server");
|
||||
binding.setResolvedToolNames(List.of("private_tool"));
|
||||
SkillCapabilityBindingServiceImpl viewService = spy(new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mcpAccessPermissionChecker,
|
||||
resourceAccessService, new ObjectMapper()));
|
||||
doReturn(List.of(binding)).when(viewService).list(any(QueryWrapper.class));
|
||||
when(resourceAccessService.canAccess(
|
||||
CategoryResourceType.SKILL, skill, ResourceAction.MANAGE)).thenReturn(true);
|
||||
when(targetAccessService.requireUsableTarget(binding, false))
|
||||
.thenThrow(new BusinessException(403, 403, "无权限查询或使用 MCP"));
|
||||
|
||||
List<SkillCapabilityBinding> result = viewService.listVisibleBindings(SKILL_ID);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("NO_PERMISSION", result.get(0).getTargetStatus());
|
||||
assertNull(result.get(0).getTargetId());
|
||||
assertNull(result.get(0).getTargetLogicalRef());
|
||||
assertNull(result.get(0).getTargetName());
|
||||
assertTrue(result.get(0).getSelectedToolNamesJson().isEmpty());
|
||||
assertTrue(result.get(0).getResolvedToolNames().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建基础能力绑定。
|
||||
*
|
||||
* @param type 能力类型
|
||||
* @param targetId 目标 ID
|
||||
* @param runtimeName 运行时名称
|
||||
* @return 能力绑定
|
||||
*/
|
||||
private SkillCapabilityBinding binding(String type, long targetId, String runtimeName) {
|
||||
SkillCapabilityBinding binding = new SkillCapabilityBinding();
|
||||
binding.setCapabilityType(type);
|
||||
binding.setTargetId(BigInteger.valueOf(targetId));
|
||||
binding.setRuntimeName(runtimeName);
|
||||
binding.setEnabled(true);
|
||||
binding.setHitlConfigJson(new LinkedHashMap<>());
|
||||
binding.setOptionsJson(new LinkedHashMap<>());
|
||||
return binding;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 MCP SELECTED 能力绑定。
|
||||
*
|
||||
* @param runtimeName 命名空间
|
||||
* @param selectedTools 已选工具
|
||||
* @return MCP 绑定
|
||||
*/
|
||||
private SkillCapabilityBinding mcpBinding(String runtimeName, List<String> selectedTools) {
|
||||
SkillCapabilityBinding binding = binding("MCP", 10, runtimeName);
|
||||
binding.setSelectionMode("SELECTED");
|
||||
binding.setSelectedToolNamesJson(selectedTools);
|
||||
return binding;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建等待导入映射的能力绑定。
|
||||
*
|
||||
* @param type 能力类型
|
||||
* @param logicalRef 可移植逻辑引用
|
||||
* @param runtimeName 运行时名称
|
||||
* @return 未映射能力绑定
|
||||
*/
|
||||
private SkillCapabilityBinding unresolvedBinding(String type, String logicalRef, String runtimeName) {
|
||||
SkillCapabilityBinding binding = new SkillCapabilityBinding();
|
||||
binding.setCapabilityType(type);
|
||||
binding.setTargetLogicalRef(logicalRef);
|
||||
binding.setRuntimeName(runtimeName);
|
||||
binding.setEnabled(true);
|
||||
binding.setHitlConfigJson(new LinkedHashMap<>());
|
||||
binding.setOptionsJson(new LinkedHashMap<>());
|
||||
return binding;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建可用能力目标。
|
||||
*
|
||||
* @param toolNames MCP 工具名
|
||||
* @return 目标摘要
|
||||
*/
|
||||
private SkillCapabilityTarget target(List<String> toolNames) {
|
||||
SkillCapabilityTarget target = new SkillCapabilityTarget();
|
||||
target.setName("target");
|
||||
target.setLogicalRef("target://demo");
|
||||
target.setRevision("r1");
|
||||
target.setStatus("AVAILABLE");
|
||||
target.setToolNames(toolNames);
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断校验结果是否包含指定问题码。
|
||||
*
|
||||
* @param result 校验结果
|
||||
* @param code 问题码
|
||||
* @return 包含时为 true
|
||||
*/
|
||||
private boolean hasIssue(SkillValidationResult result, String code) {
|
||||
return result.getIssues().stream().anyMatch(item -> code.equals(item.getCode()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定问题码的首个问题。
|
||||
*
|
||||
* @param result 校验结果
|
||||
* @param code 问题码
|
||||
* @return 校验问题
|
||||
*/
|
||||
private SkillValidationIssue issue(SkillValidationResult result, String code) {
|
||||
return result.getIssues().stream()
|
||||
.filter(item -> code.equals(item.getCode()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import tech.easyflow.ai.permission.McpAccessPermissionChecker;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 能力绑定畸形客户端输入的结构化诊断测试。
|
||||
*/
|
||||
public class SkillCapabilityMalformedInputTest {
|
||||
|
||||
private static final BigInteger SKILL_ID = BigInteger.valueOf(101);
|
||||
|
||||
private SkillCapabilityBindingServiceImpl service;
|
||||
|
||||
/**
|
||||
* 初始化具有当前租户上下文的被测服务。
|
||||
*/
|
||||
@Before
|
||||
public void setUp() {
|
||||
SkillMapper skillMapper = mock(SkillMapper.class);
|
||||
Skill skill = new Skill();
|
||||
skill.setId(SKILL_ID);
|
||||
skill.setTenantId(BigInteger.ONE);
|
||||
when(skillMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(skill);
|
||||
SkillCapabilityTargetAccessService targetAccessService = mock(SkillCapabilityTargetAccessService.class);
|
||||
SkillCapabilityTarget target = new SkillCapabilityTarget();
|
||||
target.setName("target");
|
||||
target.setLogicalRef("target:demo");
|
||||
target.setStatus("AVAILABLE");
|
||||
target.setToolNames(List.of("search"));
|
||||
when(targetAccessService.requireUsableTarget(any(SkillCapabilityBinding.class), anyBoolean()))
|
||||
.thenReturn(target);
|
||||
service = new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mock(McpAccessPermissionChecker.class),
|
||||
mock(ResourceAccessService.class), new ObjectMapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 MCP 工具数组中的 null 返回结构化错误,不触发排序空指针。
|
||||
*/
|
||||
@Test
|
||||
public void nullMcpToolNameShouldReturnStructuredIssue() {
|
||||
SkillCapabilityBinding binding = binding("MCP");
|
||||
binding.setSelectionMode("SELECTED");
|
||||
List<String> tools = new ArrayList<>();
|
||||
tools.add("search");
|
||||
tools.add(null);
|
||||
binding.setSelectedToolNamesJson(tools);
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> "MCP_TOOL_NAME_INVALID".equals(issue.getCode())));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证非法执行模式进入结构化问题列表,不以枚举异常中断校验。
|
||||
*/
|
||||
@Test
|
||||
public void invalidExecutionModeShouldReturnStructuredIssue() {
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW");
|
||||
binding.setExecutionMode("INVALID_MODE");
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> issue.getPath() != null && issue.getPath().endsWith("executionMode")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证非法 MCP 选择模式进入结构化问题列表。
|
||||
*/
|
||||
@Test
|
||||
public void invalidSelectionModeShouldReturnStructuredIssue() {
|
||||
SkillCapabilityBinding binding = binding("MCP");
|
||||
binding.setSelectionMode("INVALID_MODE");
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> issue.getPath() != null && issue.getPath().endsWith("selectionMode")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证禁用且未映射的 MCP 仍执行选择模式静态校验,不能借 targetId 为空绕过。
|
||||
*/
|
||||
@Test
|
||||
public void disabledUnresolvedMcpShouldStillValidateSelectionMode() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding("MCP", "mcp:missing");
|
||||
binding.setSelectionMode("INVALID_MODE");
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> "MCP_SELECTION_MODE_INVALID".equals(issue.getCode())));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证禁用且未映射的 MCP 仍拒绝非法工具名,避免恶意值持久化并再次导出。
|
||||
*/
|
||||
@Test
|
||||
public void disabledUnresolvedMcpShouldStillValidateToolNames() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding("MCP", "mcp:missing");
|
||||
binding.setSelectionMode("SELECTED");
|
||||
binding.setSelectedToolNamesJson(List.of("invalid tool name"));
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> "MCP_TOOL_NAME_INVALID".equals(issue.getCode())));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证禁用且未映射的非 MCP 能力仍执行 executionMode 静态校验。
|
||||
*/
|
||||
@Test
|
||||
public void disabledUnresolvedWorkflowShouldStillValidateExecutionMode() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding("WORKFLOW", "workflow:missing");
|
||||
binding.setExecutionMode("INVALID_MODE");
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> "EXECUTION_MODE_INVALID".equals(issue.getCode())));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证逻辑引用 scheme 必须与能力类型一致。
|
||||
*/
|
||||
@Test
|
||||
public void unresolvedLogicalRefShouldMatchCapabilityType() {
|
||||
SkillCapabilityBinding binding = unresolvedBinding("MCP", "workflow:wrong-type");
|
||||
binding.setSelectionMode("ALL");
|
||||
|
||||
SkillValidationResult result = validate(binding);
|
||||
|
||||
assertFalse(result.isValid());
|
||||
assertTrue(result.getIssues().stream()
|
||||
.anyMatch(issue -> "TARGET_LOGICAL_REF_INVALID".equals(issue.getCode())));
|
||||
}
|
||||
|
||||
private SkillValidationResult validate(SkillCapabilityBinding binding) {
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account());
|
||||
return service.validateBindings(SKILL_ID, List.of(binding), false);
|
||||
}
|
||||
}
|
||||
|
||||
private SkillCapabilityBinding binding(String type) {
|
||||
SkillCapabilityBinding binding = new SkillCapabilityBinding();
|
||||
binding.setCapabilityType(type);
|
||||
binding.setTargetId(BigInteger.valueOf(9));
|
||||
binding.setRuntimeName("demoTool");
|
||||
binding.setEnabled(true);
|
||||
binding.setHitlConfigJson(Map.of());
|
||||
binding.setOptionsJson(Map.of());
|
||||
return binding;
|
||||
}
|
||||
|
||||
private SkillCapabilityBinding unresolvedBinding(String type, String logicalRef) {
|
||||
SkillCapabilityBinding binding = binding(type);
|
||||
binding.setTargetId(null);
|
||||
binding.setTargetLogicalRef(logicalRef);
|
||||
binding.setEnabled(false);
|
||||
return binding;
|
||||
}
|
||||
|
||||
private LoginAccount account() {
|
||||
LoginAccount account = new LoginAccount();
|
||||
account.setId(BigInteger.valueOf(7));
|
||||
account.setTenantId(BigInteger.ONE);
|
||||
return account;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package tech.easyflow.skill.capability;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import tech.easyflow.ai.entity.Mcp;
|
||||
import tech.easyflow.ai.entity.Plugin;
|
||||
import tech.easyflow.ai.entity.PluginItem;
|
||||
import tech.easyflow.ai.permission.McpAccessPermissionChecker;
|
||||
import tech.easyflow.ai.permission.WorkflowVisibilityQueryHelper;
|
||||
import tech.easyflow.ai.service.McpService;
|
||||
import tech.easyflow.ai.service.PluginItemService;
|
||||
import tech.easyflow.ai.service.PluginService;
|
||||
import tech.easyflow.ai.service.PluginVisibilityService;
|
||||
import tech.easyflow.ai.service.WorkflowService;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillCapabilityBinding;
|
||||
import tech.easyflow.skill.enums.SkillCapabilityType;
|
||||
import tech.easyflow.skill.mapper.SkillCapabilityBindingMapper;
|
||||
import tech.easyflow.skill.mapper.SkillMapper;
|
||||
import tech.easyflow.skill.validation.SkillValidationIssue;
|
||||
import tech.easyflow.skill.validation.SkillValidationResult;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
import tech.easyflow.system.service.CategoryPermissionService;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Skill 能力绑定的租户边界和严格校验回归测试。
|
||||
*/
|
||||
public class SkillCapabilityTenantAndValidationTest {
|
||||
|
||||
/**
|
||||
* 验证当前用户即使拥有全局插件可见范围,也不能绑定其他租户的插件工具项。
|
||||
*/
|
||||
@Test
|
||||
public void pluginItemShouldNeverCrossTenantBoundary() {
|
||||
PluginItemService pluginItemService = mock(PluginItemService.class);
|
||||
PluginService pluginService = mock(PluginService.class);
|
||||
PluginVisibilityService pluginVisibilityService = mock(PluginVisibilityService.class);
|
||||
PluginItem item = new PluginItem();
|
||||
item.setId(BigInteger.valueOf(11));
|
||||
item.setPluginId(BigInteger.valueOf(22));
|
||||
item.setName("tool");
|
||||
item.setStatus(1);
|
||||
item.setServiceStatus(1);
|
||||
Plugin plugin = new Plugin();
|
||||
plugin.setId(BigInteger.valueOf(22));
|
||||
plugin.setTenantId(2L);
|
||||
plugin.setCreatedBy(8L);
|
||||
plugin.setName("other-tenant-plugin");
|
||||
when(pluginItemService.getOne(any(QueryWrapper.class))).thenReturn(item);
|
||||
// 即使底层查询实现错误地返回了跨租户对象,服务层防御检查仍必须拒绝。
|
||||
when(pluginService.getOne(any(QueryWrapper.class))).thenReturn(plugin);
|
||||
when(pluginVisibilityService.canAccessPlugin(plugin.getCreatedBy(), plugin.getId())).thenReturn(true);
|
||||
when(pluginService.preparePluginForCurrentUser(plugin)).thenReturn(plugin);
|
||||
SkillCapabilityTargetAccessServiceImpl service = new SkillCapabilityTargetAccessServiceImpl(
|
||||
mock(WorkflowService.class), pluginItemService, pluginService, pluginVisibilityService,
|
||||
mock(McpService.class), mock(McpAccessPermissionChecker.class), mock(ResourceAccessService.class),
|
||||
mock(WorkflowVisibilityQueryHelper.class), mock(CategoryPermissionService.class));
|
||||
SkillCapabilityBinding binding = binding("PLUGIN_ITEM", item.getId(), "tool");
|
||||
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account(7, 1));
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.requireUsableTarget(binding, false));
|
||||
assertEquals(403, exception.getHttpStatus());
|
||||
}
|
||||
verify(pluginService, never()).preparePluginForCurrentUser(plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证包含凭据式 URL 的 MCP 标题不会被复制进跨环境逻辑引用。
|
||||
*/
|
||||
@Test
|
||||
public void unsafeMcpTitleShouldBecomeUnresolvedLogicalRef() {
|
||||
McpService mcpService = mock(McpService.class);
|
||||
Mcp mcp = new Mcp();
|
||||
mcp.setId(BigInteger.valueOf(31));
|
||||
mcp.setTenantId(BigInteger.ONE);
|
||||
mcp.setStatus(true);
|
||||
mcp.setTitle("https://user:secret@example.test/mcp?token=must-not-enter");
|
||||
when(mcpService.getOne(any(QueryWrapper.class))).thenReturn(mcp);
|
||||
McpAccessPermissionChecker mcpPermissionChecker = mock(McpAccessPermissionChecker.class);
|
||||
SkillCapabilityTargetAccessServiceImpl service = new SkillCapabilityTargetAccessServiceImpl(
|
||||
mock(WorkflowService.class), mock(PluginItemService.class), mock(PluginService.class),
|
||||
mock(PluginVisibilityService.class), mcpService, mcpPermissionChecker, mock(ResourceAccessService.class),
|
||||
mock(WorkflowVisibilityQueryHelper.class), mock(CategoryPermissionService.class));
|
||||
SkillCapabilityBinding binding = binding("MCP", mcp.getId(), "mcpTool");
|
||||
|
||||
SkillCapabilityTarget target;
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account(7, 1));
|
||||
target = service.requireUsableTarget(binding, false);
|
||||
}
|
||||
|
||||
assertEquals("unresolved:mcp", target.getLogicalRef());
|
||||
assertFalse(target.getLogicalRef().contains("secret"));
|
||||
assertFalse(target.getLogicalRef().contains("token"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 MCP 候选、工具解析、目标绑定和增强导入映射都在访问数据前校验 MCP 模块权限。
|
||||
*/
|
||||
@Test
|
||||
public void mcpOperationsRejectCallerWithoutMcpQueryPermissionBeforeDataAccess() {
|
||||
McpService mcpService = mock(McpService.class);
|
||||
McpAccessPermissionChecker permissionChecker = mock(McpAccessPermissionChecker.class);
|
||||
doThrow(new BusinessException(403, 403, "无权限查询或使用 MCP"))
|
||||
.when(permissionChecker).assertCanUseMcp();
|
||||
SkillCapabilityTargetAccessServiceImpl service = new SkillCapabilityTargetAccessServiceImpl(
|
||||
mock(WorkflowService.class), mock(PluginItemService.class), mock(PluginService.class),
|
||||
mock(PluginVisibilityService.class), mcpService, permissionChecker,
|
||||
mock(ResourceAccessService.class), mock(WorkflowVisibilityQueryHelper.class),
|
||||
mock(CategoryPermissionService.class));
|
||||
SkillCapabilityBinding binding = binding("MCP", BigInteger.valueOf(31), "mcpTool");
|
||||
|
||||
BusinessException candidates = assertThrows(BusinessException.class,
|
||||
() -> service.listCandidates(SkillCapabilityType.MCP, null));
|
||||
BusinessException tools = assertThrows(BusinessException.class,
|
||||
() -> service.getMcpTools(BigInteger.valueOf(31)));
|
||||
BusinessException bindingAccess = assertThrows(BusinessException.class,
|
||||
() -> service.requireUsableTarget(binding, false));
|
||||
BusinessException importMapping = assertThrows(BusinessException.class,
|
||||
() -> service.resolveLogicalRef(SkillCapabilityType.MCP, "mcp:demo"));
|
||||
|
||||
assertEquals(403, candidates.getHttpStatus());
|
||||
assertEquals(403, tools.getHttpStatus());
|
||||
assertEquals(403, bindingAccess.getHttpStatus());
|
||||
assertEquals(403, importMapping.getHttpStatus());
|
||||
verify(permissionChecker, times(4)).assertCanUseMcp();
|
||||
verifyNoInteractions(mcpService);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证省略 HITL 和 options 时按空配置处理,不产生不安全配置误报。
|
||||
*/
|
||||
@Test
|
||||
public void nullSafeConfigsShouldBeNormalizedToEmptyMaps() {
|
||||
SkillMapper skillMapper = mock(SkillMapper.class);
|
||||
SkillCapabilityTargetAccessService targetAccessService = mock(SkillCapabilityTargetAccessService.class);
|
||||
Skill skill = skill(101, 1);
|
||||
when(skillMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(skill);
|
||||
when(targetAccessService.requireUsableTarget(any(SkillCapabilityBinding.class), anyBoolean()))
|
||||
.thenReturn(target());
|
||||
SkillCapabilityBindingServiceImpl service = new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mock(McpAccessPermissionChecker.class),
|
||||
mock(ResourceAccessService.class), new ObjectMapper());
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", BigInteger.valueOf(9), "workflowTool");
|
||||
|
||||
SkillValidationResult result;
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account(7, 1));
|
||||
result = service.validateBindings(skill.getId(), List.of(binding), false);
|
||||
}
|
||||
|
||||
assertTrue(result.getIssues().toString(), result.isValid());
|
||||
assertTrue(binding.getHitlConfigJson().isEmpty());
|
||||
assertTrue(binding.getOptionsJson().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证目标 USE 权限失败时,即使绑定被禁用也不能作为 warning 绕过保存校验。
|
||||
*/
|
||||
@Test
|
||||
public void disabledBindingShouldNotBypassTargetPermission() {
|
||||
SkillMapper skillMapper = mock(SkillMapper.class);
|
||||
SkillCapabilityTargetAccessService targetAccessService = mock(SkillCapabilityTargetAccessService.class);
|
||||
Skill skill = skill(101, 1);
|
||||
when(skillMapper.selectOneByQuery(any(QueryWrapper.class))).thenReturn(skill);
|
||||
when(targetAccessService.requireUsableTarget(any(SkillCapabilityBinding.class), anyBoolean()))
|
||||
.thenThrow(new BusinessException(403, 403, "无权限使用目标"));
|
||||
SkillCapabilityBindingServiceImpl service = new SkillCapabilityBindingServiceImpl(
|
||||
skillMapper, targetAccessService, mock(McpAccessPermissionChecker.class),
|
||||
mock(ResourceAccessService.class), new ObjectMapper());
|
||||
SkillCapabilityBinding binding = binding("WORKFLOW", BigInteger.valueOf(9), "workflowTool");
|
||||
binding.setEnabled(false);
|
||||
|
||||
SkillValidationResult result;
|
||||
try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account(7, 1));
|
||||
result = service.validateBindings(skill.getId(), List.of(binding), false);
|
||||
}
|
||||
|
||||
assertFalse(result.isValid());
|
||||
SkillValidationIssue issue = result.getIssues().stream()
|
||||
.filter(item -> "TARGET_NO_PERMISSION".equals(item.getCode()))
|
||||
.findFirst().orElseThrow();
|
||||
assertEquals("ERROR", issue.getSeverity());
|
||||
}
|
||||
|
||||
private SkillCapabilityBinding binding(String type, BigInteger targetId, String runtimeName) {
|
||||
SkillCapabilityBinding binding = new SkillCapabilityBinding();
|
||||
binding.setCapabilityType(type);
|
||||
binding.setTargetId(targetId);
|
||||
binding.setRuntimeName(runtimeName);
|
||||
binding.setEnabled(true);
|
||||
return binding;
|
||||
}
|
||||
|
||||
private Skill skill(long id, long tenantId) {
|
||||
Skill skill = new Skill();
|
||||
skill.setId(BigInteger.valueOf(id));
|
||||
skill.setTenantId(BigInteger.valueOf(tenantId));
|
||||
return skill;
|
||||
}
|
||||
|
||||
private SkillCapabilityTarget target() {
|
||||
SkillCapabilityTarget target = new SkillCapabilityTarget();
|
||||
target.setName("target");
|
||||
target.setLogicalRef("workflow:target");
|
||||
target.setStatus("AVAILABLE");
|
||||
return target;
|
||||
}
|
||||
|
||||
private LoginAccount account(long accountId, long tenantId) {
|
||||
LoginAccount account = new LoginAccount();
|
||||
account.setId(BigInteger.valueOf(accountId));
|
||||
account.setTenantId(BigInteger.valueOf(tenantId));
|
||||
return account;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package tech.easyflow.skill.file;
|
||||
|
||||
import com.mybatisflex.core.query.QueryWrapper;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import tech.easyflow.common.entity.LoginAccount;
|
||||
import tech.easyflow.common.satoken.util.SaTokenUtil;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
import tech.easyflow.skill.entity.Skill;
|
||||
import tech.easyflow.skill.entity.SkillResource;
|
||||
import tech.easyflow.skill.service.SkillResourceService;
|
||||
import tech.easyflow.skill.service.SkillService;
|
||||
import tech.easyflow.skill.store.DBSkillContentStore;
|
||||
import tech.easyflow.system.service.ResourceAccessService;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link SkillFileServiceImpl} 上传事务入口与失败回滚契约测试。
|
||||
*/
|
||||
public class SkillFileServiceImplTransactionTest {
|
||||
|
||||
private static final BigInteger SKILL_ID = BigInteger.valueOf(101);
|
||||
private static final String NEW_CONTENT_REF = "sha256:" + "a".repeat(64);
|
||||
|
||||
private SkillService skillService;
|
||||
private SkillResourceService skillResourceService;
|
||||
private DBSkillContentStore contentStore;
|
||||
private SkillFileServiceImpl service;
|
||||
private MockedStatic<SaTokenUtil> saToken;
|
||||
|
||||
/**
|
||||
* 初始化上传服务。
|
||||
*/
|
||||
@Before
|
||||
public void setUp() {
|
||||
skillService = mock(SkillService.class);
|
||||
skillResourceService = mock(SkillResourceService.class);
|
||||
contentStore = mock(DBSkillContentStore.class);
|
||||
service = new SkillFileServiceImpl(
|
||||
skillService,
|
||||
skillResourceService,
|
||||
contentStore,
|
||||
mock(ResourceAccessService.class));
|
||||
Skill skill = new Skill();
|
||||
skill.setId(SKILL_ID);
|
||||
skill.setTenantId(BigInteger.ONE);
|
||||
LoginAccount account = new LoginAccount();
|
||||
account.setId(BigInteger.valueOf(7));
|
||||
account.setTenantId(BigInteger.ONE);
|
||||
saToken = mockStatic(SaTokenUtil.class);
|
||||
saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
|
||||
when(skillService.getOne(any(QueryWrapper.class))).thenReturn(skill);
|
||||
when(skillResourceService.list(any(QueryWrapper.class))).thenReturn(List.of());
|
||||
when(skillResourceService.listDescriptors(any(BigInteger.class), any(BigInteger.class)))
|
||||
.thenReturn(List.of());
|
||||
when(contentStore.put(any(MultipartFile.class), anyString())).thenReturn(NEW_CONTENT_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放静态登录态 Mock。
|
||||
*/
|
||||
@After
|
||||
public void tearDown() {
|
||||
saToken.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证资源持久化失败时不手工 release 新引用,引用计数应由同一外层事务回滚。
|
||||
*/
|
||||
@Test
|
||||
public void failedUploadDoesNotDoubleReleaseNewReference() {
|
||||
when(skillResourceService.save(any(SkillResource.class))).thenReturn(false);
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.uploadAsset(
|
||||
SKILL_ID, "assets/file.bin", multipart("file.bin", "content")));
|
||||
|
||||
verify(contentStore).put(any(MultipartFile.class), anyString());
|
||||
verify(contentStore, never()).release(NEW_CONTENT_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 uploadAsset 自身成为事务代理入口,不依赖类内调用 uploadResource 的注解。
|
||||
*
|
||||
* @throws Exception 反射读取方法失败
|
||||
*/
|
||||
@Test
|
||||
public void uploadAssetIsTransactionalEntry() throws Exception {
|
||||
Method method = SkillFileServiceImpl.class.getMethod(
|
||||
"uploadAsset", BigInteger.class, String.class, MultipartFile.class);
|
||||
|
||||
assertTrue(method.isAnnotationPresent(Transactional.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证空 Skill 的文件树仍稳定返回三个标准目录。
|
||||
*/
|
||||
@Test
|
||||
public void treeAlwaysContainsStandardDirectories() {
|
||||
List<SkillFileNode> roots = service.tree(SKILL_ID);
|
||||
|
||||
assertEquals(List.of("SKILL.md", "references", "scripts", "assets"),
|
||||
roots.stream().map(SkillFileNode::getPath).toList());
|
||||
assertEquals(List.of("SKILL", "DIRECTORY", "DIRECTORY", "DIRECTORY"),
|
||||
roots.stream().map(SkillFileNode::getType).toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证脚本上传按严格 UTF-8 文本保存,不进入二进制内容仓库。
|
||||
*/
|
||||
@Test
|
||||
public void scriptUploadStoresCanonicalTextRepresentation() {
|
||||
AtomicReference<SkillResource> savedResource = new AtomicReference<>();
|
||||
when(skillResourceService.list(any(QueryWrapper.class)))
|
||||
.thenAnswer(invocation -> savedResource.get() == null
|
||||
? List.of() : List.of(savedResource.get()));
|
||||
when(skillResourceService.save(any(SkillResource.class))).thenAnswer(invocation -> {
|
||||
SkillResource resource = invocation.getArgument(0);
|
||||
resource.setId(BigInteger.valueOf(9));
|
||||
savedResource.set(resource);
|
||||
return true;
|
||||
});
|
||||
|
||||
SkillFileContent result = service.uploadResource(
|
||||
SKILL_ID, "scripts/tool.py", multipart("tool.py", "print('ok')\n"));
|
||||
|
||||
SkillResource resource = savedResource.get();
|
||||
assertTrue(resource.getIsText());
|
||||
assertEquals("SCRIPT", resource.getKind());
|
||||
assertEquals("PYTHON", resource.getLanguage());
|
||||
assertEquals("print('ok')\n", resource.getTextContent());
|
||||
assertNull(resource.getContentRef());
|
||||
assertTrue(result.getIsText());
|
||||
verify(contentStore, never()).put(any(MultipartFile.class), anyString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证脚本上传拒绝非法 UTF-8,且失败前不会写入资源或二进制仓库。
|
||||
*/
|
||||
@Test
|
||||
public void scriptUploadRejectsMalformedUtf8() {
|
||||
MultipartFile file = new TestMultipartFile("bad.py", new byte[]{(byte) 0xC3, (byte) 0x28});
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.uploadResource(SKILL_ID, "scripts/bad.py", file));
|
||||
|
||||
assertTrue(exception.getMessage().contains("严格 UTF-8"));
|
||||
verify(skillResourceService, never()).save(any(SkillResource.class));
|
||||
verify(contentStore, never()).put(any(MultipartFile.class), anyString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证二进制资源重命名到 scripts 后转为文本,并释放原内容引用。
|
||||
*/
|
||||
@Test
|
||||
public void binaryRenameToScriptConvertsAndReleasesContent() {
|
||||
String oldRef = "sha256:" + "b".repeat(64);
|
||||
String sourceHash = "b".repeat(64);
|
||||
SkillResource resource = resource(
|
||||
"assets/tool.bin", false, null, oldRef, sourceHash, 12L);
|
||||
when(skillResourceService.list(any(QueryWrapper.class)))
|
||||
.thenReturn(List.of(), List.of(resource), List.of(resource), List.of(resource));
|
||||
when(skillResourceService.update(eq(resource), any(QueryWrapper.class))).thenReturn(true);
|
||||
when(contentStore.open(oldRef)).thenReturn(
|
||||
new ByteArrayInputStream("print('ok')\n".getBytes(StandardCharsets.UTF_8)));
|
||||
SkillFileRenameRequest request = renameRequest(
|
||||
"assets/tool.bin", "scripts/tool.py", sourceHash);
|
||||
|
||||
SkillFileContent result = service.renameFile(request);
|
||||
|
||||
assertTrue(resource.getIsText());
|
||||
assertEquals("scripts/tool.py", resource.getNormalizedPath());
|
||||
assertEquals("SCRIPT", resource.getKind());
|
||||
assertEquals("PYTHON", resource.getLanguage());
|
||||
assertNull(resource.getContentRef());
|
||||
assertEquals("print('ok')\n", resource.getTextContent());
|
||||
assertTrue(result.getIsText());
|
||||
verify(contentStore).release(oldRef);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证文本资源重命名到 assets 后转为二进制内容引用。
|
||||
*/
|
||||
@Test
|
||||
public void textRenameToAssetConvertsToBinaryRepresentation() {
|
||||
String sourceHash = "c".repeat(64);
|
||||
SkillResource resource = resource(
|
||||
"references/guide.md", true, "# Guide\n", null, sourceHash, 8L);
|
||||
when(skillResourceService.list(any(QueryWrapper.class)))
|
||||
.thenReturn(List.of(), List.of(resource), List.of(resource), List.of(resource));
|
||||
when(skillResourceService.update(eq(resource), any(QueryWrapper.class))).thenReturn(true);
|
||||
when(contentStore.put(any(byte[].class))).thenReturn(NEW_CONTENT_REF);
|
||||
SkillFileRenameRequest request = renameRequest(
|
||||
"references/guide.md", "assets/guide.md", sourceHash);
|
||||
|
||||
SkillFileContent result = service.renameFile(request);
|
||||
|
||||
assertFalse(resource.getIsText());
|
||||
assertEquals("ASSET", resource.getKind());
|
||||
assertEquals(NEW_CONTENT_REF, resource.getContentRef());
|
||||
assertNull(resource.getTextContent());
|
||||
assertFalse(result.getIsText());
|
||||
verify(contentStore).put("# Guide\n".getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 assets 路径不能通过文本创建入口形成非规范表示。
|
||||
*/
|
||||
@Test
|
||||
public void createTextAssetIsRejected() {
|
||||
SkillFileSaveRequest request = new SkillFileSaveRequest();
|
||||
request.setSkillId(SKILL_ID);
|
||||
request.setPath("assets/readme.txt");
|
||||
request.setContent("text");
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class,
|
||||
() -> service.createTextFile(request));
|
||||
|
||||
assertTrue(exception.getMessage().contains("二进制文件管理"));
|
||||
verify(skillResourceService, never()).save(any(SkillResource.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证未知脚本扩展名仍可保真保存,并退化为无语言高亮的文本脚本。
|
||||
*/
|
||||
@Test
|
||||
public void unrecognizedScriptExtensionUsesPlainTextRepresentation() {
|
||||
AtomicReference<SkillResource> savedResource = new AtomicReference<>();
|
||||
when(skillResourceService.list(any(QueryWrapper.class)))
|
||||
.thenAnswer(invocation -> savedResource.get() == null
|
||||
? List.of() : List.of(savedResource.get()));
|
||||
when(skillResourceService.save(any(SkillResource.class))).thenAnswer(invocation -> {
|
||||
SkillResource resource = invocation.getArgument(0);
|
||||
resource.setId(BigInteger.valueOf(10));
|
||||
savedResource.set(resource);
|
||||
return true;
|
||||
});
|
||||
SkillFileSaveRequest request = new SkillFileSaveRequest();
|
||||
request.setSkillId(SKILL_ID);
|
||||
request.setPath("scripts/run.rb");
|
||||
request.setContent("puts 'ok'\n");
|
||||
|
||||
SkillFileContent result = service.createTextFile(request);
|
||||
|
||||
assertEquals("SCRIPT", savedResource.get().getKind());
|
||||
assertTrue(savedResource.get().getIsText());
|
||||
assertNull(savedResource.get().getLanguage());
|
||||
assertEquals("text/plain", savedResource.get().getMediaType());
|
||||
assertEquals("puts 'ok'\n", result.getContent());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证非 Markdown Reference 保存后仍保留按扩展名识别的媒体类型。
|
||||
*/
|
||||
@Test
|
||||
public void jsonReferenceSavePreservesJsonRepresentation() {
|
||||
String sourceHash = "d".repeat(64);
|
||||
SkillResource resource = resource(
|
||||
"references/data.json", true, "{}", null, sourceHash, 2L);
|
||||
resource.setKind("REFERENCE");
|
||||
resource.setLanguage(null);
|
||||
resource.setMediaType("application/json");
|
||||
when(skillResourceService.list(any(QueryWrapper.class)))
|
||||
.thenReturn(List.of(resource), List.of(resource));
|
||||
when(skillResourceService.update(eq(resource), any(QueryWrapper.class))).thenReturn(true);
|
||||
SkillFileSaveRequest request = new SkillFileSaveRequest();
|
||||
request.setSkillId(SKILL_ID);
|
||||
request.setPath("references/data.json");
|
||||
request.setContent("{\"ok\":true}\n");
|
||||
request.setExpectedContentHash(sourceHash);
|
||||
|
||||
SkillFileContent result = service.saveContent(request);
|
||||
|
||||
assertEquals("REFERENCE", resource.getKind());
|
||||
assertEquals("application/json", resource.getMediaType());
|
||||
assertNull(resource.getLanguage());
|
||||
assertEquals("application/json", result.getMediaType());
|
||||
assertEquals("{\"ok\":true}\n", result.getContent());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证保存 SKILL.md 时不会提前修改当前会话中的持久化实体,避免一级缓存导致版本误判。
|
||||
*/
|
||||
@Test
|
||||
public void skillMarkdownSaveUsesDetachedUpdateForOptimisticCheck() {
|
||||
String oldContent = "---\nname: demo\ndescription: old\n---\n\n# Old\n";
|
||||
String newContent = "---\nname: demo\ndescription: new\n---\n\n# New\n";
|
||||
String oldHash = com.easyagents.skill.util.SkillHashes.sha256Hex(
|
||||
oldContent.getBytes(StandardCharsets.UTF_8));
|
||||
Skill persisted = new Skill();
|
||||
persisted.setId(SKILL_ID);
|
||||
persisted.setTenantId(BigInteger.ONE);
|
||||
persisted.setCategoryId(BigInteger.valueOf(3));
|
||||
persisted.setDisplayName("演示 Skill");
|
||||
persisted.setEnabled(false);
|
||||
persisted.setVisibilityScope("DEPT");
|
||||
persisted.setSkillContent(oldContent);
|
||||
persisted.getMetadataJson().put("owner", "qa");
|
||||
AtomicReference<Skill> updateRef = new AtomicReference<>();
|
||||
when(skillService.getOne(any(QueryWrapper.class))).thenReturn(persisted);
|
||||
when(skillService.updateDraftIfContentMatches(any(Skill.class), eq(oldHash)))
|
||||
.thenAnswer(invocation -> {
|
||||
updateRef.set(invocation.getArgument(0));
|
||||
return persisted;
|
||||
});
|
||||
SkillFileSaveRequest request = new SkillFileSaveRequest();
|
||||
request.setSkillId(SKILL_ID);
|
||||
request.setPath("SKILL.md");
|
||||
request.setContent(newContent);
|
||||
request.setExpectedContentHash(oldHash);
|
||||
|
||||
service.saveContent(request);
|
||||
|
||||
Skill update = updateRef.get();
|
||||
assertNotSame(persisted, update);
|
||||
assertEquals(oldContent, persisted.getSkillContent());
|
||||
assertEquals(newContent, update.getSkillContent());
|
||||
assertEquals(persisted.getCategoryId(), update.getCategoryId());
|
||||
assertEquals(persisted.getDisplayName(), update.getDisplayName());
|
||||
assertEquals(persisted.getEnabled(), update.getEnabled());
|
||||
assertEquals(persisted.getVisibilityScope(), update.getVisibilityScope());
|
||||
assertNotSame(persisted.getMetadataJson(), update.getMetadataJson());
|
||||
assertEquals(persisted.getMetadataJson(), update.getMetadataJson());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建内存上传文件。
|
||||
*
|
||||
* @param filename 文件名
|
||||
* @param content 文件内容
|
||||
* @return MultipartFile
|
||||
*/
|
||||
private MultipartFile multipart(String filename, String content) {
|
||||
return new TestMultipartFile(filename, content.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建测试资源。
|
||||
*
|
||||
* @param path 路径
|
||||
* @param text 是否文本
|
||||
* @param textContent 文本内容
|
||||
* @param contentRef 内容引用
|
||||
* @param contentHash 内容 hash
|
||||
* @param size 字节数
|
||||
* @return 资源实体
|
||||
*/
|
||||
private SkillResource resource(String path,
|
||||
boolean text,
|
||||
String textContent,
|
||||
String contentRef,
|
||||
String contentHash,
|
||||
long size) {
|
||||
SkillResource resource = new SkillResource();
|
||||
resource.setId(BigInteger.valueOf(8));
|
||||
resource.setTenantId(BigInteger.ONE);
|
||||
resource.setSkillId(SKILL_ID);
|
||||
resource.setPath(path);
|
||||
resource.setNormalizedPath(path);
|
||||
resource.setIsText(text);
|
||||
resource.setTextContent(textContent);
|
||||
resource.setContentRef(contentRef);
|
||||
resource.setContentHash(contentHash);
|
||||
resource.setSize(size);
|
||||
return resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建重命名请求。
|
||||
*
|
||||
* @param path 原路径
|
||||
* @param newPath 新路径
|
||||
* @param hash 预期内容 hash
|
||||
* @return 重命名请求
|
||||
*/
|
||||
private SkillFileRenameRequest renameRequest(String path, String newPath, String hash) {
|
||||
SkillFileRenameRequest request = new SkillFileRenameRequest();
|
||||
request.setSkillId(SKILL_ID);
|
||||
request.setPath(path);
|
||||
request.setNewPath(newPath);
|
||||
request.setExpectedContentHash(hash);
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* 简单内存 MultipartFile 测试替身。
|
||||
*/
|
||||
private static final class TestMultipartFile implements MultipartFile {
|
||||
|
||||
private final String filename;
|
||||
private final byte[] bytes;
|
||||
|
||||
/**
|
||||
* 创建测试文件。
|
||||
*
|
||||
* @param filename 文件名
|
||||
* @param bytes 内容
|
||||
*/
|
||||
private TestMultipartFile(String filename, byte[] bytes) {
|
||||
this.filename = filename;
|
||||
this.bytes = bytes;
|
||||
}
|
||||
|
||||
@Override public String getName() { return "file"; }
|
||||
@Override public String getOriginalFilename() { return filename; }
|
||||
@Override public String getContentType() { return "application/octet-stream"; }
|
||||
@Override public boolean isEmpty() { return bytes.length == 0; }
|
||||
@Override public long getSize() { return bytes.length; }
|
||||
@Override public byte[] getBytes() { return bytes.clone(); }
|
||||
@Override public InputStream getInputStream() { return new ByteArrayInputStream(bytes); }
|
||||
@Override public void transferTo(File destination) throws IOException {
|
||||
org.springframework.util.FileCopyUtils.copy(bytes, destination);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package tech.easyflow.skill.imports;
|
||||
|
||||
import com.easyagents.skill.model.SkillPackageLimits;
|
||||
import com.easyagents.skill.exception.SkillPackageException;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.junit.Test;
|
||||
import tech.easyflow.common.web.exceptions.BusinessException;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* {@link EasyFlowBundleReader} 外层 ZIP 文件数量边界测试。
|
||||
*/
|
||||
public class EasyFlowBundleReaderEntryLimitTest {
|
||||
|
||||
/**
|
||||
* 验证标准包最大文件数之外允许额外携带一个 EasyFlow manifest。
|
||||
*/
|
||||
@Test
|
||||
public void containsManifestAllowsOneManifestBeyondStandardEntryLimit() {
|
||||
int standardEntryLimit = SkillPackageLimits.defaults().getMaxEntryCount();
|
||||
byte[] bundle = bundle(standardEntryLimit);
|
||||
EasyFlowBundleReader reader = new EasyFlowBundleReader(mock(EasyFlowSkillManifestCodec.class));
|
||||
|
||||
assertTrue(reader.containsManifest(new ByteArrayInputStream(bundle)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证外层 ZIP 不能借 manifest 配额多携带第二个普通文件。
|
||||
*/
|
||||
@Test
|
||||
public void containsManifestRejectsMoreThanOneEntryBeyondStandardLimit() {
|
||||
int standardEntryLimit = SkillPackageLimits.defaults().getMaxEntryCount();
|
||||
byte[] bundle = bundle(standardEntryLimit + 1);
|
||||
EasyFlowBundleReader reader = new EasyFlowBundleReader(mock(EasyFlowSkillManifestCodec.class));
|
||||
|
||||
assertThrows(BusinessException.class,
|
||||
() -> reader.containsManifest(new ByteArrayInputStream(bundle)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 损坏的增强包属于客户端输入错误,不能伪装成服务端存储故障。
|
||||
*/
|
||||
@Test
|
||||
public void corruptedBundleUsesClientErrorStatus() {
|
||||
EasyFlowBundleReader reader = new EasyFlowBundleReader(mock(EasyFlowSkillManifestCodec.class));
|
||||
|
||||
BusinessException detectionError = assertThrows(BusinessException.class,
|
||||
() -> reader.containsManifest(new ByteArrayInputStream("not-a-zip".getBytes(StandardCharsets.UTF_8))));
|
||||
BusinessException prepareError = assertThrows(BusinessException.class,
|
||||
() -> reader.prepare(new ByteArrayInputStream("not-a-zip".getBytes(StandardCharsets.UTF_8))));
|
||||
|
||||
assertEquals(400, detectionError.getHttpStatus());
|
||||
assertEquals(400, prepareError.getHttpStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 之后的非法原始文件名字节也必须被完整扫描并返回稳定错误码。
|
||||
*/
|
||||
@Test
|
||||
public void invalidUtf8EntryNameUsesStablePackageCode() {
|
||||
EasyFlowBundleReader reader = new EasyFlowBundleReader(mock(EasyFlowSkillManifestCodec.class));
|
||||
|
||||
SkillPackageException detectionError = assertThrows(SkillPackageException.class,
|
||||
() -> reader.containsManifest(new ByteArrayInputStream(invalidUtf8EntryNameBundle())));
|
||||
SkillPackageException prepareError = assertThrows(SkillPackageException.class,
|
||||
() -> reader.prepare(new ByteArrayInputStream(invalidUtf8EntryNameBundle())));
|
||||
|
||||
assertEquals("INVALID_UTF8_ENTRY_NAME", detectionError.getCode());
|
||||
assertEquals("INVALID_UTF8_ENTRY_NAME", prepareError.getCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* 外层 ZIP 中央目录 CRC 被篡改时必须在重新打包前拒绝,并返回稳定错误码。
|
||||
*/
|
||||
@Test
|
||||
public void crcMismatchUsesStablePackageCode() {
|
||||
byte[] corrupted = tamperFirstCentralDirectoryCrc(bundle(1));
|
||||
EasyFlowBundleReader reader = new EasyFlowBundleReader(mock(EasyFlowSkillManifestCodec.class));
|
||||
|
||||
SkillPackageException detectionError = assertThrows(SkillPackageException.class,
|
||||
() -> reader.containsManifest(new ByteArrayInputStream(corrupted)));
|
||||
SkillPackageException prepareError = assertThrows(SkillPackageException.class,
|
||||
() -> reader.prepare(new ByteArrayInputStream(corrupted)));
|
||||
|
||||
assertEquals("CRC_MISMATCH", detectionError.getCode());
|
||||
assertEquals("CRC_MISMATCH", prepareError.getCode());
|
||||
assertTrue(detectionError.getPath().startsWith("skills/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建将 manifest 放在末尾的增强包,以覆盖完整枚举边界。
|
||||
*
|
||||
* @param standardEntries 普通文件数量
|
||||
* @return 增强包字节
|
||||
*/
|
||||
private byte[] bundle(int standardEntries) {
|
||||
try {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes, StandardCharsets.UTF_8)) {
|
||||
for (int index = 0; index < standardEntries; index++) {
|
||||
zip.putNextEntry(new ZipEntry(String.format(
|
||||
"skills/demo-skill/assets/file-%04d.txt", index)));
|
||||
zip.closeEntry();
|
||||
}
|
||||
zip.putNextEntry(new ZipEntry(EasyFlowSkillManifestCodec.MANIFEST_PATH));
|
||||
zip.write("{}".getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("创建增强包文件数量边界样例失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 manifest 位于非法文件名前方的恶意增强包,验证检测流程不会提前返回。
|
||||
*
|
||||
* @return 恶意增强包字节
|
||||
*/
|
||||
private byte[] invalidUtf8EntryNameBundle() {
|
||||
try {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(bytes)) {
|
||||
output.setEncoding(StandardCharsets.ISO_8859_1.name());
|
||||
output.setUseLanguageEncodingFlag(false);
|
||||
output.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NEVER);
|
||||
|
||||
ZipArchiveEntry manifest = new ZipArchiveEntry(EasyFlowSkillManifestCodec.MANIFEST_PATH);
|
||||
output.putArchiveEntry(manifest);
|
||||
output.write("{}".getBytes(StandardCharsets.UTF_8));
|
||||
output.closeArchiveEntry();
|
||||
|
||||
ZipArchiveEntry invalidName = new ZipArchiveEntry("skills/demo-skill/assets/\u00ff.bin");
|
||||
output.putArchiveEntry(invalidName);
|
||||
output.write(new byte[]{1});
|
||||
output.closeArchiveEntry();
|
||||
output.finish();
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("创建非法 UTF-8 文件名增强包失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 篡改首个中央目录条目的 CRC 字段。
|
||||
*
|
||||
* @param source 原始 ZIP
|
||||
* @return 篡改后的 ZIP
|
||||
*/
|
||||
private byte[] tamperFirstCentralDirectoryCrc(byte[] source) {
|
||||
byte[] bytes = Arrays.copyOf(source, source.length);
|
||||
for (int index = 0; index <= bytes.length - 20; index++) {
|
||||
if (bytes[index] == 0x50 && bytes[index + 1] == 0x4B
|
||||
&& bytes[index + 2] == 0x01 && bytes[index + 3] == 0x02) {
|
||||
bytes[index + 16] ^= 0x01;
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("未找到 ZIP 中央目录");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user