Compare commits
11 Commits
84be9c658a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d97e69d124 | |||
| 74b30adb6e | |||
| 36aa94db7d | |||
| 49d056be09 | |||
| a5e2540c8f | |||
| 93f3823a06 | |||
| 4af6776164 | |||
| 732655e776 | |||
| 5eed5f0b26 | |||
| 529f73f8f5 | |||
| 6f180522f3 |
@@ -1,5 +1,6 @@
|
||||
# EIP4 单源托管(A10 W3)。挂载为 nginx:alpine 的 /etc/nginx/conf.d/default.conf。
|
||||
# 一个源:静态 SPA(eip4-web/dist)+ 反代 /api→platform-app、/flowable→flowable-service。
|
||||
# 一个源:静态 SPA(eip4-web/dist)+ 反代 /api→platform-app(唯一后端入口)。
|
||||
# flowable-service:8089 无鉴权,绝不经 nginx 对外(见下 /flowable/ 说明)。
|
||||
# 消除 dev 的 vite proxy 依赖;切流灰度(W6)可在此用 upstream 权重双跑(eip3↔eip4)。
|
||||
server {
|
||||
listen 80;
|
||||
@@ -22,12 +23,14 @@ server {
|
||||
proxy_read_timeout 130s; # 略大于 statement_timeout(120s),避免反代先于 DB 超时切断
|
||||
}
|
||||
|
||||
# 工作流引擎(按需直达;多数流程经 platform-app 网关,故默认收窄)
|
||||
# 🔴 工作流引擎(flowable-service:8089)绝不对外暴露。
|
||||
# flowable-service 进程无 Spring Security,鉴权唯一落点=platform-app 网关的超管门
|
||||
# (ProcessModelerController.requireSuperAdmin);裸直达 8089 会绕过所有鉴权,
|
||||
# 匿名即可部署/覆盖生产 BPMN、办结/终止任意任务(安全评审 Critical#1)。
|
||||
# 前端只经 /api/workflow/*(网关)访问流程能力,不需要 /flowable/ 直达。
|
||||
# 若确需内网调试直达,改为 `internal;` 仅供内部子请求,严禁对公网 proxy_pass。
|
||||
location /flowable/ {
|
||||
proxy_pass http://flowable-service:8089/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
return 404;
|
||||
}
|
||||
|
||||
# 静态资源:带 hash 的构建产物可长缓存
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
| `plans/2026-06-25-报表迁移-JOR引擎重宿主-design.md` | 报表 A3 设计(Phase1-3 已完成 + 安全收口,总览 §11) |
|
||||
| `plans/2026-06-25-审批闭环-实施计划.md` | 审批闭环 P0-P3(已实施合 main `c95eaee`,剩外部前置) |
|
||||
| `plans/2026-06-26-在线流程Modeler-design.md` | B3 流程 Modeler 设计(D1-D9 拍定) |
|
||||
| `plans/2026-07-02-在线流程Modeler-实施计划.md` | B3 实施计划(4 阶段 TDD 任务,含语料/代码勘探基线 + P1-P6 计划级决策,**执行中**) |
|
||||
| `plans/2026-07-02-在线流程Modeler-实施计划.md` | B3 实施计划(4 阶段 17 任务 **全完成合 main 2026-07-02**;含语料/代码勘探基线 + 计划级决策 + 每阶段 live 验收发现 + 双对抗评审处置) |
|
||||
| `AI_AGENT_AUTO_DEVELOPMENT.md` + `AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md` / `AI_AGENT_REPAIR_CONTRACT.md` / `AI_AGENT_Nocobase_ADOPTION_PLAN.md` + `skills/` | AI Agent 对外口径红线 + 编译/修复/采纳契约 + Skills 目录 |
|
||||
| `framework定制视图-TODO-2026-06-17.md` | A 兼容线**活清单**(Done/In-Progress/待验三态),每次修完回写 |
|
||||
| `framework定制视图-engineclass移植backlog-2026-06-17.md` | 46 framework 视图迁移**主 backlog**(verdict/移植项/优先级) |
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 在线流程 Modeler(B3)实施计划
|
||||
|
||||
> **✅ B3 全 17 任务完成并合 main(2026-07-02)**:platform origin/main 阶段1-4 全合、web origin/main 全合;每任务 TDD+对抗评审+修复轮,每阶段出口 live 验收(挡下 3 个单测/评审都没抓到的真 bug:options语义/面板ref/**bpmn-js PascalCase断部署**),末尾双对抗评审(安全+发布链)判定可宣告完成、唯一 Critical(nginx骨架洞)已修。**Modeler 端到端可用**:打开中文key存量流程→改办理人/会签保真读回→存草稿eip4IdMap保全→同人确认发布→部署新版本中文key保住+审计+起实例真userTask+旧实例不动+非admin403。
|
||||
>
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
>
|
||||
> 设计权威:`2026-06-26-在线流程Modeler-design.md`(D1-D9 已拍定)。本计划把 design 落成 TDD 任务,
|
||||
@@ -317,6 +319,8 @@ commit:`feat(flow): 草稿发布(id还原+ProcessValidator校验门)+影响摘
|
||||
|
||||
commit:`feat(gateway): 发布语义校验门+sys_flow_deploy_audit 审计(V4)`
|
||||
|
||||
> 🔴🔴 **阶段3 live 揪出 CRITICAL——activiti.json 描述符致 bpmn-js Modeler 输出 PascalCase 元素名(部署链断)**:bpmn-js Modeler.saveXML 对 activiti.json `extends` 的 bpmn 类型(Process/UserTask/StartEvent)序列化成大写 `<Process>/<UserTask>/<StartEvent>`(未扩展的 sequenceFlow/endEvent 仍小写)。Flowable 大小写敏感→`<Process>` 不识别→ProcessValidator 报 flowable-process-definition-not-executable,**部署完全断**。「isExecutable 丢失」是此 bug 症状非独立问题。**T1.1/T1.2 moddle round-trip 测试抓不到**(直接 fromXML→toXML 读写同形),只有真 Modeler saveXML+真部署暴露(live 铁证)。修=重构 activiti.json 扩展类型定义让 Modeler 序列化保持小写 BPMN 元素名(moddle extends 惯用法),验收硬门=saveXML 输出小写 userTask/process + 真部署 200 + 起实例生成 userTask。已挂 T3.3 修复轮 + 需前端保真测试升级到「过 bpmn-js Modeler.saveXML 非仅 bpmn-moddle」。
|
||||
|
||||
### Task 3.3 前端:同人确认弹窗(影响摘要)+ 发布流
|
||||
|
||||
**Files:** Create `src/modeler/PublishConfirm.tsx`(+test)、`src/modeler/diffSummary.ts`(+test,P2 节点级 diff);Modify `ProcessModelerPage.tsx`。
|
||||
@@ -355,6 +359,23 @@ commit:`test(modeler): 流程Modeler live e2e(改存量/新建/走查 3 场景
|
||||
|
||||
---
|
||||
|
||||
## B3 最终发布链对抗评审处置(2026-07-02)
|
||||
判定「可宣告完成,无 Critical 无阻断」。id 保真闭环三来源自洽+发布错误契约双形状透传扎实。跟进项处置:
|
||||
- **I-1 formKey 门误拒改存量——语料 dry-run 证伪(无需修)**:全库 803 个 distinct activiti:formKey **全部命中 view_wftemplate(miss=0)**,formKey 门不会误拒任何存量流程。评审担心的静默回归在真实库不成立。
|
||||
- **I-2 空 content 语义缺口**:已作已知限制记录(见下),v2 精化(content 可能是变量表达式,硬要求非空会误拒,需按 type 分白名单)。
|
||||
- **M-1**(下游 422 顶层文案 handler 用 message、前端读 msg,per-node 错误仍渲染)/ M-2(by-id 写删侧无 category 守卫,超管门+UI 已兜)/ M-3(writeCosign 重建只保 4 属性,真实会签仅用 handler-collection 模式暴露低)= 低优先清理 backlog。
|
||||
|
||||
## B3 最终安全对抗评审(2026-07-02 阶段4)——1 Critical 已修 + A10 生产加固 backlog
|
||||
|
||||
- **✅ Critical#1 已修**:`deploy/nginx.conf` 的 `/flowable/` 裸 proxy 到无鉴权 8089 对公网暴露→绕过网关超管门匿名部署/覆盖生产 BPMN。改 `return 404`(前端只走 `/api/workflow/` 网关,不需要直达)。**注:此洞在 A10 部署骨架里、生产未切流,非 B3 运行时可达**;网关侧超管门本身实现严密无绕过面(评审确认)。
|
||||
- **A10 生产加固 backlog(非 B3 dev 阻塞,超管信任模型内可接受,随 A10 生产化做)**:High#2 部署 BPMN 可含 serviceTask/JUEL 表达式/监听器=引擎内表达式求值面(超管信任内可接受;修 #1 后降为加固项,v2 可加可执行元素白名单);Medium#3 网关→flowable-service 无凭据纯靠网络隔离(加 X-Internal-Auth 共享密钥纵深);Medium#4 审计只覆盖网关 deploy 路径+写失败静默(下沉审计到 flowable-service 实际部署点或加失败告警)。Low#5(无细粒度流程授权=v1有意)/#6(伪造metaInfo不提权=超管本可写任意key)/#7(impact 缺 DOCTYPE 兜底=enableSafeBpmnXml 已挡)/#8(disableSchemaValidation 只跳 XSD 不开 DTD) 均已缓解/可接受。
|
||||
|
||||
## 已知限制 / v2 精化点(2026-07-02 阶段4 e2e 发现)
|
||||
|
||||
- **会签办理人 content 为空的语义缺口**:ModelSemanticValidator 校验 `items 非空`(数组长度)但不校验 candidate item 的 `content 非空`。会签模板出厂 items=[{type:user,content:""}] 过语义门,但运行期 multiInstanceUsersHandler 解析空 content → MI 跳过 → 流程无任务直接结束。**不硬修**(content 常是 `${APPLYUSERS}` 变量表达式,硬要求非空会误拒合法流程);v2 可考虑「content 空且非变量表达式 → WARNING」。用户新建会签流程须填办理人,否则部署出空转流程。
|
||||
- **live e2e 非幂等**:发布无运行时下架端点,每跑场景A「总包合同交底」版本 +1(live 验收固有,非 CI 硬门)。
|
||||
- **非超管 403 e2e 降级**:dev 库无非超管账号,场景C④用无 token(principal==null 走同一 requireSuperAdmin 分支)+admin 对照证门有效;真非超管 token 断言待 dev 库补账号。
|
||||
|
||||
## 验收清单(全项打勾才算 B3 完成)
|
||||
|
||||
- [ ] 1512 流 moddle round-trip 扫描零丢失(Task 1.2 工具实测)
|
||||
|
||||
@@ -16,6 +16,7 @@ EIP3(Vaadin / 老引擎)→ EIP4(amis 前端 + 保真层 + 转换器)迁
|
||||
- **B 新能力线本期里程碑突破**:「人走五环建新功能」低代码平台 **v1 全链交付并合入 origin/main 两仓**;设计器选型(amis-editor)拍板且 **DesignerPage 全闭环上线**(解除历史 P1 头号阻塞);AI 确定性(非 LLM)五环生产线**已合 main**。
|
||||
- **安全基线(§10.1 四项 P0 + 评审追加 2 孪生 + Groovy 沙箱)2026-06-25 全数收口并 push**(platform `eba9ce1` / web `2a37251`),可达 RCE/越权/fail-open 已闭。
|
||||
- **报表保真层(套打 JOR)2026-06-25/26 重宿主 + 安全/OOM 收口全数完成并 push origin/main**(§11):SQLi 门 / IDOR 授权 / XXE / 并发·字节·超时·结果集封顶 / CVE 依赖替换 / 报表只读数据源;11 类 79 单测 + live e2e + 安全对抗复审,三批 merge `e6c73a4`/`dccca17`/`d697885`。
|
||||
- **B3 在线流程 Modeler v1 全链交付并合 main(2026-07-02)**:可编辑存量/新建 BPMN→草稿→同人确认发布→部署 Flowable(中文 key 保真+EIP4 办理人/会签控件+发布门+审计),A2 审批线的「流程定义在线编辑」最后一块补齐。
|
||||
- 项目仍在 **dev 环境**;生产上线工程化(A10)**MVP 骨架已合 main(2026-06-25)**:W1 Flyway(`db/migration/V1-V3`)+ W2-W4 容器化/nginx 单源/compose 编排(`deploy/` + 模块根 Dockerfile),切流执行 / 性能并发 / 灰度未做。
|
||||
|
||||
---
|
||||
@@ -77,7 +78,7 @@ EIP3(Vaadin / 老引擎)→ EIP4(amis 前端 + 保真层 + 转换器)迁
|
||||
| **人走五环** | NocoBase 式建模器 + 实时设计器 v1 | 🟢 | **v1 全链交付 + live 验收 + 合 main 两仓**(platform 418 单测 / web 73 vitest)。五环①②③④(含引用列)+ AI①面恒 READY_FOR_HUMAN_REVIEW + production 人审部署包(requiresHumanApproval=true)+ 主子表四件套全完,红线全守。**v1 限简单 CRUD/树 recipe + 只建新不改表** |
|
||||
| **B1** | 新设计器(低代码可视化) | 🟢 | **选型已拍板**:D1 签字下注 amis-editor(接受 amis-fork 6.13.0 冻结天花板 / bus factor≈1 自维护);形态 = NocoBase 式建模器 + 实时设计器,不做线性 wizard。**DesignerPage 已修到全闭环**(`2278cbc` 等 6 提交),原 P1 头号阻塞已解除 |
|
||||
| **B2** | AI 模块 | 🟢 | **确定性(非 LLM)五环增量生产线已合 main**(超 PoC)。platform-ai + platform-cli 落地;终点恒人审、平台不内置生成 LLM(唯 LLM 修复 `HttpAiLlmRepairClient` 默认关、只修不生成)。落地 P0/P1/P2/P4/P5 第一版完成,P3 进行中 |
|
||||
| **B3** | 流程建模器 BPMN Modeler | 🔴 | 未起步(即 A2 现在唯一缺的「流程定义在线编辑」)。注:BPMN 只读**查看**已做(A2 流程图,bpmn-js NavigatedViewer);Modeler=可编辑+部署,需 S1 拍板自研 vs 嵌入 flowable-modeler |
|
||||
| **B3** | 流程建模器 BPMN Modeler | 🟢 | **v1 全链交付并合 main(2026-07-02,platform+web)**。bpmn-js Modeler 可编辑存量/新建 BPMN 流程→存草稿(act_re_model)→同人确认发布→部署到 Flowable。含:可逆 id 净化(中文流程 key 保真 D7)、EIP4 侧板五控件(办理人/会签保真读回/formKey/扩展属性/监听器)、办理人表达式 codec(逐字对齐引擎)、activiti moddle 完整描述符(1512/1512 保真零丢失)、发布门(ProcessValidator+网关语义校验+超管门+审计 V4)、4 新建模板、Playwright e2e 三场景。17 任务 TDD+对抗评审+每阶段 live 验收(挡 3 真 bug 含 bpmn-js PascalCase 断部署)。设计+实施计划见 `plans/2026-07-02-在线流程Modeler-实施计划.md`。残:A10 生产加固 backlog(nginx 洞已修/引擎表达式白名单/网关内部鉴权)、空 content 语义校验、细粒度流程授权(v2)。BPMN 只读查看(A2 流程图)仍在 |
|
||||
| **B4** | 生产级 UI/UE 组件体系 | 🟡 | L1 主题(amis-theme.css §10-15 密度/按钮/弹窗/字号)+ L2 行选中 `checkOnItemClick` + 设计中心 DesignCenterPage 已上线;剩选择框统一 / 主子表宿主 / 树编辑 Drawer / 审批待办 未完整(`组件设计体系-design-2026-06-15` 落地状态需对齐本矩阵) |
|
||||
| **B5** | 移动端 / 响应式 | 🔴 | 未起步 |
|
||||
| **B6** | 报表设计器(自助报表) | 🔴 | 未起步(与 A3 同根待立项) |
|
||||
|
||||
@@ -2,19 +2,27 @@ package com.eip4.flowservice.api;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.flowable.bpmn.converter.BpmnXMLConverter;
|
||||
import org.flowable.bpmn.model.BpmnModel;
|
||||
import org.flowable.common.engine.impl.util.io.StringStreamSource;
|
||||
import org.flowable.engine.RepositoryService;
|
||||
import org.flowable.engine.RuntimeService;
|
||||
import org.flowable.engine.repository.Model;
|
||||
import org.flowable.engine.repository.ProcessDefinition;
|
||||
import org.flowable.validation.ProcessValidator;
|
||||
import org.flowable.validation.ProcessValidatorFactory;
|
||||
import org.flowable.validation.ValidationError;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StreamUtils;
|
||||
@@ -27,6 +35,7 @@ import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -67,11 +76,42 @@ public class ProcessModelController {
|
||||
/** DOCTYPE 门 prolog 扫描字节上限(BOM/XML 声明/注释/DOCTYPE 都在最前)。 */
|
||||
private static final int PROLOG_SCAN_BYTES = 8192;
|
||||
|
||||
/**
|
||||
* bpmn-js {@code saveXML} 补的 {@code <*:incoming>/<*:outgoing>} 文本引用元素(前缀可选:bpmn/bpmn2/默认)。
|
||||
* 发布前整体剥除——Flowable 从 {@code sequenceFlow} 的 sourceRef/targetRef 自行推导入出边,这些元素冗余;
|
||||
* 且它们把节点/流 id 存为<b>元素文本</b>(非属性),{@link BpmnIdSanitizer#restore} 只还原属性位不碰文本
|
||||
* → 不剥则落库「属性=中文原 key、文本引用=净化 id」的脏 XML(T1.3 评审 I-2)。
|
||||
*/
|
||||
private static final Pattern FLOW_REF_ELEMENT = Pattern.compile(
|
||||
"<(?:[\\w.-]+:)?(?:incoming|outgoing)>[^<]*</(?:[\\w.-]+:)?(?:incoming|outgoing)>");
|
||||
|
||||
private final RepositoryService repositoryService;
|
||||
private final RuntimeService runtimeService;
|
||||
private final ProcessValidator processValidator;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
public ProcessModelController(RepositoryService repositoryService) {
|
||||
@Autowired
|
||||
public ProcessModelController(RepositoryService repositoryService, RuntimeService runtimeService) {
|
||||
this(repositoryService, runtimeService, new ProcessValidatorFactory().createDefaultProcessValidator());
|
||||
}
|
||||
|
||||
/**
|
||||
* 单参构造:既有草稿 CRUD 单测保留零改动地 {@code new ProcessModelController(repositoryService)}
|
||||
* (那些用例不触发发布/影响路径,无需 RuntimeService/校验器)。
|
||||
*/
|
||||
ProcessModelController(RepositoryService repositoryService) {
|
||||
this(repositoryService, null, new ProcessValidatorFactory().createDefaultProcessValidator());
|
||||
}
|
||||
|
||||
/**
|
||||
* 全参构造:发布/影响端点单测注入 <b>mock</b> {@link ProcessValidator}
|
||||
* ({@code ProcessValidatorFactory} 产的默认校验器无法 mock,须构造注入以断言 ERROR-vs-WARNING 分支)。
|
||||
*/
|
||||
ProcessModelController(RepositoryService repositoryService, RuntimeService runtimeService,
|
||||
ProcessValidator processValidator) {
|
||||
this.repositoryService = repositoryService;
|
||||
this.runtimeService = runtimeService;
|
||||
this.processValidator = processValidator;
|
||||
}
|
||||
|
||||
@GetMapping("/models")
|
||||
@@ -230,6 +270,188 @@ public class ProcessModelController {
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
@PostMapping("/models/{id}/deploy")
|
||||
@Operation(summary = "发布草稿为流程定义",
|
||||
description = "草稿不存在→404;还原 eip4IdMap 里的中文原 key(存量流程 D7 硬需求,新建流程无 idMap 跳过)+"
|
||||
+ "剥除 bpmn-js 补的 incoming/outgoing 文本引用 → 引擎 ProcessValidator 语义校验(仅 ERROR 级阻断,"
|
||||
+ "返 422 {errors:[{activityId,problem,defaultDescription}]} 不部署;WARNING 放行)→ "
|
||||
+ "createDeployment().disableSchemaValidation()(只跳 XSD:bpmn-js 默认命名空间与严格 XSD 已知不兼容,"
|
||||
+ "语义校验已在上一步)部署 → {status:0,deploymentId,processKey,newVersion}。")
|
||||
public ResponseEntity<Map<String, Object>> deploy(@PathVariable String id) {
|
||||
Model model = repositoryService.getModel(id);
|
||||
if (model == null) {
|
||||
return status(HttpStatus.NOT_FOUND, "草稿不存在: " + id);
|
||||
}
|
||||
byte[] source = repositoryService.getModelEditorSource(id);
|
||||
if (source == null) {
|
||||
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿源为空,无法发布: " + id);
|
||||
}
|
||||
String deployXml;
|
||||
BpmnModel bpmnModel;
|
||||
try {
|
||||
// resolveIdMap 在 try 内:存量草稿 metaInfo 不可读/丢 eip4IdMap 时 fail-fast(评审 I1),不静默跳过还原。
|
||||
Map<String, String> idMap = resolveIdMap(model.getMetaInfo());
|
||||
deployXml = prepareDeployXml(new String(source, StandardCharsets.UTF_8), idMap);
|
||||
// XXE 兜底:还原后 XML 再过字节级 DOCTYPE 守卫(与 parseGuard 同源防御);enableSafeBpmnXml 亦禁 DOCTYPE,双保险。
|
||||
if (hasDoctypeInBytes(deployXml.getBytes(StandardCharsets.UTF_8))) {
|
||||
log.warn("[流程发布] 拒绝: 还原后 XML 含 DOCTYPE 声明(XXE 防御) id={}", id);
|
||||
return status(HttpStatus.UNPROCESSABLE_ENTITY, "BPMN 解析失败");
|
||||
}
|
||||
// validateSchema=false:bpmn-js 默认命名空间输出与严格 XSD 已知不兼容,语义交给下方 ProcessValidator;
|
||||
// enableSafeBpmnXml=true:加固解析器关外部实体/DTD。
|
||||
bpmnModel = new BpmnXMLConverter().convertToBpmnModel(new StringStreamSource(deployXml), false, true);
|
||||
} catch (IllegalStateException e) {
|
||||
// resolveIdMap 的 fail-fast:存量草稿 metaInfo 不可读/丢 eip4IdMap,还原不出中文原 key→拒发,防落库 nXXX 坏 key(D7)。
|
||||
log.warn("[流程发布] id 映射不可用 id={}: {}", id, e.toString());
|
||||
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿 id 映射不可用,无法还原原 key");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// BpmnIdSanitizer.restore 的 fail-fast:idMap 非双射(metaInfo 损坏)——须炸不能静默还原成别的 key。
|
||||
log.warn("[流程发布] id 还原失败(idMap 损坏) id={}: {}", id, e.toString());
|
||||
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿 id 映射损坏,无法还原原 key");
|
||||
} catch (Exception e) {
|
||||
log.warn("[流程发布] BPMN 解析失败 id={}: {}", id, e.toString());
|
||||
return status(HttpStatus.UNPROCESSABLE_ENTITY, "BPMN 解析失败");
|
||||
}
|
||||
// 引擎校验门:区分 ERROR/WARNING,只 ERROR 级阻断部署。此处仅引擎「结构」校验(节点连通/网关/多实例等);
|
||||
// EIP4 「语义」校验(formKey 存在于 view_wftemplate、办理人/会签内嵌 JSON 白名单)在网关 ModelSemanticValidator(T3.2)。
|
||||
List<Map<String, Object>> blocking = new ArrayList<>();
|
||||
for (ValidationError ve : processValidator.validate(bpmnModel)) {
|
||||
if (ve.isWarning()) {
|
||||
log.info("[流程发布] 校验告警(放行) id={} activityId={} problem={} desc={}",
|
||||
id, ve.getActivityId(), ve.getProblem(), ve.getDefaultDescription());
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> err = new LinkedHashMap<>();
|
||||
err.put("activityId", ve.getActivityId());
|
||||
err.put("problem", ve.getProblem());
|
||||
err.put("defaultDescription", ve.getDefaultDescription());
|
||||
blocking.add(err);
|
||||
}
|
||||
if (!blocking.isEmpty()) {
|
||||
log.warn("[流程发布] ProcessValidator 拒绝 id={} errorCount={}", id, blocking.size());
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", 1);
|
||||
body.put("msg", "流程校验未通过");
|
||||
body.put("errors", blocking);
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(body);
|
||||
}
|
||||
// 部署资源名用中文原 key(仅 act_ge_bytearray 名,不决定 process key——后者取自 XML 的 <process id>)。
|
||||
String resource = model.getKey() + ".bpmn20.xml";
|
||||
var deployment = repositoryService.createDeployment()
|
||||
.disableSchemaValidation()
|
||||
.name(model.getName())
|
||||
.addString(resource, deployXml)
|
||||
.deploy();
|
||||
var deployed = repositoryService.createProcessDefinitionQuery()
|
||||
.deploymentId(deployment.getId()).singleResult();
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("status", 0);
|
||||
resp.put("deploymentId", deployment.getId());
|
||||
resp.put("processKey", deployed != null ? deployed.getKey() : model.getKey());
|
||||
resp.put("newVersion", deployed != null ? deployed.getVersion() : 0);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
@GetMapping("/models/{id}/impact")
|
||||
@Operation(summary = "发布影响摘要",
|
||||
description = "草稿不存在→404;还原后解析 processKey → {processKey,currentVersion(该 key 最新已部署版本,"
|
||||
+ "无则 0),runningInstances(该 key 运行中实例数)}。供同人确认弹窗展示「新版本/旧版本实例不受影响」。")
|
||||
public ResponseEntity<Map<String, Object>> impact(@PathVariable String id) {
|
||||
Model model = repositoryService.getModel(id);
|
||||
if (model == null) {
|
||||
return status(HttpStatus.NOT_FOUND, "草稿不存在: " + id);
|
||||
}
|
||||
byte[] source = repositoryService.getModelEditorSource(id);
|
||||
if (source == null) {
|
||||
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿源为空: " + id);
|
||||
}
|
||||
String processKey;
|
||||
try {
|
||||
// impact 是只读预览:resolveIdMap 抛(存量草稿 metaInfo 不可读)/半成品草稿解析失败,一律回退 model.key
|
||||
// ——from-procdef 建草稿的 model.key 就是中文原 key(创建时 setKey(def.getKey())),回退即得正确 processKey,
|
||||
// 不该因草稿未完成/元数据损坏而 500;真正阻断坏 key 部署由 deploy 端点 fail-fast 负责。
|
||||
// 无独立 DOCTYPE 字节守卫:impact 只查计数不部署,且 convertToBpmnModel 的 enableSafeBpmnXml=true 已禁 DOCTYPE/外部实体。
|
||||
Map<String, String> idMap = resolveIdMap(model.getMetaInfo());
|
||||
String deployXml = prepareDeployXml(new String(source, StandardCharsets.UTF_8), idMap);
|
||||
BpmnModel bpmnModel = new BpmnXMLConverter()
|
||||
.convertToBpmnModel(new StringStreamSource(deployXml), false, true);
|
||||
var mainProcess = bpmnModel.getMainProcess();
|
||||
processKey = mainProcess != null ? mainProcess.getId() : model.getKey();
|
||||
} catch (Exception e) {
|
||||
log.warn("[流程发布] 影响摘要解析失败,回退 model.key id={}: {}", id, e.toString());
|
||||
processKey = model.getKey();
|
||||
}
|
||||
var latest = repositoryService.createProcessDefinitionQuery()
|
||||
.processDefinitionKey(processKey).latestVersion().singleResult();
|
||||
long runningInstances = runtimeService.createProcessInstanceQuery()
|
||||
.processDefinitionKey(processKey).count();
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("processKey", processKey);
|
||||
resp.put("currentVersion", latest != null ? latest.getVersion() : 0);
|
||||
resp.put("runningInstances", runningInstances);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布/影响摘要前的 XML 规范化:①{@link #FLOW_REF_ELEMENT} 剥除 bpmn-js 补的 incoming/outgoing 文本引用元素;
|
||||
* ②{@link BpmnIdSanitizer#restore} 依 {@code idMap} 把净化 id 还原为中文原 key(idMap 空=新建流程,原样返回)。
|
||||
* restore 在剥除后跑:文本引用已消除,还原只作用于属性位,最终部署 XML 无残留净化 id。
|
||||
* idMap 非双射时 restore fail-fast 抛 {@link IllegalArgumentException},由调用方转 422。
|
||||
*/
|
||||
private static String prepareDeployXml(String xml, Map<String, String> idMap) {
|
||||
String stripped = FLOW_REF_ELEMENT.matcher(xml).replaceAll("");
|
||||
return BpmnIdSanitizer.restore(stripped, idMap);
|
||||
}
|
||||
|
||||
/** from-procdef 建草稿写入 metaInfo 的存量标记键(其一存在即表明本草稿源自既有流程定义,editorSource 是净化 XML)。 */
|
||||
private static final String[] FROM_PROCDEF_MARKERS = {"sourceProcDefId", "originalKey"};
|
||||
|
||||
/**
|
||||
* 从 metaInfo JSON 取 {@code eip4IdMap}(原→净化),供 {@link BpmnIdSanitizer#restore} 还原中文原 key。
|
||||
*
|
||||
* <p><b>坏 key 地雷收口(评审 I1)</b>:绝不把「idMap 不可读」静默塌成「空 idMap→跳过还原」——那会让 from-procdef
|
||||
* 存量草稿(editorSource 的 {@code <process id>} 是净化 {@code nXXX})在 metaInfo 损坏时静默部署出 key=nXXX 而非
|
||||
* 中文原 key(HTTP 200 无声,违 D7;且与 restore 非双射 fail-fast 自相矛盾)。据 from-procdef 写的
|
||||
* {@link #FROM_PROCDEF_MARKERS} 判存量草稿:</p>
|
||||
* <ul>
|
||||
* <li>metaInfo 空/null → 真·新建,空 Map(跳过还原,key 原样)。</li>
|
||||
* <li>metaInfo 非空但 JSON 解析失败 → 损坏,{@link IllegalStateException} fail-fast(调用方转 422)。</li>
|
||||
* <li>解析成功、{@code eip4IdMap} <b>存在</b>(是 Map,含空 {@code {}})→ 直接用(空=全 ASCII 存量流程无需还原,正常)。</li>
|
||||
* <li>解析成功、{@code eip4IdMap} <b>缺失/非 Map</b> 且带 from-procdef 标记 → 存量草稿丢了映射,无法还原原 key,
|
||||
* {@link IllegalStateException} fail-fast(宁拒不发坏 key)。</li>
|
||||
* <li>解析成功、无 {@code eip4IdMap} 且无标记 → 真·新建(前端另存了别的 metaInfo),空 Map 正常放行。</li>
|
||||
* </ul>
|
||||
*/
|
||||
private Map<String, String> resolveIdMap(String metaInfo) {
|
||||
if (metaInfo == null || metaInfo.isBlank()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> meta;
|
||||
try {
|
||||
meta = objectMapper.readValue(metaInfo, new TypeReference<Map<String, Object>>() {});
|
||||
} catch (Exception e) {
|
||||
// 非空 metaInfo 却解析不了=损坏,不能猜它是不是存量草稿→一律 fail-fast(宁拒不发可能的坏 key)。
|
||||
throw new IllegalStateException("metaInfo 无法解析,无法确认 id 映射: " + e, e);
|
||||
}
|
||||
Object raw = meta.get("eip4IdMap");
|
||||
if (raw instanceof Map<?, ?> m) {
|
||||
// eip4IdMap 存在(即使空):空=全 ASCII 存量流程无需还原,直接用。
|
||||
Map<String, String> idMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> e : m.entrySet()) {
|
||||
idMap.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
|
||||
}
|
||||
return idMap;
|
||||
}
|
||||
// eip4IdMap 缺失/非 Map:带 from-procdef 标记=存量草稿丢了映射(editorSource 是净化 XML)→fail-fast 防坏 key。
|
||||
for (String marker : FROM_PROCDEF_MARKERS) {
|
||||
if (meta.containsKey(marker)) {
|
||||
throw new IllegalStateException(
|
||||
"存量草稿 metaInfo 缺 eip4IdMap,无法还原净化 id 为中文原 key(marker=" + marker + ")");
|
||||
}
|
||||
}
|
||||
return Map.of(); // 无标记=真·新建,key 原样部署。
|
||||
}
|
||||
|
||||
/**
|
||||
* BPMN 解析守卫:过则返回 {@code null}(放行),坏 XML 返回 422 ResponseEntity({status:1,msg})。
|
||||
* 就地 catch 一切异常,不让引擎 XMLException/FlowableException 逸出到全局 advice(那里映射成 400,语义不符)。
|
||||
|
||||
@@ -19,10 +19,16 @@ import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.flowable.engine.RepositoryService;
|
||||
import org.flowable.engine.RuntimeService;
|
||||
import org.flowable.engine.repository.Deployment;
|
||||
import org.flowable.engine.repository.DeploymentBuilder;
|
||||
import org.flowable.engine.repository.Model;
|
||||
import org.flowable.engine.repository.ModelQuery;
|
||||
import org.flowable.engine.repository.ProcessDefinition;
|
||||
import org.flowable.engine.repository.ProcessDefinitionQuery;
|
||||
import org.flowable.engine.runtime.ProcessInstanceQuery;
|
||||
import org.flowable.validation.ProcessValidator;
|
||||
import org.flowable.validation.ValidationError;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -83,6 +89,23 @@ class ProcessModelControllerTest {
|
||||
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\">"
|
||||
+ "<process id=\"p1\"><startEvent id=\"s\"/></process></definitions>";
|
||||
|
||||
// 存量流程编辑器导出态(发布路径 fixture):process id + sequenceFlow id 原为中文,已被 sanitize 成净化 id
|
||||
// (n1a2b3c / nflow1 / nflow2);bpmn-js saveXML 给流节点补了 <incoming>/<outgoing> 文本引用(内含净化 id)。
|
||||
// metaInfo.eip4IdMap 记「中文原 id→净化 id」,发布时 restore 逆向还原。model.key=中文原 key「总包合同交底」。
|
||||
private static final String DRAFT_SANITIZED_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" targetNamespace=\"http://eip4\">"
|
||||
+ "<process id=\"n1a2b3c\" name=\"总包合同交底\" isExecutable=\"true\">"
|
||||
+ "<startEvent id=\"start1\"><outgoing>nflow1</outgoing></startEvent>"
|
||||
+ "<userTask id=\"taskA\" name=\"交底\"><incoming>nflow1</incoming><outgoing>nflow2</outgoing></userTask>"
|
||||
+ "<endEvent id=\"end1\"><incoming>nflow2</incoming></endEvent>"
|
||||
+ "<sequenceFlow id=\"nflow1\" sourceRef=\"start1\" targetRef=\"taskA\"/>"
|
||||
+ "<sequenceFlow id=\"nflow2\" sourceRef=\"taskA\" targetRef=\"end1\"/>"
|
||||
+ "</process></definitions>";
|
||||
|
||||
// 对应上面 fixture 的 metaInfo:eip4IdMap 三条(process + 两条 sequenceFlow) + sourceProcDefId + 中文 originalKey。
|
||||
private static final String DRAFT_META_INFO = "{\"eip4IdMap\":{\"总包合同交底\":\"n1a2b3c\","
|
||||
+ "\"流转1\":\"nflow1\",\"流转2\":\"nflow2\"},\"sourceProcDefId\":\"def-1\",\"originalKey\":\"总包合同交底\"}";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ProcessModelController controller = new ProcessModelController(repositoryService);
|
||||
@@ -406,6 +429,301 @@ class ProcessModelControllerTest {
|
||||
verify(repositoryService, never()).newModel();
|
||||
}
|
||||
|
||||
// ===== T3.1 发布(deploy)/ 影响摘要(impact) =====
|
||||
|
||||
/** 建带 mock ProcessValidator + RuntimeService 的控制器与 MockMvc(发布/影响端点专用,校验器须可 mock)。 */
|
||||
private MockMvc deployMvc(RuntimeService runtimeService, ProcessValidator validator) {
|
||||
return MockMvcBuilders.standaloneSetup(
|
||||
new ProcessModelController(repositoryService, runtimeService, validator)).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_还原中文原key与剥除incoming_outgoing后部署XML无残留净化id且disableSchemaValidation() throws Exception {
|
||||
Model m = Mockito.mock(Model.class);
|
||||
when(m.getName()).thenReturn("总包合同交底");
|
||||
when(m.getKey()).thenReturn("总包合同交底"); // 中文原 key(from-procdef 时存,发布资源名/还原目标)
|
||||
when(m.getMetaInfo()).thenReturn(DRAFT_META_INFO);
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// 校验器无 ERROR → 放行部署。
|
||||
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
|
||||
when(validator.validate(any())).thenReturn(List.of());
|
||||
|
||||
// 部署链 mock:disableSchemaValidation().name().addString().deploy()。
|
||||
DeploymentBuilder db = Mockito.mock(DeploymentBuilder.class);
|
||||
when(repositoryService.createDeployment()).thenReturn(db);
|
||||
when(db.disableSchemaValidation()).thenReturn(db);
|
||||
when(db.name(any())).thenReturn(db);
|
||||
when(db.addString(anyString(), anyString())).thenReturn(db);
|
||||
Deployment dep = Mockito.mock(Deployment.class);
|
||||
when(dep.getId()).thenReturn("dep-1");
|
||||
when(db.deploy()).thenReturn(dep);
|
||||
ProcessDefinition deployed = Mockito.mock(ProcessDefinition.class);
|
||||
when(deployed.getKey()).thenReturn("总包合同交底");
|
||||
when(deployed.getVersion()).thenReturn(2);
|
||||
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.deploymentId("dep-1")).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.singleResult()).thenReturn(deployed);
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value(0))
|
||||
.andExpect(jsonPath("$.deploymentId").value("dep-1"))
|
||||
.andExpect(jsonPath("$.processKey").value("总包合同交底"))
|
||||
.andExpect(jsonPath("$.newVersion").value(2));
|
||||
|
||||
// disableSchemaValidation 必被调用(防有人回退成严格 XSD,咬 bpmn-js 默认命名空间输出→cvc-complex-type)。
|
||||
verify(db).disableSchemaValidation();
|
||||
// 捕获部署 XML:属性位还原为中文原 key/流 id,incoming/outgoing 文本引用剥除 → 全程无残留净化 id。
|
||||
ArgumentCaptor<String> deployXml = ArgumentCaptor.forClass(String.class);
|
||||
verify(db).addString(eq("总包合同交底.bpmn20.xml"), deployXml.capture());
|
||||
String xml = deployXml.getValue();
|
||||
org.junit.jupiter.api.Assertions.assertTrue(xml.contains("id=\"总包合同交底\""), xml);
|
||||
org.junit.jupiter.api.Assertions.assertTrue(xml.contains("id=\"流转1\""), xml);
|
||||
org.junit.jupiter.api.Assertions.assertTrue(xml.contains("id=\"流转2\""), xml);
|
||||
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("n1a2b3c"), "残留净化 process id: " + xml);
|
||||
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("nflow1"), "残留净化流 id(incoming/outgoing 未剥除): " + xml);
|
||||
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("nflow2"), "残留净化流 id(incoming/outgoing 未剥除): " + xml);
|
||||
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("<incoming>"), "incoming 元素未剥除: " + xml);
|
||||
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("<outgoing>"), "outgoing 元素未剥除: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_ProcessValidator_ERROR级返422带明细且不部署() throws Exception {
|
||||
Model m = Mockito.mock(Model.class);
|
||||
// metaInfo 默认 null → 无 idMap(新建流程分支,不还原);getKey 在 ERROR 返回前不会被读,不 stub 免 strict-stub。
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(VALID_BPMN.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
ValidationError err = new ValidationError();
|
||||
err.setActivityId("taskA");
|
||||
err.setProblem("flowable-usertask-no-assignment");
|
||||
err.setDefaultDescription("用户任务无办理人");
|
||||
err.setWarning(false);
|
||||
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
|
||||
when(validator.validate(any())).thenReturn(List.of(err));
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.status").value(1))
|
||||
.andExpect(jsonPath("$.errors[0].activityId").value("taskA"))
|
||||
.andExpect(jsonPath("$.errors[0].problem").value("flowable-usertask-no-assignment"))
|
||||
.andExpect(jsonPath("$.errors[0].defaultDescription").value("用户任务无办理人"));
|
||||
|
||||
// ERROR 级校验失败 → 绝不部署。
|
||||
verify(repositoryService, never()).createDeployment();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_ProcessValidator仅WARNING放行部署() throws Exception {
|
||||
Model m = Mockito.mock(Model.class);
|
||||
when(m.getName()).thenReturn("新流程");
|
||||
when(m.getKey()).thenReturn("newproc");
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(VALID_BPMN.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
ValidationError warn = new ValidationError();
|
||||
warn.setActivityId("taskA");
|
||||
warn.setProblem("some-warning");
|
||||
warn.setWarning(true);
|
||||
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
|
||||
when(validator.validate(any())).thenReturn(List.of(warn));
|
||||
|
||||
DeploymentBuilder db = Mockito.mock(DeploymentBuilder.class);
|
||||
when(repositoryService.createDeployment()).thenReturn(db);
|
||||
when(db.disableSchemaValidation()).thenReturn(db);
|
||||
when(db.name(any())).thenReturn(db);
|
||||
when(db.addString(anyString(), anyString())).thenReturn(db);
|
||||
Deployment dep = Mockito.mock(Deployment.class);
|
||||
when(dep.getId()).thenReturn("dep-2");
|
||||
when(db.deploy()).thenReturn(dep);
|
||||
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.deploymentId("dep-2")).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.singleResult()).thenReturn(null); // 查不到也不炸:回退 model.key/0
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value(0))
|
||||
.andExpect(jsonPath("$.deploymentId").value("dep-2"))
|
||||
.andExpect(jsonPath("$.processKey").value("newproc"))
|
||||
.andExpect(jsonPath("$.newVersion").value(0));
|
||||
|
||||
// 仅 WARNING → 放行:部署照常发生。
|
||||
verify(db).deploy();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_草稿不存在返404不部署() throws Exception {
|
||||
when(repositoryService.getModel("nope")).thenReturn(null);
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(post("/api/flow/models/nope/deploy"))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$.status").value(1));
|
||||
|
||||
verify(repositoryService, never()).createDeployment();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 影响摘要_还原后解析processKey返当前版本与运行实例数() throws Exception {
|
||||
Model m = Mockito.mock(Model.class);
|
||||
// processKey 取自还原后 XML 的 <process id>(=总包合同交底),不读 model.getKey → 不 stub 免 strict-stub。
|
||||
when(m.getMetaInfo()).thenReturn(DRAFT_META_INFO);
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
ProcessDefinition latest = Mockito.mock(ProcessDefinition.class);
|
||||
when(latest.getVersion()).thenReturn(3);
|
||||
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.processDefinitionKey("总包合同交底")).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.latestVersion()).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.singleResult()).thenReturn(latest);
|
||||
|
||||
RuntimeService runtimeService = Mockito.mock(RuntimeService.class);
|
||||
ProcessInstanceQuery piq = Mockito.mock(ProcessInstanceQuery.class);
|
||||
when(runtimeService.createProcessInstanceQuery()).thenReturn(piq);
|
||||
when(piq.processDefinitionKey("总包合同交底")).thenReturn(piq);
|
||||
when(piq.count()).thenReturn(5L);
|
||||
|
||||
MockMvc localMvc = deployMvc(runtimeService, Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(get("/api/flow/models/m1/impact"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.processKey").value("总包合同交底"))
|
||||
.andExpect(jsonPath("$.currentVersion").value(3))
|
||||
.andExpect(jsonPath("$.runningInstances").value(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 影响摘要_草稿不存在返404() throws Exception {
|
||||
when(repositoryService.getModel("nope")).thenReturn(null);
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(get("/api/flow/models/nope/impact"))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$.status").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_非双射idMap_restore_fail_fast返422不部署() throws Exception {
|
||||
// metaInfo 的 eip4IdMap 两个中文原 id 映射到同一净化 id(n1)→restore 反转检测到非双射抛 IllegalArgumentException
|
||||
// →deploy catch→422,绝不部署(损坏映射还原会指错 key)。
|
||||
Model m = Mockito.mock(Model.class);
|
||||
when(m.getMetaInfo()).thenReturn("{\"eip4IdMap\":{\"总包合同交底\":\"n1\",\"其他流程\":\"n1\"}}");
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.status").value(1))
|
||||
.andExpect(jsonPath("$.msg").isNotEmpty());
|
||||
|
||||
verify(repositoryService, never()).createDeployment();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_存量草稿metaInfo缺eip4IdMap_fail_fast返422不部署() throws Exception {
|
||||
// I1 坏 key 地雷:from-procdef 标记(sourceProcDefId/originalKey)在但 eip4IdMap 键丢了→editorSource 是净化 nXXX
|
||||
// 却无从还原→绝不能静默塌成「空 idMap 跳过还原」部署出 key=nXXX(违 D7)→resolveIdMap fail-fast→422 不部署。
|
||||
Model m = Mockito.mock(Model.class);
|
||||
when(m.getMetaInfo()).thenReturn("{\"sourceProcDefId\":\"def-1\",\"originalKey\":\"总包合同交底\"}");
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.status").value(1))
|
||||
.andExpect(jsonPath("$.msg").isNotEmpty());
|
||||
|
||||
verify(repositoryService, never()).createDeployment();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_metaInfo解析失败_fail_fast返422不部署() throws Exception {
|
||||
// 非空 metaInfo 却是坏 JSON:无从确认是不是存量草稿→宁拒不发(可能的坏 key)→resolveIdMap fail-fast→422 不部署。
|
||||
Model m = Mockito.mock(Model.class);
|
||||
when(m.getMetaInfo()).thenReturn("{坏JSON不可解析");
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.status").value(1));
|
||||
|
||||
verify(repositoryService, never()).createDeployment();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_存量草稿eip4IdMap为空_全ASCII流程不误拒正常部署() throws Exception {
|
||||
// 防 I1 修过头:from-procdef 的全 ASCII 存量流程 sanitize 出空 eip4IdMap {}(present),editorSource 本就是 ASCII key,
|
||||
// 无需还原→eip4IdMap 存在(空)即「可用」,不该被 fail-fast 误拒→正常部署。
|
||||
Model m = Mockito.mock(Model.class);
|
||||
when(m.getName()).thenReturn("ascii流程");
|
||||
when(m.getKey()).thenReturn("asciiKey");
|
||||
when(m.getMetaInfo())
|
||||
.thenReturn("{\"eip4IdMap\":{},\"sourceProcDefId\":\"def-1\",\"originalKey\":\"asciiKey\"}");
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(VALID_BPMN.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
|
||||
when(validator.validate(any())).thenReturn(List.of());
|
||||
|
||||
DeploymentBuilder db = Mockito.mock(DeploymentBuilder.class);
|
||||
when(repositoryService.createDeployment()).thenReturn(db);
|
||||
when(db.disableSchemaValidation()).thenReturn(db);
|
||||
when(db.name(any())).thenReturn(db);
|
||||
when(db.addString(anyString(), anyString())).thenReturn(db);
|
||||
Deployment dep = Mockito.mock(Deployment.class);
|
||||
when(dep.getId()).thenReturn("dep-3");
|
||||
when(db.deploy()).thenReturn(dep);
|
||||
ProcessDefinition deployed = Mockito.mock(ProcessDefinition.class);
|
||||
when(deployed.getKey()).thenReturn("p1");
|
||||
when(deployed.getVersion()).thenReturn(1);
|
||||
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.deploymentId("dep-3")).thenReturn(processDefinitionQuery);
|
||||
when(processDefinitionQuery.singleResult()).thenReturn(deployed);
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value(0))
|
||||
.andExpect(jsonPath("$.processKey").value("p1"));
|
||||
|
||||
verify(db).deploy();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_editorSource含DOCTYPE_字节级XXE守卫返422不部署() throws Exception {
|
||||
// deploy 路径自带的字节级 DOCTYPE 守卫(还原后 XML 再过一道):即便存储的 editorSource 含 DOCTYPE(理论不该,
|
||||
// 因写入端已拒),部署也在解析前拒,绝不部署。
|
||||
Model m = Mockito.mock(Model.class);
|
||||
// metaInfo 默认 null→真·新建分支,resolveIdMap 返空,prepareDeployXml 剥除+空还原=原样→deployXml 仍含 DOCTYPE。
|
||||
when(repositoryService.getModel("m1")).thenReturn(m);
|
||||
when(repositoryService.getModelEditorSource("m1"))
|
||||
.thenReturn(DOCTYPE_XML.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
|
||||
localMvc.perform(post("/api/flow/models/m1/deploy"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.status").value(1));
|
||||
|
||||
verify(repositoryService, never()).createDeployment();
|
||||
}
|
||||
|
||||
/** 把任意字符串编成 JSON 字符串字面量(转义引号/反斜杠/换行),用于拼请求体。 */
|
||||
private static String jsonString(String s) {
|
||||
StringBuilder sb = new StringBuilder("\"");
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Flyway 迁移 V4:在线流程 Modeler 发布审计表(sys_flow_deploy_audit)。
|
||||
-- 记录每次草稿→流程定义部署:谁(operator)/何时(deployed_at)/发布了哪个草稿(model_id)/产生的部署(deployment_id)/
|
||||
-- 流程 key(可能中文,如「总包合同交底」)+新版本号。供合规审计与发布追溯(D2 同人确认部署的审计要求)。
|
||||
-- 平台表(非引擎表 act_re_*),走 Flyway;写入收口网关 FlowDeployAuditService。
|
||||
-- 幂等:配合 baseline-on-migrate,既有库已有此表也安全。
|
||||
CREATE TABLE IF NOT EXISTS sys_flow_deploy_audit (
|
||||
id bigserial NOT NULL,
|
||||
model_id varchar(64),
|
||||
deployment_id varchar(64),
|
||||
process_key varchar(255),
|
||||
new_version integer,
|
||||
operator varchar(64),
|
||||
deployed_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT pk_sys_flow_deploy_audit PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
-- 按流程 key + 时间倒查发布历史(某流程被谁何时发布过哪些版本)。
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_flow_deploy_audit_key ON sys_flow_deploy_audit (process_key, deployed_at);
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.eip4.platform.flowgateway.aggregate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 流程发布审计:每次草稿→流程定义部署成功后,记一行 {@code sys_flow_deploy_audit}
|
||||
* (谁 operator / 何时 deployed_at / 发布了哪个草稿 model_id / 产生的 deployment_id / 流程 key + 新版本号),
|
||||
* 供合规审计与发布追溯(D2 同人确认部署的审计要求)。表由 Flyway V4 建(平台表,非引擎表)。
|
||||
*
|
||||
* <p><b>为何是 @Service 而非控制器直查</b>:{@code @RestController} 直持 {@link JdbcTemplate} 触架构棘轮
|
||||
* ({@code 控制器不得新增直用JdbcTemplate}),审计 INSERT 与字段抽取收口到本 Service。</p>
|
||||
*
|
||||
* <p><b>旁路写、不反噬部署</b>:本记录发生在下游部署<b>已成功</b>之后。写审计失败(如库抖动)绝不能让整个
|
||||
* 发布请求变 500——那会误导用户以为发布失败而重试,产生重复部署。故 {@link #record} 就地吞异常记 error,
|
||||
* 不上抛。审计缺失可事后追查,重复部署不可逆。</p>
|
||||
*/
|
||||
@Service
|
||||
public class FlowDeployAuditService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FlowDeployAuditService.class);
|
||||
|
||||
static final String INSERT_SQL =
|
||||
"INSERT INTO sys_flow_deploy_audit (model_id, deployment_id, process_key, new_version, operator) "
|
||||
+ "VALUES (?, ?, ?, ?, ?)";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public FlowDeployAuditService(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从下游 deploy 结果 Map 抽 {@code deploymentId/processKey/newVersion} 落审计行。
|
||||
*
|
||||
* @param modelId 被发布的草稿 id
|
||||
* @param deployResult flowable-service deploy 返回体({status,deploymentId,processKey,newVersion})
|
||||
* @param operator 操作者(= principal.userId(),超管门已保证非空)
|
||||
*/
|
||||
public void record(String modelId, Map<String, Object> deployResult, String operator) {
|
||||
String deploymentId = str(deployResult, "deploymentId");
|
||||
String processKey = str(deployResult, "processKey");
|
||||
Integer newVersion = intOf(deployResult, "newVersion");
|
||||
try {
|
||||
jdbcTemplate.update(INSERT_SQL, modelId, deploymentId, processKey, newVersion, operator);
|
||||
} catch (RuntimeException e) {
|
||||
// 部署已成功,审计是旁路记录:写失败不回滚不上抛(否则用户误判发布失败→重试→重复部署)。
|
||||
log.error("[发布审计] 写入 sys_flow_deploy_audit 失败(部署已成功,不回滚) modelId={} operator={}: {}",
|
||||
modelId, operator, e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private static String str(Map<String, Object> m, String key) {
|
||||
Object v = m == null ? null : m.get(key);
|
||||
return v == null ? null : String.valueOf(v);
|
||||
}
|
||||
|
||||
private static Integer intOf(Map<String, Object> m, String key) {
|
||||
Object v = m == null ? null : m.get(key);
|
||||
return v instanceof Number n ? n.intValue() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package com.eip4.platform.flowgateway.aggregate;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* 发布门 EIP4 <b>语义</b>校验(网关层):flowable-service 的 {@code ProcessValidator} 只做引擎<b>结构</b>校验
|
||||
* (节点连通/网关/多实例配置),本校验器补 EIP4 特有的三项运行期正确性约束,返回 {@code List<String>} 错误清单
|
||||
* (空=通过),供网关 deploy 端点 fail-fast 返 422 且<b>不部署</b>。
|
||||
*
|
||||
* <ol>
|
||||
* <li><b>办理人 / 会签内嵌 JSON</b>:userTask 的 {@code activiti:candidateUsers} 与多实例
|
||||
* {@code activiti:collection}——凡以 EIP4 handler 前缀
|
||||
* ({@code candidateUsersHandler.getCandidateUsers} / {@code multiInstanceUsersHandler.getUsers})开头者,
|
||||
* 内容段花括号全角【】→半角后必须 <b>JSON 可解析</b>、{@code items} <b>非空</b>({@code items:[]} 的 MI
|
||||
* collection 运行期会炸——仅「JSON 可解析 + type 白名单」不够,T2.4 评审补充)、且每个
|
||||
* {@code items[].type} ∈ {@link #TYPE_WHITELIST}。非 handler 前缀的裸值(如 {@code ${var}} / 逗号分隔用户)
|
||||
* 非 EIP4 codec 产物,放行不套 JSON 白名单(避免误拒合法 Flowable 裸值)。</li>
|
||||
* <li><b>formKey 存在性</b>:userTask 的 {@code activiti:formKey}(= view_wftemplate_id)若存在,必须命中
|
||||
* {@code view_wftemplate}({@link JdbcTemplate} count 查询);读库异常按全站降级惯例<b>放行</b>该项
|
||||
* (不因基础设施抖动阻断部署,引用完整性检查跳过并记告警)。</li>
|
||||
* <li><b>会签完成条件</b>:{@code completionCondition} 允许「三预设 或 保留的自定义非空表达式」
|
||||
* (T2.4 已实现自定义保留态,别把存量自定义条件拒了)——匹配预设正则则通过,非预设但<b>非空</b>放行
|
||||
* (仅记 info 告警不阻断),仅<b>空白</b>视为错误。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p><b>XML 解析</b>:照 {@link WfTemplateService#parseXml} 钉 JDK 内置解析器
|
||||
* (防 platform-report 带入的上古 xerces 击穿 JAXP 1.4),禁 DOCTYPE / 外部实体(XXE 门)。非命名空间感知,
|
||||
* 按<b>本地名</b>匹配元素/属性(兼容 bpmn-js 默认命名空间输出与 {@code activiti:}/{@code flowable:} 前缀)。</p>
|
||||
*
|
||||
* <p><b>为何是 @Service 而非控制器直查</b>:{@code @RestController} 直持 {@link JdbcTemplate} 触架构棘轮
|
||||
* ({@code 控制器不得新增直用JdbcTemplate});且 XML 解析 + JSON 白名单逻辑本就该收口成可独立单测的领域件。</p>
|
||||
*/
|
||||
@Service
|
||||
public class ModelSemanticValidator {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ModelSemanticValidator.class);
|
||||
|
||||
/** 办理人 handler 表达式前缀,逐字对齐 {@code BasePropertiesConverter} CANDIDATESERVICE(:34)。 */
|
||||
private static final String CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
|
||||
/** 会签 handler 表达式前缀,逐字对齐 {@code BasePropertiesConverter} MULTIINSTANCESERVICE(:35)。 */
|
||||
private static final String MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'";
|
||||
private static final String SUFFIX = "')}";
|
||||
|
||||
/**
|
||||
* 办理人/会签项合法 type。<b>权威集 = flowable-service {@code WfTypes} 的 16 个配置类型 + {@code OrgDirectoryJdbc}
|
||||
* 运行期分派</b>(非 BasePropertiesConverter——它只 setType,不做白名单)。网关不依赖 flowable-service 故此处复刻
|
||||
* 常量值;<b>WfTypes 新增类型时两处必须同步</b>。此前只列 10 种会 422 误拒含 {@code initiatorDepartManager}
|
||||
* (实测 24 文档)/{@code fixedDimension}(12 文档)等运行期完全支持的存量流程(from-procdef 载入→编辑无关节点→发布)。
|
||||
*/
|
||||
static final Set<String> TYPE_WHITELIST = Set.of(
|
||||
"user", "roles", "depart", "position", "initiator",
|
||||
"initiatorDepartManager", "initiatorLeader", "initiatorSubordinate", "initiatorDepart",
|
||||
"sameToTask", "beforeTaskLeader", "beforeTaskDepartManager",
|
||||
"fixedDimension", "formSpecifiedDimension", "projectRoleType", "scriptUser");
|
||||
|
||||
/** 会签完成条件三预设(与 Eip4Panel.tsx:60-77 逐字一致):全票 / 过半 / 指定数。 */
|
||||
private static final Pattern COMPLETION_ALL =
|
||||
Pattern.compile("^\\$\\{nrOfCompletedInstances/nrOfInstances==1\\}$");
|
||||
private static final Pattern COMPLETION_MAJORITY =
|
||||
Pattern.compile("^\\$\\{nrOfCompletedInstances/nrOfInstances>0\\.5\\}$");
|
||||
private static final Pattern COMPLETION_COUNT =
|
||||
Pattern.compile("^\\$\\{nrOfCompletedInstances>=\\d+\\}$");
|
||||
|
||||
/** formKey 存在性查询(bpchar 列比较忽略尾部补白,传裸 UUID 即可,对齐 WfTemplateService.readXml)。 */
|
||||
static final String FORMKEY_EXISTS_SQL =
|
||||
"SELECT count(*) FROM view_wftemplate WHERE view_wftemplate_id = ?";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
public ModelSemanticValidator(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
/** 校验 bpmn XML,返回错误清单(空=通过)。任何解析异常归一为一条「解析失败」错误,不抛。 */
|
||||
public List<String> validate(String bpmnXml) {
|
||||
List<String> errors = new ArrayList<>();
|
||||
if (bpmnXml == null || bpmnXml.isBlank()) {
|
||||
errors.add("BPMN 源为空,无法校验");
|
||||
return errors;
|
||||
}
|
||||
Document doc;
|
||||
try {
|
||||
doc = parse(bpmnXml);
|
||||
} catch (Exception e) {
|
||||
// 含 DOCTYPE(XXE 门 disallow-doctype-decl 抛)/非良构 XML → 统一拒;细节仅进日志,不回显。
|
||||
log.warn("[发布语义] BPMN 解析失败: {}", e.toString());
|
||||
errors.add("BPMN 解析失败,无法校验语义");
|
||||
return errors;
|
||||
}
|
||||
|
||||
for (Element userTask : elementsByLocalName(doc, "userTask")) {
|
||||
String label = nodeLabel(userTask);
|
||||
validateHandlerJson(attrByLocalName(userTask, "candidateUsers"), CANDIDATE_PREFIX,
|
||||
label, "办理人", errors);
|
||||
validateFormKey(attrByLocalName(userTask, "formKey"), label, errors);
|
||||
}
|
||||
|
||||
for (Element mi : elementsByLocalName(doc, "multiInstanceLoopCharacteristics")) {
|
||||
String label = enclosingUserTaskLabel(mi);
|
||||
validateHandlerJson(attrByLocalName(mi, "collection"), MULTI_PREFIX, label, "会签人员", errors);
|
||||
validateCompletionCondition(mi, label, errors);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 校验分项
|
||||
|
||||
/**
|
||||
* 办理人/会签内嵌 JSON 校验:仅当值以 {@code prefix}(EIP4 handler)开头才校验;解析失败/items 空/type 非白名单
|
||||
* 各追加一条错误(type 逐项报,一个节点多个坏 type 出多条)。
|
||||
*/
|
||||
private void validateHandlerJson(String value, String prefix, String label, String role, List<String> errors) {
|
||||
if (value == null || value.isBlank() || !value.startsWith(prefix)) {
|
||||
return; // 无配置 或 非 EIP4 handler 裸值:非本校验器职责
|
||||
}
|
||||
if (!value.endsWith(SUFFIX)) {
|
||||
errors.add("节点『" + label + "』的" + role + "表达式格式错误(缺尾部 " + SUFFIX + ")");
|
||||
return;
|
||||
}
|
||||
String content = value.substring(prefix.length(), value.length() - SUFFIX.length());
|
||||
// 全角【】→半角(对齐 CandidateUsersHandler:54 运行期还原),再 JSON 解析。
|
||||
String json = content.replace("【", "{").replace("】", "}");
|
||||
JsonNode root;
|
||||
try {
|
||||
root = objectMapper.readTree(json);
|
||||
} catch (Exception e) {
|
||||
errors.add("节点『" + label + "』的" + role + "配置 JSON 无法解析");
|
||||
return;
|
||||
}
|
||||
JsonNode items = root.get("items");
|
||||
if (items == null || !items.isArray() || items.isEmpty()) {
|
||||
errors.add("节点『" + label + "』的" + role + "为空(items 为空),运行期会异常");
|
||||
return;
|
||||
}
|
||||
for (JsonNode item : items) {
|
||||
JsonNode type = item.get("type");
|
||||
if (type == null || !type.isTextual() || !TYPE_WHITELIST.contains(type.asText())) {
|
||||
errors.add("节点『" + label + "』的" + role + "含非法 type:"
|
||||
+ (type == null || type.isNull() ? "(缺失)" : type.asText()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** formKey 存在性:非空则查 view_wftemplate;不存在报错,读库异常降级放行(记告警)。 */
|
||||
private void validateFormKey(String formKey, String label, List<String> errors) {
|
||||
if (formKey == null || formKey.isBlank()) {
|
||||
return;
|
||||
}
|
||||
String key = formKey.trim();
|
||||
try {
|
||||
Integer c = jdbcTemplate.queryForObject(FORMKEY_EXISTS_SQL, Integer.class, key);
|
||||
if (c == null || c == 0) {
|
||||
errors.add("节点『" + label + "』的表单 formKey 不存在于模板库(view_wftemplate):" + key);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// 读库抖动不阻断发布(全站降级惯例);该项引用完整性检查跳过并记告警。
|
||||
log.warn("[发布语义] formKey 存在性校验读库降级(跳过该项) formKey={}: {}", key, e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** 会签完成条件:present+空白=错误;非空放行(非预设仅记 info 告警,保留 T2.4 自定义态)。 */
|
||||
private void validateCompletionCondition(Element mi, String label, List<String> errors) {
|
||||
Element cc = firstChildByLocalName(mi, "completionCondition");
|
||||
if (cc == null) {
|
||||
return; // 无完成条件:多实例全部完成才结束,合法。
|
||||
}
|
||||
String body = cc.getTextContent();
|
||||
if (body == null || body.isBlank()) {
|
||||
errors.add("节点『" + label + "』的会签完成条件为空");
|
||||
return;
|
||||
}
|
||||
String trimmed = body.trim();
|
||||
if (!isPresetCompletion(trimmed)) {
|
||||
log.info("[发布语义] 节点『{}』会签完成条件为自定义表达式(放行,保留 T2.4 自定义态): {}", label, trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPresetCompletion(String body) {
|
||||
return COMPLETION_ALL.matcher(body).matches()
|
||||
|| COMPLETION_MAJORITY.matcher(body).matches()
|
||||
|| COMPLETION_COUNT.matcher(body).matches();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- DOM 小工具(按本地名,兼容前缀/默认命名空间)
|
||||
|
||||
private static Document parse(String xml) throws Exception {
|
||||
DocumentBuilderFactory f = newJdkDbf();
|
||||
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
f.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
f.setExpandEntityReferences(false);
|
||||
DocumentBuilder b = f.newDocumentBuilder();
|
||||
return b.parse(new InputSource(new StringReader(xml)));
|
||||
}
|
||||
|
||||
/** JDK 内置 DocumentBuilderFactory(钉实现类,防 platform-report 上古 xerces 击穿;对齐 WfTemplateService)。 */
|
||||
private static DocumentBuilderFactory newJdkDbf() {
|
||||
try {
|
||||
return DocumentBuilderFactory.newInstance(
|
||||
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", null);
|
||||
} catch (Throwable t) {
|
||||
return DocumentBuilderFactory.newInstance();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Element> elementsByLocalName(Document doc, String localName) {
|
||||
NodeList all = doc.getElementsByTagName("*");
|
||||
List<Element> out = new ArrayList<>();
|
||||
for (int i = 0; i < all.getLength(); i++) {
|
||||
Node n = all.item(i);
|
||||
if (n.getNodeType() == Node.ELEMENT_NODE && localName.equals(localName(n.getNodeName()))) {
|
||||
out.add((Element) n);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 取元素下第一个指定本地名的直接子元素。 */
|
||||
private static Element firstChildByLocalName(Element parent, String localName) {
|
||||
NodeList children = parent.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
Node n = children.item(i);
|
||||
if (n.getNodeType() == Node.ELEMENT_NODE && localName.equals(localName(n.getNodeName()))) {
|
||||
return (Element) n;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 按本地名取属性值(兼容 {@code activiti:}/{@code flowable:} 前缀与无前缀),无则 null。 */
|
||||
private static String attrByLocalName(Element e, String localName) {
|
||||
NamedNodeMap attrs = e.getAttributes();
|
||||
for (int i = 0; i < attrs.getLength(); i++) {
|
||||
Node a = attrs.item(i);
|
||||
if (localName.equals(localName(a.getNodeName()))) {
|
||||
String v = a.getNodeValue();
|
||||
return v == null || v.isEmpty() ? null : v;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 上溯到最近的 userTask 祖先取其名(会签 collection/完成条件的节点上下文)。 */
|
||||
private static String enclosingUserTaskLabel(Element mi) {
|
||||
Node p = mi.getParentNode();
|
||||
while (p != null && p.getNodeType() == Node.ELEMENT_NODE) {
|
||||
if ("userTask".equals(localName(p.getNodeName()))) {
|
||||
return nodeLabel((Element) p);
|
||||
}
|
||||
p = p.getParentNode();
|
||||
}
|
||||
return "会签节点";
|
||||
}
|
||||
|
||||
private static String nodeLabel(Element e) {
|
||||
String name = attrByLocalName(e, "name");
|
||||
if (name != null && !name.isBlank()) {
|
||||
return name;
|
||||
}
|
||||
String id = attrByLocalName(e, "id");
|
||||
return id != null && !id.isBlank() ? id : "(未命名节点)";
|
||||
}
|
||||
|
||||
private static String localName(String qname) {
|
||||
int c = qname.indexOf(':');
|
||||
return c < 0 ? qname : qname.substring(c + 1);
|
||||
}
|
||||
}
|
||||
@@ -8,17 +8,33 @@ import org.springframework.http.HttpStatusCode;
|
||||
* <p>与 {@link FlowServiceUnavailableException} 区分:那个是"引擎进程不可达"(→ 503);
|
||||
* 这个是"引擎在线但拒绝了这次操作"(原状态码透传给调用方,保留 Flowable 语义,
|
||||
* 如挂起拒办 409、参数错 400)。
|
||||
*
|
||||
* <p><b>responseBody(可空)</b>:携带下游原始响应体,供 {@code FlowGatewayExceptionHandler} 透传结构化错误
|
||||
* ——如流程发布下游 422 的 {@code {errors:[{activityId,problem,defaultDescription}]}}(引擎 ProcessValidator 结构校验)
|
||||
* 需并入网关响应,与网关语义校验 422 的顶层 {@code errors} 契约统一(T3.2 评审 I-2:此前只留状态码丢体,
|
||||
* 结构化错误到不了前端)。旧两参构造(无体)保留,非发布路径不受影响。
|
||||
*/
|
||||
public class FlowRemoteException extends RuntimeException {
|
||||
|
||||
private final HttpStatusCode status;
|
||||
private final String responseBody;
|
||||
|
||||
public FlowRemoteException(HttpStatusCode status, String message) {
|
||||
this(status, message, null);
|
||||
}
|
||||
|
||||
public FlowRemoteException(HttpStatusCode status, String message, String responseBody) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
|
||||
public HttpStatusCode getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
/** 下游原始响应体(可空);供 handler 解析并透传结构化 errors。 */
|
||||
public String getResponseBody() {
|
||||
return responseBody;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,6 +329,34 @@ public class FlowableClient {
|
||||
return delete("删草稿", "/api/flow/models/{id}", Map.class, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布草稿为流程定义(T3.2)。对应 flowable-service {@code POST /api/flow/models/{id}/deploy},无请求体,
|
||||
* 返回 {@code {status:0,deploymentId,processKey,newVersion}};下游 ProcessValidator 拒 → 422 /
|
||||
* 草稿不存在 → 404 → {@link FlowRemoteException} 透传。{@code id} 走 uri 模板变量严格编码(禁字符串拼接)。
|
||||
*
|
||||
* <p><b>幂等性</b>:部署<b>非幂等</b>(每次 deploy 产生新版本)——{@link #execute} 的连接级重试存在重复部署窗口
|
||||
* (产生 vN 与 vN+1 内容相同的冗余版本)。接受该风险:①网关↔flowable-service 同机链路,连接级瞬时故障概率极低;
|
||||
* ②冗余新版本无害(运行中实例留旧版本,新起用 latest);③语义级 4xx/5xx(校验拒)由 {@link #execute} 保证
|
||||
* <b>绝不</b>重试,故校验失败无重复窗口。发布前网关 {@code ModelSemanticValidator} 已挡住绝大多数坏草稿。</p>
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Object> deployModel(String id) {
|
||||
return post("发布草稿", "/api/flow/models/{id}/deploy", Map.of(), Map.class, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布影响摘要(T3.2)。对应 flowable-service {@code GET /api/flow/models/{id}/impact},返回
|
||||
* {@code {processKey,currentVersion,runningInstances}};草稿不存在 → 404 {@link FlowRemoteException} 透传。
|
||||
* {@code id} 走 uri 模板变量严格编码(禁字符串拼接)。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Object> modelImpact(String id) {
|
||||
return execute("发布影响", () -> restClient.get()
|
||||
.uri("/api/flow/models/{id}/impact", id)
|
||||
.retrieve()
|
||||
.body(Map.class));
|
||||
}
|
||||
|
||||
/** 按发起人查询历史流程实例。对应 flowable-service {@code GET /api/flow/process/started}。 */
|
||||
public List<ProcessInstanceDto> started(String startedBy, int firstResult, int maxResults) {
|
||||
return execute("发起流程列表", () -> restClient.get()
|
||||
@@ -402,6 +430,20 @@ public class FlowableClient {
|
||||
.body(respType));
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 转发(uri 模板 + 变量版):{@code uriTemplate}+{@code uriVars} 走 RestClient 严格编码
|
||||
* ({@code id} 作 uri 变量,禁字符串拼接)。谓词固定 POST 但路径含变量段(如 {@code /models/{id}/deploy})。
|
||||
* 幂等性/重试语义与四参 {@link #post(String, String, Object, Class)} 一致(非幂等,连接级重试有重复窗口);
|
||||
* 具体端点的重复风险由调用方 javadoc 声明。四参调用因固定元数优先绑定,不与本重载歧义。
|
||||
*/
|
||||
private <T> T post(String op, String uriTemplate, Object body, Class<T> respType, Object... uriVars) {
|
||||
return execute(op, () -> restClient.post()
|
||||
.uri(uriTemplate, uriVars)
|
||||
.body(body == null ? Map.of() : body)
|
||||
.retrieve()
|
||||
.body(respType));
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT 转发(RestClient 无既有封装 → 照 {@link #post} 补)。{@code uriTemplate}+{@code uriVars} 走 RestClient
|
||||
* 严格编码({@code id} 作 uri 变量,禁字符串拼接);连接级重试 + 4xx/5xx 透传语义与 post 一致。
|
||||
@@ -448,10 +490,12 @@ public class FlowableClient {
|
||||
sleepBackoff();
|
||||
}
|
||||
} catch (RestClientResponseException e) {
|
||||
// 业务级:引擎在线但返回 4xx/5xx(如挂起拒办 409)——透传原状态码,绝不重试
|
||||
// 业务级:引擎在线但返回 4xx/5xx(如挂起拒办 409)——透传原状态码,绝不重试。
|
||||
// 携带原始响应体:发布下游 422 的结构化 errors(activityId/problem) 交 handler 并入网关响应(评审 I-2)。
|
||||
HttpStatusCode status = e.getStatusCode();
|
||||
log.debug("flowable-service {}调用返回业务状态 {}: {}", op, status, e.getMessage());
|
||||
throw new FlowRemoteException(status, "flowable-service " + op + "返回 " + status.value());
|
||||
throw new FlowRemoteException(status, "flowable-service " + op + "返回 " + status.value(),
|
||||
e.getResponseBodyAsString());
|
||||
}
|
||||
}
|
||||
// 重试耗尽仍连不上 —— 熔断降级为 503 语义
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package com.eip4.platform.flowgateway.web;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
@@ -9,6 +12,8 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import com.eip4.platform.flowgateway.client.FlowRemoteException;
|
||||
import com.eip4.platform.flowgateway.client.FlowServiceUnavailableException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* 流程网关异常 → 干净 HTTP 语义(只管本网关 client 抛出的两类异常,不拦其他)。
|
||||
@@ -17,12 +22,17 @@ import com.eip4.platform.flowgateway.client.FlowServiceUnavailableException;
|
||||
* <li>{@link FlowServiceUnavailableException}(引擎进程不可达,重试耗尽)→ <b>503</b>
|
||||
* Service Unavailable —— 待办聚合在引擎宕机/网络分区时返回明确的服务不可用语义,而非 500 堆栈。</li>
|
||||
* <li>{@link FlowRemoteException}(引擎在线但拒绝,如挂起拒办 409)→ <b>透传原状态码</b>,
|
||||
* 保留 Flowable 语义。</li>
|
||||
* 保留 Flowable 语义;若下游响应体带结构化 {@code errors} 数组(如发布 422 的引擎结构校验错误
|
||||
* {@code [{activityId,problem,defaultDescription}]}),<b>并入</b>网关响应顶层 {@code errors},
|
||||
* 与网关语义校验 422 的顶层 {@code errors} 契约统一(评审 I-2)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@RestControllerAdvice(basePackages = "com.eip4.platform.flowgateway")
|
||||
public class FlowGatewayExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FlowGatewayExceptionHandler.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@ExceptionHandler(FlowServiceUnavailableException.class)
|
||||
public ResponseEntity<Map<String, Object>> onUnavailable(FlowServiceUnavailableException e) {
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
@@ -34,10 +44,33 @@ public class FlowGatewayExceptionHandler {
|
||||
|
||||
@ExceptionHandler(FlowRemoteException.class)
|
||||
public ResponseEntity<Map<String, Object>> onRemote(FlowRemoteException e) {
|
||||
return ResponseEntity.status(e.getStatus())
|
||||
.body(Map.of(
|
||||
"status", e.getStatus().value(),
|
||||
"error", "FLOW_REMOTE_ERROR",
|
||||
"message", e.getMessage()));
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", e.getStatus().value());
|
||||
body.put("error", "FLOW_REMOTE_ERROR");
|
||||
body.put("message", e.getMessage());
|
||||
Object errors = extractErrors(e.getResponseBody());
|
||||
if (errors != null) {
|
||||
body.put("errors", errors);
|
||||
}
|
||||
return ResponseEntity.status(e.getStatus()).body(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从下游原始响应体抽结构化 {@code errors} 数组(非空才返回)。下游体非 JSON / 无 errors / 空数组 → null
|
||||
* (回原 FLOW_REMOTE_ERROR 信封,不加 errors 键)。防御性:解析失败静默降级,不让异常翻译再抛异常。
|
||||
*/
|
||||
private static Object extractErrors(String responseBody) {
|
||||
if (responseBody == null || responseBody.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode errors = MAPPER.readTree(responseBody).get("errors");
|
||||
if (errors != null && errors.isArray() && !errors.isEmpty()) {
|
||||
return MAPPER.convertValue(errors, Object.class);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.debug("下游响应体非 JSON 或无 errors,回原信封: {}", ex.toString());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.eip4.platform.flowgateway.web;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -17,6 +18,8 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eip4.platform.auth.security.AuthPrincipal;
|
||||
import com.eip4.platform.auth.security.EngineContextBinder;
|
||||
import com.eip4.platform.flowgateway.aggregate.FlowDeployAuditService;
|
||||
import com.eip4.platform.flowgateway.aggregate.ModelSemanticValidator;
|
||||
import com.eip4.platform.flowgateway.aggregate.WfTemplatePickerService;
|
||||
import com.eip4.platform.flowgateway.client.FlowableClient;
|
||||
|
||||
@@ -41,11 +44,17 @@ public class ProcessModelerController {
|
||||
|
||||
private final FlowableClient flowableClient;
|
||||
private final WfTemplatePickerService wfTemplatePickerService;
|
||||
private final ModelSemanticValidator semanticValidator;
|
||||
private final FlowDeployAuditService deployAuditService;
|
||||
|
||||
public ProcessModelerController(FlowableClient flowableClient,
|
||||
WfTemplatePickerService wfTemplatePickerService) {
|
||||
WfTemplatePickerService wfTemplatePickerService,
|
||||
ModelSemanticValidator semanticValidator,
|
||||
FlowDeployAuditService deployAuditService) {
|
||||
this.flowableClient = flowableClient;
|
||||
this.wfTemplatePickerService = wfTemplatePickerService;
|
||||
this.semanticValidator = semanticValidator;
|
||||
this.deployAuditService = deployAuditService;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 存量流程源载入(T1.6)
|
||||
@@ -158,6 +167,66 @@ public class ProcessModelerController {
|
||||
return ResponseEntity.ok(flowableClient.deleteModel(id));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 发布门(T3.2)
|
||||
|
||||
/**
|
||||
* <b>TOCTOU 已接受风险(评审 I-3)</b>:本端点先 {@link FlowableClient#getModel} 读草稿源做语义校验,再由下游
|
||||
* deploy 重新读 editorSource 部署——两次读之间存在并发 PUT 改写草稿的窗口(校验的是旧内容、部署的是新内容)。
|
||||
* v1 <b>接受</b>该风险,不做 content-hash 乐观锁 409:①发布是超管手动、低频、通常单人操作,并发改写窗口极窄;
|
||||
* ②非安全洞(超管门已限定调用者,下游 deploy 仍过引擎 ProcessValidator 结构校验兜底);③content-hash 409
|
||||
* 对 v1 过重(需前端拿版本号回传+冲突重试 UI)。与 {@link FlowableClient} 幂等段同风格声明,v2 有多人协同编辑
|
||||
* 需求再引入乐观锁。
|
||||
*/
|
||||
@Operation(summary = "发布草稿为流程定义(超管 + 语义校验门 + 审计)",
|
||||
description = "超管门 → 取草稿源 XML(FlowableClient.getModel)→ EIP4 语义校验"
|
||||
+ "(ModelSemanticValidator:办理人/会签内嵌 JSON items 非空+type 白名单、formKey 存在于 view_wftemplate、"
|
||||
+ "completionCondition 预设∪自定义)→ 有错返 422 {status:1,msg,errors} <b>不部署</b>;过则转发 flowable-service "
|
||||
+ "POST /api/flow/models/{id}/deploy(引擎 ProcessValidator 结构校验+id 还原中文原 key+部署)→ 成功后写"
|
||||
+ " sys_flow_deploy_audit(operator=principal.userId())→ 透传下游 {status,deploymentId,processKey,newVersion}。"
|
||||
+ "草稿不存在/源为空 → 404。非超管 403。")
|
||||
@PostMapping("/models/{id}/deploy")
|
||||
public ResponseEntity<Map<String, Object>> deploy(@AuthenticationPrincipal AuthPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
ResponseEntity<Map<String, Object>> denied = requireSuperAdmin(principal);
|
||||
if (denied != null) {
|
||||
return denied;
|
||||
}
|
||||
// 取草稿源 XML 供语义校验(办理人/会签 JSON、formKey 在草稿态即定,与部署时 id 还原无关)。
|
||||
Map<String, Object> model = flowableClient.getModel(id);
|
||||
String bpmnXml = (model != null && Boolean.TRUE.equals(model.get("found"))
|
||||
&& model.get("bpmnXml") instanceof String s) ? s : null;
|
||||
if (bpmnXml == null || bpmnXml.isBlank()) {
|
||||
return error(HttpStatus.NOT_FOUND, "草稿不存在或源为空: " + id);
|
||||
}
|
||||
// EIP4 语义校验门:非空错误清单 → 422 不部署(引擎结构校验在下游 deploy,二者互补)。
|
||||
List<String> errors = semanticValidator.validate(bpmnXml);
|
||||
if (!errors.isEmpty()) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", 1);
|
||||
body.put("msg", "流程语义校验未通过");
|
||||
body.put("errors", errors);
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(body);
|
||||
}
|
||||
// 转发部署(下游还原中文原 key + ProcessValidator 结构校验 + deploy)。
|
||||
Map<String, Object> result = flowableClient.deployModel(id);
|
||||
// 部署成功后旁路写审计(收口 @Service,避免 @RestController 直用 JdbcTemplate 触架构棘轮);写失败不反噬部署。
|
||||
deployAuditService.record(id, result, principal.userId());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
@Operation(summary = "发布影响摘要(超管)",
|
||||
description = "超管门后转发 flowable-service GET /api/flow/models/{id}/impact,返回"
|
||||
+ " {processKey,currentVersion,runningInstances} 供同人确认弹窗展示。草稿不存在 → 下游 404 透传。非超管 403。")
|
||||
@GetMapping("/models/{id}/impact")
|
||||
public ResponseEntity<Map<String, Object>> impact(@AuthenticationPrincipal AuthPrincipal principal,
|
||||
@PathVariable String id) {
|
||||
ResponseEntity<Map<String, Object>> denied = requireSuperAdmin(principal);
|
||||
if (denied != null) {
|
||||
return denied;
|
||||
}
|
||||
return ResponseEntity.ok(flowableClient.modelImpact(id));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- formKey 选择器数据源(T2.2)
|
||||
|
||||
@Operation(summary = "wftemplate 选择器数据源(超管)",
|
||||
@@ -184,9 +253,14 @@ public class ProcessModelerController {
|
||||
if (EngineContextBinder.isSystemAdmin(principal)) {
|
||||
return null;
|
||||
}
|
||||
return error(HttpStatus.FORBIDDEN, "仅系统管理员可用");
|
||||
}
|
||||
|
||||
/** 统一错误信封 {status:1,msg}(与全站网关端点逐字对齐)。 */
|
||||
private static ResponseEntity<Map<String, Object>> error(HttpStatus httpStatus, String msg) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", 1);
|
||||
body.put("msg", "仅系统管理员可用");
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
|
||||
body.put("msg", msg);
|
||||
return ResponseEntity.status(httpStatus).body(body);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.eip4.platform.flowgateway;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.eip4.platform.flowgateway.aggregate.FlowDeployAuditService;
|
||||
|
||||
/**
|
||||
* 部署审计 Service 单测:从 deploy 下游结果抽字段 INSERT sys_flow_deploy_audit;写库异常吞掉不反噬已成功的部署。
|
||||
* SQL 收口到本 @Service(@RestController 不得直用 JdbcTemplate,架构棘轮)。
|
||||
*/
|
||||
class FlowDeployAuditServiceTest {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
|
||||
private final FlowDeployAuditService service = new FlowDeployAuditService(jdbcTemplate);
|
||||
|
||||
@Test
|
||||
void record_从下游结果抽全字段INSERT() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("status", 0);
|
||||
result.put("deploymentId", "dep-9");
|
||||
result.put("processKey", "总包合同交底");
|
||||
result.put("newVersion", 4);
|
||||
|
||||
service.record("m1", result, "ADMIN");
|
||||
|
||||
// SQL 用 anyString()(照 WfTemplatePickerServiceTest 惯例,不耦合具体语句);断言抽出的字段值与顺序。
|
||||
verify(jdbcTemplate).update(anyString(),
|
||||
eq("m1"), eq("dep-9"), eq("总包合同交底"), eq(4), eq("ADMIN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void record_newVersion数字归一为Integer_processKey缺失传null() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("deploymentId", "dep-1");
|
||||
// 无 processKey/newVersion:抽为 null,不炸
|
||||
service.record("m2", result, "ADMIN");
|
||||
|
||||
verify(jdbcTemplate).update(anyString(),
|
||||
eq("m2"), eq("dep-1"), eq((Object) null), eq((Object) null), eq("ADMIN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void record_写库异常被吞不抛_部署已成功不回滚() {
|
||||
when(jdbcTemplate.update(anyString(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new DataAccessResourceFailureException("db down"));
|
||||
Map<String, Object> result = Map.of("deploymentId", "d", "processKey", "k", "newVersion", 1);
|
||||
|
||||
assertThatCode(() -> service.record("m3", result, "ADMIN")).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
@@ -430,4 +430,85 @@ class FlowableClientTest {
|
||||
.satisfies(e -> assertThat(((FlowRemoteException) e).getStatus().value()).isEqualTo(404));
|
||||
server.verify();
|
||||
}
|
||||
|
||||
// ---- 发布/影响转发(T3.2):POST /api/flow/models/{id}/deploy、GET /api/flow/models/{id}/impact ----
|
||||
|
||||
@Test
|
||||
void 发布草稿_POST_models_id_deploy_透传下游结果() {
|
||||
FlowGatewayProperties p = props();
|
||||
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
|
||||
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
|
||||
server.expect(ExpectedCount.once(), requestTo("http://localhost:8089/api/flow/models/m1/deploy"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess(
|
||||
"{\"status\":0,\"deploymentId\":\"dep-9\",\"processKey\":\"总包合同交底\",\"newVersion\":4}",
|
||||
MediaType.APPLICATION_JSON));
|
||||
FlowableClient client = new FlowableClient(builder.build(), p);
|
||||
|
||||
Map<String, Object> resp = client.deployModel("m1");
|
||||
|
||||
assertThat(resp).containsEntry("deploymentId", "dep-9").containsEntry("processKey", "总包合同交底")
|
||||
.containsEntry("newVersion", 4);
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布草稿_下游422透传FlowRemote且不重试() {
|
||||
FlowGatewayProperties p = props();
|
||||
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
|
||||
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
|
||||
server.expect(ExpectedCount.once(), // 业务错不重试(引擎 ProcessValidator 拒)
|
||||
requestTo("http://localhost:8089/api/flow/models/m1/deploy"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withStatus(HttpStatus.UNPROCESSABLE_ENTITY).body("流程校验未通过"));
|
||||
FlowableClient client = new FlowableClient(builder.build(), p);
|
||||
|
||||
assertThatThrownBy(() -> client.deployModel("m1"))
|
||||
.isInstanceOf(FlowRemoteException.class)
|
||||
.satisfies(e -> assertThat(((FlowRemoteException) e).getStatus().value()).isEqualTo(422));
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_下游422结构化errors体被FlowRemoteException携带_不丢弃() {
|
||||
// 评审 I-2:execute 曾只留状态码丢响应体,引擎结构校验 errors 到不了前端。现携带原始体供 handler 透传。
|
||||
FlowGatewayProperties p = props();
|
||||
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
|
||||
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
|
||||
String engineBody = "{\"status\":1,\"msg\":\"流程校验未通过\",\"errors\":"
|
||||
+ "[{\"activityId\":\"t1\",\"problem\":\"flowable-noOutgoingSeq\",\"defaultDescription\":\"节点未连出边\"}]}";
|
||||
server.expect(ExpectedCount.once(), requestTo("http://localhost:8089/api/flow/models/m1/deploy"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withStatus(HttpStatus.UNPROCESSABLE_ENTITY)
|
||||
.body(engineBody).contentType(MediaType.APPLICATION_JSON));
|
||||
FlowableClient client = new FlowableClient(builder.build(), p);
|
||||
|
||||
assertThatThrownBy(() -> client.deployModel("m1"))
|
||||
.isInstanceOf(FlowRemoteException.class)
|
||||
.satisfies(e -> {
|
||||
FlowRemoteException fre = (FlowRemoteException) e;
|
||||
assertThat(fre.getStatus().value()).isEqualTo(422);
|
||||
assertThat(fre.getResponseBody()).contains("activityId").contains("节点未连出边");
|
||||
});
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布影响_GET_models_id_impact_透传下游结果() {
|
||||
FlowGatewayProperties p = props();
|
||||
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
|
||||
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
|
||||
server.expect(ExpectedCount.once(), requestTo("http://localhost:8089/api/flow/models/m1/impact"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess(
|
||||
"{\"processKey\":\"总包合同交底\",\"currentVersion\":3,\"runningInstances\":7}",
|
||||
MediaType.APPLICATION_JSON));
|
||||
FlowableClient client = new FlowableClient(builder.build(), p);
|
||||
|
||||
Map<String, Object> resp = client.modelImpact("m1");
|
||||
|
||||
assertThat(resp).containsEntry("processKey", "总包合同交底").containsEntry("currentVersion", 3)
|
||||
.containsEntry("runningInstances", 7);
|
||||
server.verify();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.eip4.platform.flowgateway;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
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.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.eip4.platform.flowgateway.aggregate.ModelSemanticValidator;
|
||||
|
||||
/**
|
||||
* 发布语义校验器单测:办理人/会签内嵌 JSON(全角【】)items 非空 + type 白名单、formKey 存在于
|
||||
* view_wftemplate、completionCondition 预设∪自定义(自定义不阻断)。返回 {@code List<String>} 空=通过。
|
||||
*
|
||||
* <p>fixture 逐字复刻 §0 真实形态:candidateUsers/collection 值是引擎 handler 表达式,内容段花括号全角【】、
|
||||
* XML 属性内引号 {@code "}(DOM 解码回真引号后 validator 再 replace 全角→半角 JSON.parse)。
|
||||
*/
|
||||
class ModelSemanticValidatorTest {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
|
||||
private final ModelSemanticValidator validator = new ModelSemanticValidator(jdbcTemplate);
|
||||
|
||||
private static final String CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
|
||||
private static final String MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'";
|
||||
private static final String SUFFIX = "')}";
|
||||
|
||||
/** formKey 存在性查询恒返回给定 count(一次 stub 覆盖所有 formKey)。 */
|
||||
private void formKeyCount(int count) {
|
||||
when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(count);
|
||||
}
|
||||
|
||||
/** 办理人/会签内容段:半角 JSON → 花括号全角【】(方括号保持半角,逐字对齐存储态)。 */
|
||||
private static String toStored(String halfWidthJson) {
|
||||
return halfWidthJson.replace("{", "【").replace("}", "】");
|
||||
}
|
||||
|
||||
private static String candidateExpr(String itemsJson) {
|
||||
return CANDIDATE_PREFIX + toStored("{\"items\":" + itemsJson + "}") + SUFFIX;
|
||||
}
|
||||
|
||||
private static String multiExpr(String itemsJson) {
|
||||
return MULTI_PREFIX + toStored("{\"items\":" + itemsJson + "}") + SUFFIX;
|
||||
}
|
||||
|
||||
/** XML 属性值转义(内嵌 JSON 双引号 → ")。 */
|
||||
private static String attr(String s) {
|
||||
return s.replace("&", "&").replace("\"", """).replace("<", "<");
|
||||
}
|
||||
|
||||
private static String bpmn(String processInner) {
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" "
|
||||
+ "xmlns:activiti=\"http://activiti.org/bpmn\" targetNamespace=\"n\">"
|
||||
+ "<process id=\"p1\" name=\"流程\">" + processInner + "</process></definitions>";
|
||||
}
|
||||
|
||||
private static String userTaskWithCandidate(String name, String candidateExpr) {
|
||||
return "<userTask id=\"t1\" name=\"" + name + "\" activiti:candidateUsers=\""
|
||||
+ attr(candidateExpr) + "\"/>";
|
||||
}
|
||||
|
||||
private static String cosignUserTask(String name, String collectionExpr, String completion) {
|
||||
String cc = completion == null ? ""
|
||||
: "<completionCondition>" + attr(completion) + "</completionCondition>";
|
||||
return "<userTask id=\"t2\" name=\"" + name + "\">"
|
||||
+ "<multiInstanceLoopCharacteristics isSequential=\"false\" activiti:collection=\""
|
||||
+ attr(collectionExpr) + "\" activiti:elementVariable=\"assignee\">" + cc
|
||||
+ "</multiInstanceLoopCharacteristics></userTask>";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 通过
|
||||
|
||||
@Test
|
||||
void 合法流程_办理人items非空白名单_formKey存在_预设完成条件_零错误() {
|
||||
formKeyCount(1);
|
||||
String xml = bpmn(
|
||||
"<userTask id=\"t1\" name=\"审批\" activiti:formKey=\"wft-1\" activiti:candidateUsers=\""
|
||||
+ attr(candidateExpr("[{\"type\":\"user\",\"content\":\"u1,u2\",\"isCandidate\":true}]"))
|
||||
+ "\"/>"
|
||||
+ cosignUserTask("会签", multiExpr("[{\"type\":\"depart\",\"content\":\"d1\"}]"),
|
||||
"${nrOfCompletedInstances/nrOfInstances==1}"));
|
||||
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 裸userTask无办理人无formKey_不属本校验器职责_零错误() {
|
||||
String xml = bpmn("<userTask id=\"t1\" name=\"纯节点\"/>");
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
// 无 formKey → 不查库
|
||||
verify(jdbcTemplate, never()).queryForObject(anyString(), eq(Integer.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非handler裸候选值_非EIP4codec产物_放行不校验JSON() {
|
||||
// 直接写 ${someVar} 等裸表达式:非 EIP4 办理人 handler 形态,不套 JSON 白名单(避免误拒合法 Flowable 裸值)
|
||||
String xml = bpmn("<userTask id=\"t1\" name=\"节点\" activiti:candidateUsers=\"${someVar}\"/>");
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void M1_flowable前缀candidateUsers_按本地名匹配同样校验() {
|
||||
// 语料有 flowable 命名空间文档(3docs);按本地名匹配,flowable:candidateUsers 与 activiti: 同样被校验。
|
||||
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" "
|
||||
+ "xmlns:flowable=\"http://flowable.org/bpmn\" targetNamespace=\"n\">"
|
||||
+ "<process id=\"p1\" name=\"流程\">"
|
||||
+ "<userTask id=\"t1\" name=\"flowable节点\" flowable:candidateUsers=\""
|
||||
+ attr(candidateExpr("[{\"type\":\"bogusType\",\"content\":\"x\"}]")) + "\"/>"
|
||||
+ "</process></definitions>";
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("flowable节点").contains("bogusType");
|
||||
}
|
||||
|
||||
@Test
|
||||
void M2_新增4种type放行_锁I1白名单对齐WfTypes() {
|
||||
// roles/initiatorLeader/initiatorDepartManager/fixedDimension:WfTypes 配置类型、OrgDirectoryJdbc 运行期支持,
|
||||
// 但旧 10 种白名单缺失。实测 initiatorDepartManager(24 文档)/fixedDimension(12 文档)真存量命中→曾会 422 误拒。
|
||||
for (String type : new String[]{"roles", "initiatorLeader", "initiatorDepartManager", "fixedDimension",
|
||||
"initiatorSubordinate", "initiatorDepart"}) {
|
||||
String xml = bpmn(userTaskWithCandidate("节点",
|
||||
candidateExpr("[{\"type\":\"" + type + "\",\"content\":\"x\"}]")));
|
||||
assertThat(validator.validate(xml)).as("type=%s 应放行", type).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 办理人 JSON 错误
|
||||
|
||||
@Test
|
||||
void 办理人items为空数组_error() {
|
||||
String xml = bpmn(userTaskWithCandidate("空办理人", candidateExpr("[]")));
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("空办理人").contains("为空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 办理人type非白名单_error() {
|
||||
String xml = bpmn(userTaskWithCandidate("坏type",
|
||||
candidateExpr("[{\"type\":\"bogusType\",\"content\":\"x\"}]")));
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("坏type").contains("bogusType");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 办理人JSON无法解析_error() {
|
||||
// 内容段坏 JSON(缺闭合)——全角还原后仍非法
|
||||
String bad = CANDIDATE_PREFIX + toStored("{\"items\":[{\"type\":") + SUFFIX;
|
||||
String xml = bpmn("<userTask id=\"t1\" name=\"坏JSON\" activiti:candidateUsers=\""
|
||||
+ attr(bad) + "\"/>");
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("坏JSON").contains("JSON");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 办理人多个type_逐项报非法() {
|
||||
String xml = bpmn(userTaskWithCandidate("多项",
|
||||
candidateExpr("[{\"type\":\"user\",\"content\":\"a\"},"
|
||||
+ "{\"type\":\"bad1\",\"content\":\"b\"},{\"type\":\"bad2\",\"content\":\"c\"}]")));
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(2);
|
||||
assertThat(errors).anyMatch(e -> e.contains("bad1")).anyMatch(e -> e.contains("bad2"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 会签 collection + 完成条件
|
||||
|
||||
@Test
|
||||
void 会签collection的items为空_error() {
|
||||
formKeyCount(1);
|
||||
String xml = bpmn(cosignUserTask("空会签", multiExpr("[]"),
|
||||
"${nrOfCompletedInstances/nrOfInstances==1}"));
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("空会签").contains("为空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 会签自定义完成条件_不阻断_零错误() {
|
||||
// T2.4 保留自定义完成条件态:非三预设的合法表达式必须放行(别把存量自定义条件拒了)
|
||||
String xml = bpmn(cosignUserTask("过六成会签",
|
||||
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"),
|
||||
"${nrOfCompletedInstances/nrOfInstances>0.6}"));
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 会签过半预设_不阻断_零错误() {
|
||||
String xml = bpmn(cosignUserTask("过半会签",
|
||||
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"),
|
||||
"${nrOfCompletedInstances/nrOfInstances>0.5}"));
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 会签指定数预设_不阻断_零错误() {
|
||||
String xml = bpmn(cosignUserTask("三票会签",
|
||||
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"),
|
||||
"${nrOfCompletedInstances>=3}"));
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 会签完成条件空白_error() {
|
||||
String xml = bpmn(cosignUserTask("空条件会签",
|
||||
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"), " "));
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("空条件会签").contains("完成条件");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- formKey 存在性
|
||||
|
||||
@Test
|
||||
void formKey不存在于模板库_error() {
|
||||
formKeyCount(0);
|
||||
String xml = bpmn("<userTask id=\"t1\" name=\"带表单\" activiti:formKey=\"ghost-uuid\"/>");
|
||||
List<String> errors = validator.validate(xml);
|
||||
assertThat(errors).hasSize(1);
|
||||
assertThat(errors.get(0)).contains("带表单").contains("ghost-uuid").contains("view_wftemplate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formKey读库异常_降级放行不阻断部署() {
|
||||
when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any()))
|
||||
.thenThrow(new DataAccessResourceFailureException("db down"));
|
||||
String xml = bpmn("<userTask id=\"t1\" name=\"带表单\" activiti:formKey=\"wft-1\"/>");
|
||||
// 读库抖动不因基础设施问题阻断发布(全站降级惯例),该项引用完整性检查跳过
|
||||
assertThat(validator.validate(xml)).isEmpty();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- XML 层防御
|
||||
|
||||
@Test
|
||||
void 坏XML_error不抛() {
|
||||
List<String> errors = validator.validate("<definitions><process</bad>");
|
||||
assertThat(errors).isNotEmpty();
|
||||
assertThat(errors.get(0)).contains("解析");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 含DOCTYPE_XXE防御_error() {
|
||||
String evil = "<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY x \"y\">]>"
|
||||
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"><process id=\"p\"/></definitions>";
|
||||
List<String> errors = validator.validate(evil);
|
||||
assertThat(errors).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 空XML_error() {
|
||||
assertThat(validator.validate(" ")).isNotEmpty();
|
||||
assertThat(validator.validate(null)).isNotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import com.eip4.platform.auth.security.AuthPrincipal;
|
||||
import com.eip4.platform.flowgateway.aggregate.FlowDeployAuditService;
|
||||
import com.eip4.platform.flowgateway.aggregate.ModelSemanticValidator;
|
||||
import com.eip4.platform.flowgateway.aggregate.WfTemplatePickerService;
|
||||
import com.eip4.platform.flowgateway.client.FlowRemoteException;
|
||||
import com.eip4.platform.flowgateway.client.FlowServiceUnavailableException;
|
||||
@@ -47,8 +49,10 @@ class ProcessModelerControllerTest {
|
||||
|
||||
private final FlowableClient flowableClient = mock(FlowableClient.class);
|
||||
private final WfTemplatePickerService wfTemplatePickerService = mock(WfTemplatePickerService.class);
|
||||
private final ProcessModelerController controller =
|
||||
new ProcessModelerController(flowableClient, wfTemplatePickerService);
|
||||
private final ModelSemanticValidator semanticValidator = mock(ModelSemanticValidator.class);
|
||||
private final FlowDeployAuditService deployAuditService = mock(FlowDeployAuditService.class);
|
||||
private final ProcessModelerController controller = new ProcessModelerController(
|
||||
flowableClient, wfTemplatePickerService, semanticValidator, deployAuditService);
|
||||
|
||||
/** 真实形态:中文 key + 冒号分隔的 procDefId。 */
|
||||
private static final String CN_PROCDEF = "总包合同交底:3:abc123";
|
||||
@@ -368,4 +372,124 @@ class ProcessModelerControllerTest {
|
||||
// 路由匹配 PUT 谓词 + {id} 绑定到 "m1" 交给控制器
|
||||
verify(flowableClient).updateModel(eq("m1"), any());
|
||||
}
|
||||
|
||||
// ---- 发布门(T3.2):超管门 → 语义校验 → 转发部署 → 审计 INSERT。语义 fail 零转发零审计;非超管零触达。----
|
||||
|
||||
@Test
|
||||
void 发布_超管语义通过_转发部署并写审计_operator为userId() {
|
||||
when(flowableClient.getModel("m1"))
|
||||
.thenReturn(Map.of("found", true, "bpmnXml", "<definitions/>"));
|
||||
when(semanticValidator.validate("<definitions/>")).thenReturn(List.of());
|
||||
Map<String, Object> deployed = Map.of("status", 0, "deploymentId", "dep-9",
|
||||
"processKey", "总包合同交底", "newVersion", 4);
|
||||
when(flowableClient.deployModel("m1")).thenReturn(deployed);
|
||||
|
||||
ResponseEntity<Map<String, Object>> resp = controller.deploy(admin(), "m1");
|
||||
|
||||
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(resp.getBody()).isEqualTo(deployed);
|
||||
verify(flowableClient).deployModel("m1");
|
||||
// 审计收口到 @Service,operator=principal.userId()="ADMIN"(超管门已保证 principal 非空)
|
||||
verify(deployAuditService).record("m1", deployed, "ADMIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_语义校验失败_422带明细_零转发零审计() {
|
||||
when(flowableClient.getModel("m1"))
|
||||
.thenReturn(Map.of("found", true, "bpmnXml", "<definitions/>"));
|
||||
when(semanticValidator.validate("<definitions/>"))
|
||||
.thenReturn(List.of("节点『会签』的办理人为空(items 为空)"));
|
||||
|
||||
ResponseEntity<Map<String, Object>> resp = controller.deploy(admin(), "m1");
|
||||
|
||||
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
assertThat(resp.getBody()).containsEntry("status", 1);
|
||||
assertThat(resp.getBody().get("errors")).isEqualTo(List.of("节点『会签』的办理人为空(items 为空)"));
|
||||
verify(flowableClient, never()).deployModel(anyString()); // 校验拦截:绝不部署
|
||||
verify(deployAuditService, never()).record(anyString(), any(), anyString()); // 未部署不写审计
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_非超管_403_零触达下游与校验() {
|
||||
ResponseEntity<Map<String, Object>> resp = controller.deploy(normalUser(), "m1");
|
||||
|
||||
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(resp.getBody()).containsEntry("status", 1).containsEntry("msg", "仅系统管理员可用");
|
||||
verify(flowableClient, never()).getModel(anyString());
|
||||
verify(flowableClient, never()).deployModel(anyString());
|
||||
verify(semanticValidator, never()).validate(anyString());
|
||||
verify(deployAuditService, never()).record(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 发布_草稿不存在_404_不校验不部署() {
|
||||
when(flowableClient.getModel("nope")).thenReturn(Map.of("found", false));
|
||||
|
||||
ResponseEntity<Map<String, Object>> resp = controller.deploy(admin(), "nope");
|
||||
|
||||
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(resp.getBody()).containsEntry("status", 1);
|
||||
verify(semanticValidator, never()).validate(anyString());
|
||||
verify(flowableClient, never()).deployModel(anyString());
|
||||
verify(deployAuditService, never()).record(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 影响摘要_超管_透传下游200() {
|
||||
Map<String, Object> downstream = Map.of("processKey", "总包合同交底",
|
||||
"currentVersion", 3, "runningInstances", 7);
|
||||
when(flowableClient.modelImpact("m1")).thenReturn(downstream);
|
||||
|
||||
ResponseEntity<Map<String, Object>> resp = controller.impact(admin(), "m1");
|
||||
|
||||
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(resp.getBody()).isEqualTo(downstream);
|
||||
verify(flowableClient).modelImpact("m1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 影响摘要_非超管_403_零触达下游() {
|
||||
ResponseEntity<Map<String, Object>> resp = controller.impact(normalUser(), "m1");
|
||||
|
||||
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
verify(flowableClient, never()).modelImpact(anyString());
|
||||
}
|
||||
|
||||
// ---- 胶水:发布 422 语义信封经 MVC 出(status:1 + errors 数组);发布路由 POST /{id}/deploy 绑定 ----
|
||||
|
||||
@Test
|
||||
void 胶水_发布_语义422信封含errors数组() throws Exception {
|
||||
when(flowableClient.getModel("m1"))
|
||||
.thenReturn(Map.of("found", true, "bpmnXml", "<definitions/>"));
|
||||
when(semanticValidator.validate("<definitions/>"))
|
||||
.thenReturn(List.of("节点『审批』的表单 formKey 不存在于模板库(view_wftemplate):ghost"));
|
||||
|
||||
glueMvc().perform(post("/api/workflow/models/{id}/deploy", "m1"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.status").value(1))
|
||||
.andExpect(jsonPath("$.errors[0]").value(
|
||||
"节点『审批』的表单 formKey 不存在于模板库(view_wftemplate):ghost"));
|
||||
|
||||
verify(flowableClient, never()).deployModel(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 胶水_发布_语义过但下游引擎422结构化errors经handler并入顶层() throws Exception {
|
||||
// I-2:语义门放行 → 转发 deploy → 下游引擎 ProcessValidator 结构校验 422(对象式 errors) → handler 并入网关响应。
|
||||
// 两条 422 契约统一:顶层 errors(语义=字符串数组 / 引擎=对象数组),前端 T3.3 同一渲染。
|
||||
when(flowableClient.getModel("m1"))
|
||||
.thenReturn(Map.of("found", true, "bpmnXml", "<definitions/>"));
|
||||
when(semanticValidator.validate("<definitions/>")).thenReturn(List.of()); // 语义过
|
||||
String engineBody = "{\"status\":1,\"msg\":\"流程校验未通过\",\"errors\":"
|
||||
+ "[{\"activityId\":\"t1\",\"problem\":\"noOutgoing\",\"defaultDescription\":\"节点未连出边\"}]}";
|
||||
when(flowableClient.deployModel("m1")).thenThrow(
|
||||
new FlowRemoteException(HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
"flowable-service 发布草稿返回 422", engineBody));
|
||||
|
||||
glueMvc().perform(post("/api/workflow/models/{id}/deploy", "m1"))
|
||||
.andExpect(status().isUnprocessableEntity())
|
||||
.andExpect(jsonPath("$.error").value("FLOW_REMOTE_ERROR"))
|
||||
.andExpect(jsonPath("$.errors[0].activityId").value("t1"))
|
||||
.andExpect(jsonPath("$.errors[0].defaultDescription").value("节点未连出边"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user