Compare commits

..

16 Commits

Author SHA1 Message Date
546a8228b0 Merge feat/process-modeler 阶段1: Modeler 只读载入存量(可逆净化+source端点+网关超管门)
Some checks failed
ci / build-test-parity (push) Has been cancelled
- BpmnIdSanitizer 可逆化(碰撞消解+前缀安全+双射契约测试,BpmnIdSanitizerTest 10)
- by-id/by-key 取净化源XML端点(共享 sourceResponse,ProcessDiagramControllerTest 9)
- 网关转发+超管门(isSystemAdmin public化+9契约测试,中文procDefId uri变量编码硬验收,
  FlowGatewayExceptionHandler 全仓首测,ProcessModelerControllerTest 10)
- live 验收:中文key「总包合同交底」全链打开,画布/palette/标准面板(Multi-instance组)全渲染,
  无身份403;全 reactor mvn clean install 绿
- live 揪修2真bug:options source=model 语义缺口(by-key修法)/属性面板 ref 未绑
- 计划文件随评审实证持续回写(7次 docs 提交)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:08:05 +08:00
ddaf536419 test(gateway+auth): T1.6 评审收口(I-1 胶水测试/M-2 空 userId/M-1 时效性注释)
- I-1(合 main 前必须):ProcessModelerControllerTest 补 4 个 MockMvc 胶水测试
  (standaloneSetup + setControllerAdvice(FlowGatewayExceptionHandler) + 自定义超管参数解析器)——
  by-id/by-key 各:①引擎不可达经既有 handler 出 503 通用信封(FlowGatewayExceptionHandler 全仓首测)
  ②正常路径 200 透传 ③MVC 层把 percent 编码中文 path variable(含冒号 procDefId)正确解码回原串交控制器。
- M-2:EngineContextBinderAdminTest 补「userId 空串/空白/null 且 account 非 admin → false」用例。
- M-1:EngineContextBinder.isSystemAdmin javadoc 补时效性说明(userId/account 取自 JWT claim 签发快照,
  非实时查库;token 有效期内 admin 改名/停用/降权不即时生效,由 TTL/吊销兜底)。

测试(mvn -pl platform-flow-gateway,platform-auth -am test 全绿,既有零修改):
ProcessModelerControllerTest 6→10 / EngineContextBinderAdminTest 8→9 / FlowableClientTest 12 不变。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:03:59 +08:00
9cfef7e931 feat(flow+gateway): by-key 取最新版源 XML(修 process-select options=model 语义缺口)
live 验收发现:/api/process-select/options 在本库 143 项全部 source='model',
option.id=act_re_model id(非 procDefId)→ by-id source 端点永远 found:false;
option.key 才是真流程 key。补 by-key 姊妹端点,打开器改用 key 载入。

- flowable-service ProcessDiagramController:
  + GET /api/flow/process-definitions/by-key/{key}/source
    (processDefinitionKey(key).latestVersion().singleResult(),null→found:false)。
  by-id 与 by-key 逻辑抽共享私有 sourceResponse(procDefId, def),不复制粘贴;
  by-id 行为不变(仍以入参 procDefId 读部署 BPMN,既有 7 测试零修改)。
- 网关:FlowableClient.procDefSourceByKey(key)(uri 变量严格编码,禁拼接)
  + ProcessModelerController GET /api/workflow/process-definitions/by-key/{key}/source
    (同超管门,非超管 403)。by-id/by-key 段数不同无路由歧义。

测试(mvn -pl flowable-service,platform-flow-gateway,platform-auth -am test 全绿,既有零修改):
- ProcessDiagramControllerTest 7→9(+2:by-key 命中取最新版 v2 净化XML+idMap / key 不存在 found:false)
- FlowableClientTest 11→12(+1:纯中文 key「总包合同交底」uri 变量严格编码,断言 %E6%80%BB 且无裸中文)
- ProcessModelerControllerTest 4→6(+2:by-key 超管 200 透传 / 非超管 403 不触发下游)
- 三模块 Reactor 均 SUCCESS。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:59:04 +08:00
88ab0b8f0e docs(plan): 回写 T1.6 评审 M-3——T2.2 抽 requireSuperAdmin 统一过门 + 红线补「生产 8089 不对外」
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:55:38 +08:00
fdb97def4d docs(plan): 回写阶段1 live 发现——options source=model 语义缺口与 by-key 修法
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:54:10 +08:00
6d16206a08 feat(gateway): Modeler source 转发+超管门(中文 procDefId 编码硬验收)
阶段1 T1.6 代码部分:流程 Modeler 存量源 XML 经网关超管门载入。

- FlowableClient.procDefSource(procDefId):转发 GET /api/flow/process-definitions/{id}/source,
  procDefId 作为 uri 变量由 RestClient 严格编码(中文 percent、冒号→%3A),绝不字符串拼 URL(M-2)。
  走既有 execute() 重试/降级封装(连接级重试→503,4xx/5xx 透传)。
- ProcessModelerController GET /api/workflow/process-definitions/{procDefId}/source:
  超管门(EngineContextBinder.isSystemAdmin,非超管 403 {status:1,msg:"仅系统管理员可用"}),
  过门后透传下游返回体。flowable-service 裸 8089 无安全栈,超管门唯一落点在网关。
- EngineContextBinder.isSystemAdmin 由 private 提升为 public static + null 安全,供网关复用;
  判定口径不变(ADMIN 大小写不敏感去补白 / account 大小写敏感=admin / 含 admin 字样不误判)。

测试(mvn -pl platform-flow-gateway,platform-auth -am test 全绿,既有测试零修改):
- FlowableClientTest +2:中文 procDefId「总包合同交底:3:abc123」uri 变量严格编码(断言 %3A 且无裸中文)
  / 下游 4xx 透传 FlowRemoteException 不重试。共 11。
- ProcessModelerControllerTest 4:超管 200 透传 / 非超管 403 不触发下游 / 无身份 403 / 引擎不可达上抛。
- EngineContextBinderAdminTest 8:ADMIN 大小写·补白 / account=admin / Admin 变体不提权 / 含 admin 普通用户 / null。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:47:00 +08:00
14a825d0a0 docs(plan): 回写 T1.5 评审——T2.4 顺带补红线回归测试+canvas分支错误提示
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:43:12 +08:00
3ca082408c docs(plan): 回写 T1.4 评审 M-2——T1.6 中文 procDefId 编码为硬验收点(禁拼URL,测试+live 均须中文用例)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:34:25 +08:00
e5781ddd02 test(flow): source 端点补 ref 重写断言(评审 M-1)
中文 fixture 测试追加断言:sequenceFlow 的 sourceRef 引用须随 process id
一致重写,净化后 XML 不含 sourceRef="总包合同交底",让 ref 重写不白放。
ProcessDiagramControllerTest 7/7 绿(JDK21)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:34:22 +08:00
3927146f08 feat(flow): 按 procDefId 取净化源 XML 端点(含 idMap,D7 载入侧)
新增 GET /api/flow/process-definitions/{procDefId}/source:
createProcessDefinitionQuery 取 key/version + readProcessModel 取 BPMN
+ BpmnIdSanitizer.sanitize 净化中文 id → {found,bpmnXml,idMap,procDefKey,version}。
定义不存在 / XML 为空或读取异常 → {found:false}(HTTP 200,WARN log,防御性同 diagram 端点)。
idMap 透出原→净化映射,供发布时逆向还原原 key(D7)。

TDD:ProcessDiagramControllerTest +3 用例(净化XML+idMap+key版本 / 定义不存在
found:false / 读取异常 found:false),既有 4 用例零修改仍绿。
类 7/7、模块全量 71/71 绿(JDK21)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:27:46 +08:00
e361d3a9ad fix(flow): BpmnIdSanitizer 评审收口——safe占位契约测试+空白原样+inverse fail-fast
- I-1:补「生成净化 id 不与文档既有合法字面 id 冲突」契约测试。fixture 含合法字面
  id nb7af8 + 中文 id 审批(其 hashCode&0x7fffffff 的 hex 恰为 b7af8)→ 断言 审批 让位
  映射为 nb7af8-2、既有 nb7af8 不动、restore 逐字节还原。
- M-1:rewrite 未改值的属性原样回写(append group(0)),不再重构 → 不归一 id = "x" 这类
  等号周围空白,保逐字节契约。补测:带等号空白的合法属性 + 非空 map,round-trip 后原文不变。
- M-2:restore 反转 idMap 时检测净化 id 重复(非双射,损坏 metaInfo)抛 IllegalArgumentException,
  不再静默覆盖还原错。补 fail-fast 测试。

测试:BpmnIdSanitizerTest 7→10 例;ProcessDiagramControllerTest 4 例仍零修改;
flowable-service 全模块 mvn -pl flowable-service -am test = 68 测试 0 失败 0 错误。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:24:14 +08:00
33fccb6541 docs(plan): 回写 T1.3 评审 I-2——T3.1 部署前须处理 incoming/outgoing 文本引用(剥除或纳入 restore)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:22:57 +08:00
3cf58fe72c refactor(flow): id 净化抽 BpmnIdSanitizer,补可逆 restore+碰撞消解(D7 地基)
ProcessDiagramController.sanitizeBpmnIds 的中文 id→安全 ASCII 净化逻辑抽成
BpmnIdSanitizer(sanitize 返 Result{xml,idMap} / restore 逆向还原),为 D7「发布存量
流程 key 不变」打地基。

- 双射保证:同文档两个不同中文 id hash 碰撞时基名追加 -2/-3 序号,生成 id 亦不与既有
  合法 id 冲突;非碰撞场景净化输出与旧实现逐字节一致(查看器零回归)。
- restore 前缀安全:复用 ID_ATTR 正则逐属性值精确匹配,不裸 String.replace 子串替换
  (n1 不误伤 n1x);映射外 ASCII id(设计器新增节点)原样保留。
- ProcessDiagramController.sanitizeBpmnIds 改为委托,原包级签名/行为不变。

测试:新增 BpmnIdSanitizerTest 7 例(中文全引用面 restore 逐字节还原/撞哈希 中Aa~中BB
双射/restore n1~n1x 前缀安全/合法 NCName 不改写/混合只映射中文/空 XML 防御);
既有 ProcessDiagramControllerTest 4 例零修改仍绿;flowable-service 全模块 65 测试通过。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:10:47 +08:00
7a97b712b4 docs(plan): 回写 T1.2 实证——T1.3 净化 hash 有碰撞风险,可逆 restore 须双射消解
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:03:06 +08:00
90a6f97040 docs(plan): T1.1 评审 M-3 回写——T1.5 严禁引 Camunda provider(双包冲突变体)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:45:06 +08:00
f7d96489d0 docs(plan): 回写 T1.1 实证——双包冲突/嵌套全角【】/formKey裸UUID/moddle拒中文id
T1.1(eip4-web 8fdfe68)三发现防漂移回写:T1.5 只载 activiti 描述符(双载丢 userTask)+resolveJsonModule 提示;
T2.3 表达式 fixture 改嵌套全角形态(items 内层对象也是【】,content 尾部补白不可 trim);
§0 补 formKey=裸UUID + moddle 拒中文id 实证

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:38:19 +08:00
11 changed files with 1016 additions and 59 deletions

View File

@@ -16,7 +16,7 @@
## §0 事实基线(2026-07-02 勘探,全部核实过)
**语料(本地 eip4 库,5433,search_path=eip3)**:1512 真实 BPMN(act_ge_bytearray)/1503 部署/143 act_re_model。
扩展面实测:**11 个扩展属性**(activiti:formKey 1476docs / candidateUsers 1465 / exclusive 1311 / assignee 27 / collection 28 / elementVariable 24 / candidateGroups 3 / autoStoreVariables 4 / initiator 3 / dueDate 1 + flowable:assignee 3docs)、**5 个扩展元素**(taskListener 159docs / formProperty 6 / value / field / string);命名空间 activiti=1509docs、flowable=3docs。BPMN 特性:userTask 1505 / conditionExpression 297 / exclusiveGateway 276 / parallelGateway 52 / **multiInstance 28(8 个 distinct key,如「总包合同交底」——key 就是中文,D7 id 可逆净化是硬需求)** / boundary·timer·subProcess·error 个位数 / signal·callActivity·serviceTask 零。
扩展面实测:**11 个扩展属性**(activiti:formKey 1476docs / candidateUsers 1465 / exclusive 1311 / assignee 27 / collection 28 / elementVariable 24 / candidateGroups 3 / autoStoreVariables 4 / initiator 3 / dueDate 1 + flowable:assignee 3docs)、**5 个扩展元素**(taskListener 159docs / formProperty 6 / value / field / string);命名空间 activiti=1509docs、flowable=3docs。BPMN 特性:userTask 1505 / conditionExpression 297 / exclusiveGateway 276 / parallelGateway 52 / **multiInstance 28(8 个 distinct key,如「总包合同交底」——key 就是中文,D7 id 可逆净化是硬需求;且 moddle-xml 拒绝中文 id=进 moddle 前必须已净化,T1.1 实证)**。activiti:formKey 值=裸 UUID(view_wftemplate_id 本身,无前缀) / boundary·timer·subProcess·error 个位数 / signal·callActivity·serviceTask 零。
**后端**(file:line 均已核实):
- 部署端点已有:`FlowController.deploy` @ flowable-service `api/FlowController.java:81-105`,body=`{name?,bpmnXml}`,`createDeployment().name().addString().deploy()`,**无鉴权无审计**;网关 FlowableClient **未封装 deploy**。
@@ -54,7 +54,9 @@
## 阶段 1:moddle 保真 + 只读载入存量(可独立合 main)
### Task 1.1 前端依赖 + moddle 描述符 + 保真单测
### Task 1.1 前端依赖 + moddle 描述符 + 保真单测 ✅(8fdfe68,2026-07-02)
> 完成实证:panel 5.60.0/3.47.0;12/12+全量 101/101 绿;**三发现已回写本计划**(双包冲突→T1.5 只载 activiti / 嵌套全角【】→T2.3 / formKey=裸 UUID)。遗留:bpmn-moddle 无类型声明(TS7016 编辑器诊断,tsc -b 不受影响)→ T1.5 顺带补 `.d.ts`。
**Files:**
- Modify: `eip4-web/package.json`(+`bpmn-js-properties-panel@^5.23.0` +`@bpmn-io/properties-panel@^3.23.0`;装完看 npm 实际解析版本,只需兼容 bpmn-js 17)
@@ -109,6 +111,8 @@ commit:`feat(modeler): 全量 1512 真实流程 moddle round-trip 保真扫描
### Task 1.3 后端:id 净化抽成可逆 `BpmnIdSanitizer`
> ⚠️ **T1.2 实证预警——hash 碰撞**:现行 `"n"+hex(hashCode&0x7fffffff)` **有碰撞可能**(1445/1512 文档 process id 为中文;同文档内两个原 id 撞哈希→引用错乱)。查看器容忍,但**可逆 restore 要求双射**:`sanitize` 必须检测碰撞并消解(碰撞时追加 `-2`/`-3` 序号),并补「同文档撞哈希仍双射可逆」单测(构造碰撞对或可注入 hash 的测试缝)。
**Files:**
- Create: `flowable-service/src/main/java/com/eip4/flowservice/api/BpmnIdSanitizer.java`
- Modify: `flowable-service/src/main/java/com/eip4/flowservice/api/ProcessDiagramController.java`(sanitizeBpmnIds 委托新类,行为不变)
@@ -159,13 +163,18 @@ import 'bpmn-js/dist/assets/bpmn-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import '@bpmn-io/properties-panel/dist/assets/properties-panel.css';
import activitiModdle from '../modeler/moddle/activiti.json';
import flowableModdle from '../modeler/moddle/flowable.json';
// (app 代码首次 import json:本 task 顺带在 tsconfig.app.json 开 "resolveJsonModule": true)
const modeler = new Modeler({
container: canvasRef.current,
propertiesPanel: { parent: panelRef.current },
additionalModules: [BpmnPropertiesPanelModule, BpmnPropertiesProviderModule],
moddleExtensions: { activiti: activitiModdle, flowable: flowableModdle },
// ⚠️ 只载 activiti!T1.1 实证:activiti+flowable 双包同载会因 bpmn:UserTask 同名 extends
// 属性冲突(not allowed without redefines)静默丢弃 userTask。语料 1509/3 两命名空间不混用;
// 单载 activiti 时 flowable 文档经 moddle lax $attrs 零丢失往返。flowable.json 只做隔离单测。
// ⚠️ 同理:只 import 标准 BpmnPropertiesProviderModule,严禁引 Camunda provider——
// 它会把 camunda 描述符注进 moddle,即双包冲突的变体(T1.1 评审 M-3)。
moddleExtensions: { activiti: activitiModdle },
});
```
布局参照 DesignerPage:顶栏(名称/保存草稿·发布·返回,本阶段按钮 disabled 占位)+ 左画布 + 右栏(上=EIP4 侧板占位,下=标准面板)。存量入口:设计中心按钮 → 新页内「打开存量流程」下拉(数据源复用 `GET /api/process-select/options`)。
@@ -174,6 +183,10 @@ const modeler = new Modeler({
### Task 1.6 网关:source 转发 + 阶段 1 live 验收
> 🔴 **阶段1 live 验收实证(2026-07-02)——options 语义缺口已修**:`/api/process-select/options` 在合并库返回的 143 选项**全部 source='model',option.id=act_re_model 的 id 非 procDefId**(计划原假设错),打开器按 procDefId 载入恒 found:false。修法=新增 **by-key 取最新版**端点(`GET /api/flow/process-definitions/by-key/{key}/source` + 网关同门转发),前端打开器按 option.source 双参分派(model→?procKey=key / processDefinition→?procDefId=id)。
>
> ⚠️ **T1.4 评审 M-2——中文 procDefId 编码**:真实 procDefId 形如 `总包合同交底:3:<uuid>`(中文+冒号进 path segment)。网关 FlowableClient 转发**必须用 UriComponentsBuilder/uriVariables 正确编码**(禁字符串拼 URL),且测试必须含一个**中文 procDefId 用例**(MockRestServiceServer 断言转发 URL 编码正确);live 验收也必须用中文 key 流程点穿 HTTP 全链。
**Files:**
- Modify: `platform-flow-gateway/.../client/FlowableClient.java`(+`procDefSource(procDefId)`)
- Create: `platform-flow-gateway/.../web/ProcessModelerController.java`(`GET /api/workflow/process-definitions/{id}/source`,**超管门**:`AuthPrincipal` 校验 `EngineContextBinder.isSystemAdmin`,非超管 403——若该方法非 public static,本 task 顺带提升可见性并补一个判定单测)
@@ -204,6 +217,8 @@ commit:`feat(flow): 流程草稿 ProcessModelController(act_re_model,Model API
### Task 2.2 网关:models 全套转发 + wftemplate picker 数据源
> 📌 **T1.6 评审 M-3**:本 task 给 ProcessModelerController 加第二个及以后端点时,先抽 `requireSuperAdmin()` 私有方法(返回 403 ResponseEntity 或 null),所有端点统一过门防漏。
**Files:**
- Modify: `FlowableClient.java`(+models list/get/create/update/fromProcDef 五方法)
- Modify: `ProcessModelerController.java`(+`/api/workflow/models/**` 五端点,全部过超管门)
@@ -219,7 +234,9 @@ commit:`feat(gateway): 流程草稿转发(超管门)+wftemplate picker 数据
**Step 1** 失败测试(真实形态往返):
```ts
const REAL = `\${candidateUsersHandler.getCandidateUsers(execution,'【"items":[{"type":"user","content":"u1,u2","isCandidate":true,"isSendMail":false,"isSendPhone":false}]】')}`;
// T1.1 psql 实证真实形态:外层对象与 items 内每个对象的花括号**全部**是全角【】,
// 方括号[]半角,XML 属性内引号转义为 &quot;,content 可带 CHAR 尾部补白空格(不可 trim)。
const REAL = `\${candidateUsersHandler.getCandidateUsers(execution,'【"items":[【"type":"user","content":"u1,u2","isCandidate":true,"isSendMail":false,"isSendPhone":false】]】')}`;
it('解析真实表达式(全角【】)', () => {
const r = parseCandidateExpression(REAL);
expect(r!.items[0]).toMatchObject({ type: 'user', content: 'u1,u2', isCandidate: true });
@@ -238,6 +255,8 @@ commit:`feat(modeler): 办理人/会签表达式编解码器(与 BasePropertie
### Task 2.4 前端:EIP4 侧板(办理人/会签/formKey/扩展属性/监听器)
> 📌 **随本 task 顺带收 T1.5 评审两小项**:①红线回归测试——ProcessModelerPage 测试断言 `ModelerCtor.mock.calls[0][0].moddleExtensions` 键恰为 `['activiti']` 且 `additionalModules` 长度为 2(防有人「顺手」加 provider 静默回归);②canvas ref 为 null 分支也 set error(现停留 loading 无提示)。
**Files:**
- Create: `src/modeler/Eip4Panel.tsx`(+`Eip4Panel.test.tsx`)、`src/modeler/useSelectedElement.ts`(订阅 `selection.changed`)
- Modify: `ProcessModelerPage.tsx`(右栏上方挂 Eip4Panel)
@@ -265,6 +284,8 @@ commit + 合 main:`feat(modeler): 阶段2 EIP4 控件+草稿闭环`
### Task 3.1 后端:deploy-from-model(id 还原 + 引擎校验门)
> ⚠️ **T1.3 评审 I-2 预警——文本引用**:bpmn-js `saveXML` 会给流节点补 `<bpmn:incoming>/<bpmn:outgoing>` **元素文本**引用(存量 1512 文档 0 命中,但编辑器导出会有),`BpmnIdSanitizer.restore` 只还原**属性位** → 直接部署会落库「属性=中文原 id、文本引用=净化 id」的脏 XML(Flowable 不解析 incoming/outgoing 故功能无害,但再次 from-procdef 重编辑时碰撞序号换位可能指错节点)。**本 task 必须**:restore 前剥除 incoming/outgoing 元素(Flowable 自行从 sequenceFlow 推导)或把文本引用位纳入 restore,二选一并加测试(含「编辑器导出态 XML → 部署 XML 无净化 id 残留」断言)。
**Files:** Modify `ProcessModelController.java` + test。
`POST /models/{id}/deploy`:
@@ -337,4 +358,4 @@ commit:`test(modeler): 流程Modeler live e2e(改存量/新建/走查 3 场景
## 红线提醒(执行中不可越)
flowable `databaseSchemaUpdate=false` 不动(act_re_model 已存在无需 DDL;审计表走 Flyway V4 是平台表非引擎表);保真层 `com.dsasp.*` 不改(BasePropertiesConverter 只读对齐,不重构);XML 解析一律钉 JDK 解析器(xerces 击穿前科);JDK 21;部署门只落网关(flowable-service 裸 8089 无安全栈);每 task TDD、每阶段对抗自查后才合 main。
**生产 8089 不对外**(T1.6 评审:门在网关的前提=flowable-service 网络隔离,阶段 3 部署门验收清单显式检查,deploy/nginx/compose 不得暴露 8089);flowable `databaseSchemaUpdate=false` 不动(act_re_model 已存在无需 DDL;审计表走 Flyway V4 是平台表非引擎表);保真层 `com.dsasp.*` 不改(BasePropertiesConverter 只读对齐,不重构);XML 解析一律钉 JDK 解析器(xerces 击穿前科);JDK 21;部署门只落网关(flowable-service 裸 8089 无安全栈);每 task TDD、每阶段对抗自查后才合 main。

View File

@@ -0,0 +1,134 @@
package com.eip4.flowservice.api;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* BPMN id 净化/还原(可逆双射)。
*
* <p>迁移的 1512 个真实流程里,1445 个的 process id 就是中文(如「总包合同交底」),BPMN 常把中文用作
* process/diagram/节点 id。bpmn-js / moddle 的 NCName 校验拒非 ASCII id → 整图无法渲染,且 moddle-xml
* 在 import 前就会拒中文 id。{@link #sanitize} 把非法(非 ASCII NCName)id 及其全部引用一致重写为安全
* ASCII id(稳定哈希),保存原→净化映射;{@link #restore} 依映射逆向还原——发布存量流程时把中文原 key
* 原样写回引擎,保证 process key 不变(D7 硬需求)。</p>
*
* <p><b>双射保证</b>:同一文档内两个不同中文 id 若哈希相同(Java String.hashCode 存在碰撞),基名冲突时
* 追加 {@code -2}/{@code -3} 序号;生成的净化 id 亦不与文档内既有合法 id 冲突。故净化后引用不串、restore
* 可精确逆向。<b>非碰撞场景</b>下净化输出与历史实现({@code "n"+hex(hashCode)})逐字节一致,保住查看器回归。</p>
*
* <p><b>restore 前缀安全</b>:还原一律复用 {@link #ID_ATTR} 正则逐个属性值精确匹配,绝不裸 {@code String.replace}
* 子串替换——否则净化 id {@code n1} 会误伤前缀相同的 {@code n1x}。映射外的 id(如设计器新增的 ASCII 节点)原样保留。</p>
*/
final class BpmnIdSanitizer {
private BpmnIdSanitizer() {
}
/** id/引用类属性(值须为合法 NCName);name/value 等展示属性不在内,避免改坏中文节点名。 */
static final Pattern ID_ATTR = Pattern.compile(
"\\b(id|bpmnElement|sourceRef|targetRef|attachedToRef|processRef|default)\\s*=\\s*\"([^\"]+)\"");
/** 净化结果:{@code xml}=净化后 XML;{@code idMap}=原 id→净化 id(双射,供 {@link #restore} 逆向)。 */
record Result(String xml, Map<String, String> idMap) {
}
/**
* 把 BPMN 里非法(非 ASCII NCName)的 id 及其全部引用一致重写为安全 ASCII id。
* 只重写 id/引用类属性,name 等展示属性不动。返回净化 XML 与「原 id→净化 id」映射。
*/
static Result sanitize(String xml) {
if (xml == null || xml.isEmpty()) {
return new Result(xml, Map.of());
}
// 先登记文档内所有合法 id,占位保证生成的净化 id 不与既有合法 id 冲突(双射 + restore 安全)。
Set<String> used = new LinkedHashSet<>();
Matcher scanLegal = ID_ATTR.matcher(xml);
while (scanLegal.find()) {
String val = scanLegal.group(2);
if (isValidNcName(val)) {
used.add(val);
}
}
// 收集非法 id → 唯一净化 id;基名冲突(含 hash 碰撞)时追加 -2/-3… 保双射。
Map<String, String> map = new LinkedHashMap<>();
Matcher scan = ID_ATTR.matcher(xml);
while (scan.find()) {
String val = scan.group(2);
if (!isValidNcName(val) && !map.containsKey(val)) {
String base = "n" + Integer.toHexString(val.hashCode() & 0x7fffffff);
String safe = base;
int seq = 2;
while (used.contains(safe)) {
safe = base + "-" + seq++;
}
map.put(val, safe);
used.add(safe);
}
}
if (map.isEmpty()) {
return new Result(xml, Map.of());
}
return new Result(rewrite(xml, map), map);
}
/**
* 依 {@code idMap}(原→净化)逆向还原:把净化 id 精确写回原 id。映射外的 id(如新增 ASCII 节点)原样保留。
* 逐个属性值精确匹配(复用 {@link #ID_ATTR}),前缀安全。
*/
static String restore(String xml, Map<String, String> idMap) {
if (xml == null || xml.isEmpty() || idMap == null || idMap.isEmpty()) {
return xml;
}
// 反转前校验双射:idMap 值(净化 id)重复会让 inverse 静默覆盖 → 还原错。fail-fast
// (T2.1 起 idMap 从 metaInfo JSON 反序列化,损坏数据须炸不能静默还原成别的 key)。
Map<String, String> inverse = new LinkedHashMap<>();
for (Map.Entry<String, String> e : idMap.entrySet()) {
String clash = inverse.put(e.getValue(), e.getKey());
if (clash != null) {
throw new IllegalArgumentException("idMap 非双射:净化 id \"" + e.getValue()
+ "\" 同时映射自 \"" + clash + "\" 与 \"" + e.getKey() + "\"");
}
}
return rewrite(xml, inverse);
}
/**
* 逐个 id/引用类属性值按 {@code map} 精确替换(命中才换,未命中原样)。前缀安全:只锚定完整属性值。
* 未改值的属性原样回写(append group(0) 原文),不重构 → 不归一 {@code id = "x"} 这类等号周围空白,保逐字节契约。
*/
private static String rewrite(String xml, Map<String, String> map) {
Matcher rw = ID_ATTR.matcher(xml);
StringBuilder sb = new StringBuilder();
while (rw.find()) {
String val = rw.group(2);
String repl = map.getOrDefault(val, val);
String replacement = repl.equals(val) ? rw.group(0) : rw.group(1) + "=\"" + repl + "\"";
rw.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
rw.appendTail(sb);
return sb.toString();
}
/** ASCII NCName:首字符字母/下划线,其余字母/数字/下划线/连字符/点;非 ASCII(中文等)视为非法。 */
private static boolean isValidNcName(String s) {
if (s == null || s.isEmpty()) {
return false;
}
char c0 = s.charAt(0);
if (!((c0 >= 'A' && c0 <= 'Z') || (c0 >= 'a' && c0 <= 'z') || c0 == '_')) {
return false;
}
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| c == '_' || c == '-' || c == '.')) {
return false;
}
}
return true;
}
}

View File

@@ -11,6 +11,7 @@ import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -109,63 +110,70 @@ public class ProcessDiagramController {
return ResponseEntity.ok(resp);
}
/** id/引用类属性(需为合法 NCName;name/value 等展示属性不在内,避免改坏中文节点名)。 */
private static final java.util.regex.Pattern ID_ATTR = java.util.regex.Pattern.compile(
"\\b(id|bpmnElement|sourceRef|targetRef|attachedToRef|processRef|default)\\s*=\\s*\"([^\"]+)\"");
/**
* 把 BPMN 里非法(非 ASCII NCName)的 id 及其全部引用一致重写为安全 ASCII id(稳定哈希),
* 使 bpmn-js 能解析渲染。只重写 id/引用类属性,name 等展示属性不动。同步重映射 active/finished 节点 id。
*/
static String sanitizeBpmnIds(String xml, List<String> active, List<String> finished) {
if (xml == null || xml.isEmpty()) {
return xml;
}
// 1. 收集所有非法 id 值 → 安全 id 映射
java.util.Map<String, String> map = new java.util.LinkedHashMap<>();
java.util.regex.Matcher scan = ID_ATTR.matcher(xml);
while (scan.find()) {
String val = scan.group(2);
if (!isValidNcName(val) && !map.containsKey(val)) {
map.put(val, "n" + Integer.toHexString(val.hashCode() & 0x7fffffff));
}
}
if (map.isEmpty()) {
return xml;
}
// 2. 仅重写 id/引用类属性(appendReplacement 精确,不误伤 name=)
java.util.regex.Matcher rw = ID_ATTR.matcher(xml);
StringBuilder sb = new StringBuilder();
while (rw.find()) {
String attr = rw.group(1);
String val = rw.group(2);
String repl = map.getOrDefault(val, val);
rw.appendReplacement(sb, java.util.regex.Matcher.quoteReplacement(attr + "=\"" + repl + "\""));
}
rw.appendTail(sb);
// 3. 同步重映射返回的当前/历史节点 id
active.replaceAll(id -> map.getOrDefault(id, id));
finished.replaceAll(id -> map.getOrDefault(id, id));
return sb.toString();
@GetMapping("/process-definitions/{procDefId}/source")
@Operation(summary = "按流程定义 id 取净化源 XML",
description = "返回 {procDefId, found, bpmnXml(净化后), idMap(原id→净化id), procDefKey, version},供 bpmn-js Modeler 在线编辑载入。"
+ "流程定义不存在 / BPMN 读取失败或为空 → found=false(HTTP 200,前端降级)。"
+ "中文 process id 经 BpmnIdSanitizer 可逆净化,idMap 供发布时逆向还原原 key(D7)。")
public ResponseEntity<Map<String, Object>> source(@PathVariable String procDefId) {
ProcessDefinition def = repositoryService.createProcessDefinitionQuery()
.processDefinitionId(procDefId).singleResult();
return sourceResponse(procDefId, def);
}
/** ASCII NCName:首字符字母/下划线,其余字母/数字/下划线/连字符/点;非 ASCII(中文等)视为非法。 */
private static boolean isValidNcName(String s) {
if (s == null || s.isEmpty()) {
return false;
@GetMapping("/process-definitions/by-key/{key}/source")
@Operation(summary = "按流程 key 取最新版净化源 XML",
description = "返回与 by-id 端点完全相同的形状 {procDefId, found, bpmnXml, idMap, procDefKey, version},"
+ "供 Modeler 打开器按真流程 key 载入(process-select 的 source='model' 项 id 是 act_re_model id 而非 procDefId,"
+ "by-id 永远 found:false → 改用本端点)。processDefinitionKey(key).latestVersion() 取最新版,key 不存在 found:false。")
public ResponseEntity<Map<String, Object>> sourceByKey(@PathVariable String key) {
ProcessDefinition def = repositoryService.createProcessDefinitionQuery()
.processDefinitionKey(key).latestVersion().singleResult();
String procDefId = def == null ? null : def.getId();
return sourceResponse(procDefId, def);
}
/**
* 按已解析的流程定义构建源响应(by-id / by-key 共用,逻辑单一不复制):净化 XML + 原→净化 idMap + key/version。
* {@code def==null}(不存在)或 BPMN 空/读失败 → {@code found:false}(HTTP 200,前端降级)。
* {@code procDefId} 是读取部署 BPMN 资源用的定义 id(by-id=入参、by-key=解析出的最新版 id),命中时随响应回显。
*/
private ResponseEntity<Map<String, Object>> sourceResponse(String procDefId, ProcessDefinition def) {
Map<String, Object> resp = new LinkedHashMap<>();
if (procDefId != null) {
resp.put("procDefId", procDefId);
}
char c0 = s.charAt(0);
if (!((c0 >= 'A' && c0 <= 'Z') || (c0 >= 'a' && c0 <= 'z') || c0 == '_')) {
return false;
if (def == null) {
resp.put("found", false);
return ResponseEntity.ok(resp);
}
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| c == '_' || c == '-' || c == '.')) {
return false;
}
String bpmnXml = readProcessModel(procDefId);
if (bpmnXml == null || bpmnXml.isBlank()) {
log.warn("[流程源] BPMN 为空或读取失败 procDefId={}", procDefId);
resp.put("found", false);
return ResponseEntity.ok(resp);
}
return true;
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(bpmnXml);
resp.put("found", true);
resp.put("bpmnXml", r.xml());
resp.put("idMap", r.idMap());
resp.put("procDefKey", def.getKey());
resp.put("version", def.getVersion());
return ResponseEntity.ok(resp);
}
/**
* 把 BPMN 里非法(非 ASCII NCName)的 id 及其全部引用一致重写为安全 ASCII id,使 bpmn-js 能解析渲染,
* 并同步重映射 active/finished 节点 id。净化算法委托 {@link BpmnIdSanitizer}(含可逆映射与 hash 碰撞消解)。
*/
static String sanitizeBpmnIds(String xml, List<String> active, List<String> finished) {
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
Map<String, String> map = r.idMap();
active.replaceAll(id -> map.getOrDefault(id, id));
finished.replaceAll(id -> map.getOrDefault(id, id));
return r.xml();
}
/** 读流程定义 BPMN XML(getProcessModel 返回部署的 BPMN 资源流)。读失败返回 null(前端降级)。 */

View File

@@ -0,0 +1,223 @@
package com.eip4.flowservice.api;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
/**
* BpmnIdSanitizer 可逆双射单测:净化(中文 id→安全 ASCII)与还原(restore)严格互逆,
* 覆盖 hash 碰撞消解、restore 前缀安全、合法 id 不动、混合场景。
*
* <p>非碰撞净化输出须与 ProcessDiagramController 旧实现逐字节一致(由既有 ProcessDiagramControllerTest 兜底),
* 本类聚焦「可逆」这一新增契约。</p>
*/
class BpmnIdSanitizerTest {
/** 中文 process id + processRef/sourceRef/targetRef/default/attachedToRef 全引用面净化→restore 须逐字节还原。 */
@Test
void 净化后还原_逐字节等于原文() {
String xml = """
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
<process id="总包合同交底" name="总包合同交底">
<startEvent id="start"/>
<userTask id="审批" name="审批人"/>
<boundaryEvent id="超时" attachedToRef="审批"/>
<exclusiveGateway id="gw" default="回退"/>
<sequenceFlow id="回退" sourceRef="gw" targetRef="审批"/>
<sequenceFlow id="通过" sourceRef="审批" targetRef="end"/>
<endEvent id="end"/>
</process>
<collaboration id="collab">
<participant id="part" processRef="总包合同交底"/>
</collaboration>
<bpmndi:BPMNDiagram id="di" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI">
<bpmndi:BPMNPlane bpmnElement="总包合同交底"/>
</bpmndi:BPMNDiagram>
</definitions>""";
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
// 中文 id 不再出现在 id/引用类属性中;name 展示属性照旧保留中文
assertThat(r.xml()).doesNotContain("id=\"总包合同交底\"");
assertThat(r.xml()).doesNotContain("processRef=\"总包合同交底\"");
assertThat(r.xml()).doesNotContain("attachedToRef=\"审批\"");
assertThat(r.xml()).contains("name=\"总包合同交底\"");
assertThat(r.xml()).contains("name=\"审批人\"");
// idMap 覆盖全部 5 个中文 id(合法 ASCII id 不入 map)
assertThat(r.idMap()).containsOnlyKeys("总包合同交底", "审批", "超时", "回退", "通过");
// restore 逐字节还原
assertThat(BpmnIdSanitizer.restore(r.xml(), r.idMap())).isEqualTo(xml);
}
/**
* hash 碰撞消解:Java String.hashCode 下 "中Aa" 与 "中BB" 撞哈希('A'*31+'a' == 'B'*31+'B' == 2112),
* 二者又都是非法 NCName(含中文)→ 旧实现会撞成同一净化 id(非双射)。sanitize 须给两者不同净化 id,restore 仍完整还原。
*/
@Test
void 撞哈希两中文id_净化后仍双射可逆() {
// 前置自证:确实撞哈希
assertThat("中Aa".hashCode()).isEqualTo("中BB".hashCode());
String xml = """
<definitions>
<process id="p">
<userTask id="中Aa"/>
<userTask id="中BB"/>
<sequenceFlow id="f1" sourceRef="中Aa" targetRef="中BB"/>
</process>
</definitions>""";
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
String s1 = r.idMap().get("中Aa");
String s2 = r.idMap().get("中BB");
// 双射:两净化 id 互不相同(否则 sourceRef/targetRef 引用会串)
assertThat(s1).isNotNull();
assertThat(s2).isNotNull();
assertThat(s1).isNotEqualTo(s2);
// 碰撞消解序号:其一为基名,另一为基名 +"-2"
assertThat(s1 + "|" + s2).containsPattern("-2");
// 净化后中文 id 消失
assertThat(r.xml()).doesNotContain("中Aa");
assertThat(r.xml()).doesNotContain("中BB");
// restore 逐字节还原(引用不串)
assertThat(BpmnIdSanitizer.restore(r.xml(), r.idMap())).isEqualTo(xml);
}
/**
* restore 前缀安全:idMap 同时含净化 id "n1" 与 "n1x"(后者以前者为前缀)。
* 裸 String.replace("n1",..) 会把 "n1x" 误伤成 "<orig1>x";必须锚定完整属性值精确匹配。
*/
@Test
void restore前缀安全_n1不误伤n1x() {
Map<String, String> idMap = new LinkedHashMap<>();
idMap.put("原A", "n1");
idMap.put("原B", "n1x");
String xml = "<userTask id=\"n1x\"/><sequenceFlow id=\"f\" sourceRef=\"n1\" targetRef=\"n1x\"/>";
String out = BpmnIdSanitizer.restore(xml, idMap);
assertThat(out).isEqualTo("<userTask id=\"原B\"/><sequenceFlow id=\"f\" sourceRef=\"原A\" targetRef=\"原B\"/>");
assertThat(out).doesNotContain("原Ax"); // 无前缀误伤
assertThat(out).doesNotContain("n1x");
assertThat(out).doesNotContain("n1\"");
}
/** 全合法 NCName id:不改写,idMap 为空,restore 无副作用。 */
@Test
void 合法NCName_id不改写_映射为空() {
String xml = "<process id=\"p\"><userTask id=\"sid-A\"/>"
+ "<sequenceFlow id=\"f1\" sourceRef=\"p\" targetRef=\"sid-A\" default=\"f1\"/></process>";
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
assertThat(r.idMap()).isEmpty();
assertThat(r.xml()).isEqualTo(xml);
// 空 idMap 的 restore 原样返回
assertThat(BpmnIdSanitizer.restore(xml, r.idMap())).isEqualTo(xml);
}
/** 混合:部分中文部分合法,只映射中文者;合法 id 原样保留;restore 还原。 */
@Test
void 混合_只映射中文id_合法id原样保留() {
String xml = "<process id=\"审批流程\"><userTask id=\"legalTask\"/>"
+ "<sequenceFlow id=\"f1\" sourceRef=\"审批流程\" targetRef=\"legalTask\"/></process>";
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
assertThat(r.idMap()).containsOnlyKeys("审批流程");
assertThat(r.xml()).contains("id=\"legalTask\"");
assertThat(r.xml()).contains("targetRef=\"legalTask\"");
assertThat(r.xml()).doesNotContain("审批流程");
assertThat(BpmnIdSanitizer.restore(r.xml(), r.idMap())).isEqualTo(xml);
}
/** restore 只回写映射内 id;净化后新增的 ASCII 节点 id(不在 idMap)原样保留。 */
@Test
void restore只回写映射内id_新增ascii_id保留() {
Map<String, String> idMap = new LinkedHashMap<>();
idMap.put("审批", "n5");
// n9 是设计器新增节点,不在 idMap → restore 不得改动
String xml = "<userTask id=\"n5\"/><userTask id=\"n9\"/>"
+ "<sequenceFlow id=\"f\" sourceRef=\"n5\" targetRef=\"n9\"/>";
String out = BpmnIdSanitizer.restore(xml, idMap);
assertThat(out).isEqualTo("<userTask id=\"审批\"/><userTask id=\"n9\"/>"
+ "<sequenceFlow id=\"f\" sourceRef=\"审批\" targetRef=\"n9\"/>");
}
/** null/空 XML 防御:不抛,idMap 为空。 */
@Test
void 空xml不抛_映射为空() {
assertThat(BpmnIdSanitizer.sanitize(null).idMap()).isEmpty();
assertThat(BpmnIdSanitizer.sanitize("").idMap()).isEmpty();
assertThat(BpmnIdSanitizer.restore(null, Map.of())).isNull();
assertThat(BpmnIdSanitizer.restore("<a/>", Map.of())).isEqualTo("<a/>");
}
/**
* 生成的净化 id 不与文档内既有合法字面 id 冲突(used 占位契约)。
* "审批".hashCode()&0x7fffffff 的 hex 恰为 b7af8 → 基名 "nb7af8" 与合法字面 id "nb7af8" 撞
* → sanitize 须让 审批 映射为 nb7af8-2(否则 restore 会误改那个合法 id),restore 逐字节还原。
*/
@Test
void 净化id不与既有合法id冲突_让位加序号() {
assertThat(Integer.toHexString("审批".hashCode() & 0x7fffffff)).isEqualTo("b7af8"); // 前置自证
String xml = """
<process id="p">
<userTask id="nb7af8"/>
<userTask id="审批"/>
<sequenceFlow id="f" sourceRef="nb7af8" targetRef="审批"/>
</process>""";
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
// 中文 id 让位到 -2;既有合法字面 id nb7af8 原样不动、不入 map
assertThat(r.idMap()).containsOnlyKeys("审批");
assertThat(r.idMap().get("审批")).isEqualTo("nb7af8-2");
assertThat(r.xml()).contains("id=\"nb7af8\"");
assertThat(r.xml()).contains("sourceRef=\"nb7af8\"");
assertThat(BpmnIdSanitizer.restore(r.xml(), r.idMap())).isEqualTo(xml);
}
/**
* M-1 逐字节契约:未改值的合法属性(含等号周围空白)须原样回写,不被重构归一。
* 即便 map 非空(另有中文 id 被改),带空白的合法属性 round-trip 后原文不变。
*/
@Test
void 未改值属性含等号空白_原样保留不归一() {
// legalTask 用 `id = "..."`(等号带空格)合法写法;审批 是被净化的中文 id → map 非空
String xml = "<userTask id = \"legalTask\"/>"
+ "<userTask id=\"审批\"/>"
+ "<sequenceFlow id=\"f\" sourceRef=\"legalTask\" targetRef=\"审批\"/>";
BpmnIdSanitizer.Result r = BpmnIdSanitizer.sanitize(xml);
// 审批被改;legalTask 的等号空白写法逐字保留(旧实现会归一成 id="legalTask")
assertThat(r.idMap()).containsOnlyKeys("审批");
assertThat(r.xml()).contains("id = \"legalTask\"");
// round-trip 后原文逐字节不变
assertThat(BpmnIdSanitizer.restore(r.xml(), r.idMap())).isEqualTo(xml);
}
/** M-2 fail-fast:idMap 值(净化 id)重复=非双射(损坏 metaInfo),restore 抛而非静默还原错。 */
@Test
void restore_idMap值重复_抛非双射异常() {
Map<String, String> broken = new LinkedHashMap<>();
broken.put("原A", "n1");
broken.put("原B", "n1"); // 两个原 id 映到同一净化 id → 反转会静默覆盖
String xml = "<userTask id=\"n1\"/>";
org.assertj.core.api.Assertions.assertThatThrownBy(() -> BpmnIdSanitizer.restore(xml, broken))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("非双射")
.hasMessageContaining("n1");
}
}

View File

@@ -17,6 +17,8 @@ import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricActivityInstanceQuery;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.runtime.ProcessInstanceQuery;
import org.junit.jupiter.api.BeforeEach;
@@ -39,6 +41,7 @@ class ProcessDiagramControllerTest {
@Mock ProcessInstanceQuery processInstanceQuery;
@Mock HistoricProcessInstanceQuery historicProcessInstanceQuery;
@Mock HistoricActivityInstanceQuery historicActivityInstanceQuery;
@Mock ProcessDefinitionQuery processDefinitionQuery;
MockMvc mvc;
@@ -150,4 +153,105 @@ class ProcessDiagramControllerTest {
org.junit.jupiter.api.Assertions.assertEquals(safe, finished.get(0));
org.junit.jupiter.api.Assertions.assertEquals("sid-A", active.get(0));
}
@Test
void source_按procDefId返净化XML与idMap及key版本() throws Exception {
// 存量流程 process id 为中文(如「总包合同交底」),moddle 载入前须净化;端点透出原→净化映射供发布时逆向。
ProcessDefinition def = org.mockito.Mockito.mock(ProcessDefinition.class);
when(def.getKey()).thenReturn("总包合同交底");
when(def.getVersion()).thenReturn(3);
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.processDefinitionId("def-1")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(def);
String xml = "<definitions>"
+ "<process id=\"总包合同交底\" name=\"总包合同交底\">"
+ "<userTask id=\"sid-A\"/>"
+ "<sequenceFlow id=\"f1\" sourceRef=\"总包合同交底\" targetRef=\"sid-A\"/>"
+ "</process></definitions>";
when(repositoryService.getProcessModel("def-1"))
.thenReturn(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
mvc.perform(get("/api/flow/process-definitions/def-1/source"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true))
.andExpect(jsonPath("$.procDefKey").value("总包合同交底"))
.andExpect(jsonPath("$.version").value(3))
// idMap 非空且含中文原 key;净化后 XML 的 id 属性不再含中文(name 展示位不受影响)
.andExpect(jsonPath("$.idMap").isNotEmpty())
.andExpect(jsonPath("$.idMap['总包合同交底']").isNotEmpty())
.andExpect(jsonPath("$.bpmnXml",
org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("id=\"总包合同交底\""))))
// sequenceFlow 的 sourceRef 引用也须随 process id 一致重写,不白放(评审 M-1)
.andExpect(jsonPath("$.bpmnXml",
org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("sourceRef=\"总包合同交底\""))));
}
@Test
void source_定义不存在返found_false() throws Exception {
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.processDefinitionId("nope")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(null);
mvc.perform(get("/api/flow/process-definitions/nope/source"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(false));
}
@Test
void sourceByKey_按key命中返最新版净化XML与idMap及版本() throws Exception {
// process-select options 的 source='model' 项 id 是 act_re_model id(非 procDefId),by-id 永远 found:false;
// 打开器改用 option.key(真流程 key)走本端点。latestVersion() 在两版本(v1/v2)里取 v2。
ProcessDefinition v2 = org.mockito.Mockito.mock(ProcessDefinition.class);
when(v2.getId()).thenReturn("总包合同交底:2:aa22");
when(v2.getKey()).thenReturn("总包合同交底");
when(v2.getVersion()).thenReturn(2);
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.processDefinitionKey("总包合同交底")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.latestVersion()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(v2);
String xml = "<definitions>"
+ "<process id=\"总包合同交底\" name=\"总包合同交底\">"
+ "<userTask id=\"sid-A\"/>"
+ "<sequenceFlow id=\"f1\" sourceRef=\"总包合同交底\" targetRef=\"sid-A\"/>"
+ "</process></definitions>";
when(repositoryService.getProcessModel("总包合同交底:2:aa22"))
.thenReturn(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
mvc.perform(get("/api/flow/process-definitions/by-key/{key}/source", "总包合同交底"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true))
.andExpect(jsonPath("$.procDefId").value("总包合同交底:2:aa22"))
.andExpect(jsonPath("$.procDefKey").value("总包合同交底"))
.andExpect(jsonPath("$.version").value(2))
.andExpect(jsonPath("$.idMap['总包合同交底']").isNotEmpty())
.andExpect(jsonPath("$.bpmnXml",
org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("id=\"总包合同交底\""))));
}
@Test
void sourceByKey_key不存在返found_false() throws Exception {
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.processDefinitionKey("无此流程")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.latestVersion()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(null);
mvc.perform(get("/api/flow/process-definitions/by-key/{key}/source", "无此流程"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(false));
}
@Test
void source_读取XML异常返found_false不抛500() throws Exception {
ProcessDefinition def = org.mockito.Mockito.mock(ProcessDefinition.class);
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.processDefinitionId("def-x")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(def);
when(repositoryService.getProcessModel("def-x")).thenThrow(new RuntimeException("boom"));
mvc.perform(get("/api/flow/process-definitions/def-x/source"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(false));
}
}

View File

@@ -64,8 +64,18 @@ public final class EngineContextBinder {
* DB 校验 {@code TRIM(account)='admin'}(精确小写)。不放宽成大小写不敏感,避免因 {@code SYS_USER.ACCOUNT}
* 无唯一约束、建号去重又区分大小写而把 {@code 'Admin'} 这类变体账号静默提权(安全评审 M-1)。</li>
* </ul>
*
* <p><b>时效性(time-of-check)</b>:userId/account 均取自 JWT claim(token 签发时的身份快照),
* <strong>不实时查库</strong>。故在 token 有效期内,若 admin 账号被改名/停用/降权,本判定仍按签发时结果放行——
* 由 token TTL 兜底,安全敏感的提权变更需配合短 TTL 或主动吊销 token 方能即时生效。
*
* <p>公开为 {@code public static} 供网关层复用(流程 Modeler 超管门,flowable-service 裸 8089
* 无安全栈 → 超管门唯一落点在网关,T1.6)。{@code null} 主体安全返回 {@code false}(未认证即非超管)。
*/
private static boolean isSystemAdmin(AuthPrincipal principal) {
public static boolean isSystemAdmin(AuthPrincipal principal) {
if (principal == null) {
return false;
}
String adminId = LoggedInUser.ADMIN.trim(); // "ADMIN"
String userId = principal.userId();
if (userId != null && adminId.equalsIgnoreCase(userId.trim())) {

View File

@@ -0,0 +1,75 @@
package com.eip4.platform.auth.security;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.dsasp.server.common.user.service.LoggedInUser;
/**
* {@link EngineContextBinder#isSystemAdmin} 判定单测:与全站 {@code requireAdmin} 逐口径对齐。
*
* <p>本方法在 T1.6 由 {@code private} 提升为 {@code public static},供 platform-flow-gateway 的
* 流程 Modeler 超管门复用(网关层唯一保护点)。这里锁定其行为契约,防提升可见性后被随意放宽:
* ADMIN 大小写不敏感 + 去补白、account 大小写敏感等于 admin、含 "admin" 字样的普通用户不误判、null 安全。
*/
class EngineContextBinderAdminTest {
private static AuthPrincipal user(String userId, String account) {
return new AuthPrincipal(userId, account, "n", null, null, List.of());
}
@Test
void userId为ADMIN_判超管() {
assertThat(EngineContextBinder.isSystemAdmin(user("ADMIN", "someacct"))).isTrue();
}
@Test
void userId小写admin_大小写不敏感判超管() {
assertThat(EngineContextBinder.isSystemAdmin(user("admin", "someacct"))).isTrue();
}
@Test
void userId带补白_去补白后判超管() {
// 引擎 CURRENTUSER 是 CHAR(36) 补白常量("ADMIN" + 31 空格),trim 后判真
assertThat(EngineContextBinder.isSystemAdmin(user(LoggedInUser.ADMIN, "someacct"))).isTrue();
assertThat(EngineContextBinder.isSystemAdmin(user(" ADMIN ", "someacct"))).isTrue();
}
@Test
void account为admin_userId非admin_判超管() {
assertThat(EngineContextBinder.isSystemAdmin(user("U1", "admin"))).isTrue();
assertThat(EngineContextBinder.isSystemAdmin(user("U1", " admin "))).isTrue();
}
@Test
void account大小写敏感_Admin变体不判超管() {
// SYS_USER.ACCOUNT 无唯一约束,'Admin' 这类变体账号不得静默提权(安全评审 M-1)
assertThat(EngineContextBinder.isSystemAdmin(user("U1", "Admin"))).isFalse();
}
@Test
void 含admin字样的普通用户_不误判() {
assertThat(EngineContextBinder.isSystemAdmin(user("USER_ADMINISTRATOR", "user_admin"))).isFalse();
}
@Test
void 普通用户_非超管() {
assertThat(EngineContextBinder.isSystemAdmin(user("U1", "zhangsan"))).isFalse();
}
@Test
void userId空串或空白且account非admin_非超管() {
// principal 非 null 但 userId 空/空白(trim 后非 ADMIN),account 也非 admin → 两分支均判假,不越权
assertThat(EngineContextBinder.isSystemAdmin(user("", "zhangsan"))).isFalse();
assertThat(EngineContextBinder.isSystemAdmin(user(" ", "zhangsan"))).isFalse();
assertThat(EngineContextBinder.isSystemAdmin(user(null, "zhangsan"))).isFalse();
}
@Test
void null主体_null安全返回false() {
assertThat(EngineContextBinder.isSystemAdmin(null)).isFalse();
}
}

View File

@@ -226,6 +226,40 @@ public class FlowableClient {
.body(Map.class));
}
/**
* 按流程定义 id 取净化源 XML(供 bpmn-js Modeler 在线编辑载入)。对应 flowable-service
* {@code GET /api/flow/process-definitions/{procDefId}/source},返回体
* {@code {procDefId, found, bpmnXml(净化后), idMap(原id→净化id), procDefKey, version}}。
*
* <p><b>中文 procDefId 编码</b>:真实 procDefId 形如 {@code 总包合同交底:3:<uuid>}(中文 key + 冒号)。
* procDefId 作为 uri 变量传入({@code .uri(template, procDefId)}),由 {@code RestClient} 严格编码
* (中文 percent 编码、冒号 → {@code %3A});<b>绝不字符串拼 URL</b>(拼接会把冒号当分隔符裸传,
* 且中文可能编码不一致)。
*/
@SuppressWarnings("unchecked")
public Map<String, Object> procDefSource(String procDefId) {
return execute("流程源", () -> restClient.get()
.uri("/api/flow/process-definitions/{id}/source", procDefId)
.retrieve()
.body(Map.class));
}
/**
* 按流程 key 取最新版净化源 XML(供 Modeler 打开器按真流程 key 载入)。对应 flowable-service
* {@code GET /api/flow/process-definitions/by-key/{key}/source},返回体与 {@link #procDefSource} 同形状。
*
* <p>process-select 的 {@code source='model'} 选项 id 是 act_re_model id 而非 procDefId,
* by-id 端点永远 {@code found:false} → 打开器改用真流程 key 走本路。key 同样作为 uri 变量严格编码
* (纯中文 key percent 编码),<b>绝不字符串拼 URL</b>。
*/
@SuppressWarnings("unchecked")
public Map<String, Object> procDefSourceByKey(String key) {
return execute("流程源(按key)", () -> restClient.get()
.uri("/api/flow/process-definitions/by-key/{key}/source", key)
.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()

View File

@@ -0,0 +1,75 @@
package com.eip4.platform.flowgateway.web;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
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.client.FlowableClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
* 在线流程 Modeler 网关门面:把 flowable-service 的流程定义/草稿能力经<b>超管门</b>暴露给设计器前端。
*
* <p>flowable-service 裸 8089 无 Spring Security → 流程编辑/部署面的鉴权唯一落点在本网关层。
* 本控制器所有端点先过超管门({@link EngineContextBinder#isSystemAdmin},与全站 {@code requireAdmin}
* 逐口径对齐),非超管返回 403,过门后转发 {@link FlowableClient},返回体原样透传。
*
* <p>阶段 1(T1.6):只读载入存量流程源 XML。草稿 CRUD / 发布门在后续阶段接入本控制器。
*/
@Tag(name = "流程 Modeler 网关", description = "流程设计器:超管门 + flowable-service 转发(存量源载入/草稿/发布)")
@RestController
@RequestMapping("/api/workflow")
public class ProcessModelerController {
private final FlowableClient flowableClient;
public ProcessModelerController(FlowableClient flowableClient) {
this.flowableClient = flowableClient;
}
@Operation(summary = "按流程定义 id 取净化源 XML(超管)",
description = "超管门后转发 flowable-service /api/flow/process-definitions/{procDefId}/source,"
+ "返回 {procDefId, found, bpmnXml(净化后), idMap, procDefKey, version} 供 bpmn-js Modeler 载入。"
+ "非超管 403。中文 procDefId 由 FlowableClient 以 uri 变量严格编码转发。")
@GetMapping("/process-definitions/{procDefId}/source")
public ResponseEntity<Map<String, Object>> source(@AuthenticationPrincipal AuthPrincipal principal,
@PathVariable String procDefId) {
if (!EngineContextBinder.isSystemAdmin(principal)) {
return forbidden();
}
return ResponseEntity.ok(flowableClient.procDefSource(procDefId));
}
@Operation(summary = "按流程 key 取最新版净化源 XML(超管)",
description = "超管门后转发 flowable-service /api/flow/process-definitions/by-key/{key}/source,"
+ "返回与 by-id 端点同形状。打开器对 process-select 的 source='model' 选项改用真流程 key 走本路"
+ "(该选项 id 是 act_re_model id 非 procDefId,by-id 永远 found:false)。非超管 403。"
+ "中文 key 由 FlowableClient 以 uri 变量严格编码转发。")
@GetMapping("/process-definitions/by-key/{key}/source")
public ResponseEntity<Map<String, Object>> sourceByKey(@AuthenticationPrincipal AuthPrincipal principal,
@PathVariable String key) {
if (!EngineContextBinder.isSystemAdmin(principal)) {
return forbidden();
}
return ResponseEntity.ok(flowableClient.procDefSourceByKey(key));
}
/** 超管门未过:403 + {status:1,msg} 风格对齐既有网关端点。 */
private static ResponseEntity<Map<String, Object>> forbidden() {
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", 1);
body.put("msg", "仅系统管理员可用");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
}
}

View File

@@ -2,6 +2,11 @@ package com.eip4.platform.flowgateway;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
@@ -199,4 +204,78 @@ class FlowableClientTest {
assertThat(result).containsEntry("businessKey", "BK-1");
server.verify();
}
// ---- 流程源(Modeler 载入):中文 procDefId 编码硬验收(T1.4 评审 M-2) ----
/**
* 真实 procDefId 形如 {@code 总包合同交底:3:<uuid>}(中文 key + 冒号进 path segment)。
* procDefId 必须作为 uri 变量被严格编码转发——冒号编码为 {@code %3A}、中文 percent 编码,绝无裸传。
* 关键判别:字符串拼接会把冒号当 path 分隔符保留裸 {@code ':'};只有 uri 变量展开才会编码成 {@code %3A}。
*/
@Test
void 取流程源_中文procDefId作为uri变量严格编码不裸传() {
FlowGatewayProperties p = props();
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
String procDefId = "总包合同交底:3:abc123";
server.expect(ExpectedCount.once(), requestTo(allOf(
startsWith("http://localhost:8089/api/flow/process-definitions/"),
endsWith("/source"),
containsString("%3A3%3Aabc123"), // 两个冒号均编码为 %3A(证明走 uri 变量非拼接)
not(containsString("总包合同交底"))))) // 中文未裸传(已 percent 编码)
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("{\"found\":true,\"procDefKey\":\"总包合同交底\",\"version\":3}",
MediaType.APPLICATION_JSON));
FlowableClient client = new FlowableClient(builder.build(), p);
Map<String, Object> resp = client.procDefSource(procDefId);
assertThat(resp).containsEntry("procDefKey", "总包合同交底");
assertThat(resp).containsEntry("found", true);
server.verify();
}
/**
* by-key 端点:process-select options 的 source='model' 项 id 非 procDefId,打开器改用真流程 key 走此路。
* 纯中文 key「总包合同交底」作为 uri 变量严格编码转发——percent 编码,绝无裸中文。
*/
@Test
void 取流程源按key_纯中文key作为uri变量严格编码不裸传() {
FlowGatewayProperties p = props();
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
String key = "总包合同交底";
server.expect(ExpectedCount.once(), requestTo(allOf(
startsWith("http://localhost:8089/api/flow/process-definitions/by-key/"),
endsWith("/source"),
containsString("%E6%80%BB"), // 「总」的 UTF-8 percent 编码,证明已编码
not(containsString("总包合同交底"))))) // 中文未裸传
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("{\"found\":true,\"procDefKey\":\"总包合同交底\",\"version\":2}",
MediaType.APPLICATION_JSON));
FlowableClient client = new FlowableClient(builder.build(), p);
Map<String, Object> resp = client.procDefSourceByKey(key);
assertThat(resp).containsEntry("procDefKey", "总包合同交底");
assertThat(resp).containsEntry("found", true);
server.verify();
}
@Test
void 取流程源_下游4xx透传FlowRemote且不重试() {
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/process-definitions/X/source"))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.BAD_REQUEST).body("bad procDefId"));
FlowableClient client = new FlowableClient(builder.build(), p);
assertThatThrownBy(() -> client.procDefSource("X"))
.isInstanceOf(FlowRemoteException.class)
.satisfies(e -> assertThat(((FlowRemoteException) e).getStatus().value()).isEqualTo(400));
server.verify();
}
}

View File

@@ -0,0 +1,194 @@
package com.eip4.platform.flowgateway;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
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 static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
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.client.FlowServiceUnavailableException;
import com.eip4.platform.flowgateway.client.FlowableClient;
import com.eip4.platform.flowgateway.web.FlowGatewayExceptionHandler;
import com.eip4.platform.flowgateway.web.ProcessModelerController;
/**
* 流程 Modeler 网关转发单测:超管门 + source 透传 + 引擎不可达上抛(由既有 handler 映射 503)。
* 中文 procDefId 全链编码在 {@link FlowableClientTest} 覆盖(客户端层),此处覆盖门控与透传语义。
*/
class ProcessModelerControllerTest {
private final FlowableClient flowableClient = mock(FlowableClient.class);
private final ProcessModelerController controller = new ProcessModelerController(flowableClient);
/** 真实形态:中文 key + 冒号分隔的 procDefId。 */
private static final String CN_PROCDEF = "总包合同交底:3:abc123";
private static AuthPrincipal admin() {
return new AuthPrincipal("ADMIN", "admin", "管理员", null, null, List.of());
}
/** 含 "admin" 字样但非超管的普通用户(account=user_admin ≠ admin)。 */
private static AuthPrincipal normalUser() {
return new AuthPrincipal("U1", "user_admin", "张三", "D1", "O1", List.of("R1"));
}
@Test
void 超管_透传下游净化源XML返回200() {
Map<String, Object> downstream = Map.of("found", true, "procDefKey", "总包合同交底",
"bpmnXml", "<definitions/>", "idMap", Map.of("总包合同交底", "n1a2b3"), "version", 3);
when(flowableClient.procDefSource(CN_PROCDEF)).thenReturn(downstream);
ResponseEntity<Map<String, Object>> resp = controller.source(admin(), CN_PROCDEF);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(resp.getBody()).isEqualTo(downstream);
verify(flowableClient).procDefSource(CN_PROCDEF);
}
@Test
void 非超管_403且不触发下游调用() {
ResponseEntity<Map<String, Object>> resp = controller.source(normalUser(), CN_PROCDEF);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(resp.getBody()).containsEntry("status", 1).containsEntry("msg", "仅系统管理员可用");
verify(flowableClient, never()).procDefSource(anyString());
}
@Test
void 无身份_403且不触发下游调用() {
ResponseEntity<Map<String, Object>> resp = controller.source(null, CN_PROCDEF);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(resp.getBody()).containsEntry("status", 1);
verify(flowableClient, never()).procDefSource(anyString());
}
@Test
void 引擎不可达_异常上抛由既有handler映射503() {
when(flowableClient.procDefSource(CN_PROCDEF))
.thenThrow(new FlowServiceUnavailableException("flowable-service 不可达", null));
// 控制器不吞异常:FlowServiceUnavailableException 上抛 → FlowGatewayExceptionHandler.onUnavailable 映射 503
assertThatThrownBy(() -> controller.source(admin(), CN_PROCDEF))
.isInstanceOf(FlowServiceUnavailableException.class);
verify(flowableClient).procDefSource(CN_PROCDEF);
}
// ---- by-key:process-select options=model 的语义缺口修复,打开器用真流程 key ----
private static final String CN_KEY = "总包合同交底";
@Test
void byKey_超管_透传下游源XML返回200() {
Map<String, Object> downstream = Map.of("found", true, "procDefId", "总包合同交底:2:aa22",
"procDefKey", "总包合同交底", "bpmnXml", "<definitions/>", "idMap", Map.of(), "version", 2);
when(flowableClient.procDefSourceByKey(CN_KEY)).thenReturn(downstream);
ResponseEntity<Map<String, Object>> resp = controller.sourceByKey(admin(), CN_KEY);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(resp.getBody()).isEqualTo(downstream);
verify(flowableClient).procDefSourceByKey(CN_KEY);
}
@Test
void byKey_非超管_403且不触发下游调用() {
ResponseEntity<Map<String, Object>> resp = controller.sourceByKey(normalUser(), CN_KEY);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(resp.getBody()).containsEntry("status", 1).containsEntry("msg", "仅系统管理员可用");
verify(flowableClient, never()).procDefSourceByKey(anyString());
}
// ---- 胶水层(MockMvc + FlowGatewayExceptionHandler):I-1 ----
// 覆盖三件此前直调单测碰不到的真实 MVC 行为:①引擎不可达经既有 handler 出 503 通用信封
// (FlowGatewayExceptionHandler 全仓首个测试) ②正常路径 200 透传 ③MVC 层把 percent 编码中文 path
// variable 正确解码回原串交给控制器。@AuthenticationPrincipal 在 standalone 无 Security 上下文,
// 用自定义参数解析器恒注入超管(门控通过与否由直调单测覆盖,这里只验 MVC 编码/异常映射管道)。
private MockMvc glueMvc() {
HandlerMethodArgumentResolver adminPrincipal = new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return AuthPrincipal.class.equals(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mav,
NativeWebRequest req, WebDataBinderFactory bf) {
return admin();
}
};
return MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new FlowGatewayExceptionHandler())
.setCustomArgumentResolvers(adminPrincipal)
.build();
}
@Test
void 胶水_byId_MVC解码percent中文pathVar并200透传() throws Exception {
Map<String, Object> downstream = Map.of("found", true, "procDefKey", "总包合同交底", "version", 3);
when(flowableClient.procDefSource(CN_PROCDEF)).thenReturn(downstream);
glueMvc().perform(get("/api/workflow/process-definitions/{procDefId}/source", CN_PROCDEF))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true))
.andExpect(jsonPath("$.procDefKey").value("总包合同交底"));
// 关键:MVC 层把 %E6.. / %3A 解码回「总包合同交底:3:abc123」原串交给控制器(③编码提取正确)
verify(flowableClient).procDefSource(CN_PROCDEF);
}
@Test
void 胶水_byId_引擎不可达经handler出503通用信封() throws Exception {
when(flowableClient.procDefSource(CN_PROCDEF))
.thenThrow(new FlowServiceUnavailableException("flowable-service 不可达", null));
glueMvc().perform(get("/api/workflow/process-definitions/{procDefId}/source", CN_PROCDEF))
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.status").value(503))
.andExpect(jsonPath("$.error").value("FLOW_SERVICE_UNAVAILABLE"));
}
@Test
void 胶水_byKey_MVC解码percent中文pathVar并200透传() throws Exception {
Map<String, Object> downstream = Map.of("found", true, "procDefKey", "总包合同交底", "version", 2);
when(flowableClient.procDefSourceByKey(CN_KEY)).thenReturn(downstream);
glueMvc().perform(get("/api/workflow/process-definitions/by-key/{key}/source", CN_KEY))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true));
verify(flowableClient).procDefSourceByKey(CN_KEY);
}
@Test
void 胶水_byKey_引擎不可达经handler出503通用信封() throws Exception {
when(flowableClient.procDefSourceByKey(CN_KEY))
.thenThrow(new FlowServiceUnavailableException("flowable-service 不可达", null));
glueMvc().perform(get("/api/workflow/process-definitions/by-key/{key}/source", CN_KEY))
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.error").value("FLOW_SERVICE_UNAVAILABLE"));
}
}