Compare commits

..

6 Commits

Author SHA1 Message Date
93f3823a06 Merge feat/process-modeler 阶段3: 发布门(deploy+校验+审计+同人确认)
Some checks failed
ci / build-test-parity (push) Has been cancelled
- deploy-from-model(incoming/outgoing剥除+id还原中文key+ProcessValidator校验门+
  disableSchemaValidation+metaInfo不可读fail-fast防坏key)+impact影响摘要
- 网关语义校验门 ModelSemanticValidator(办理人JSON items非空+type白名单对齐WfTypes16种防误拒/
  formKey存在性/完成条件三预设∪自定义不阻断)+FlowDeployAuditService+Flyway V4 sys_flow_deploy_audit
- 下游ProcessValidator结构化errors透传前端(不再吞成通用FLOW_REMOTE_ERROR)
- live 验收:改总包合同交底→存草稿→发布 v9,中文key保住+审计行(op=ADMIN)+起实例生成真userTask+
  旧6实例不受影响+非admin 403;全reactor mvn clean install绿+ArchUnit 6/6
- live 揪修CRITICAL:activiti.json缺tagAlias致Modeler输出PascalCase元素名(Flowable大小写敏感断部署)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:30:32 +08:00
4af6776164 docs(plan): 回写阶段3 live CRITICAL——activiti.json致bpmn-js Modeler输出PascalCase元素名(部署断)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:02:37 +08:00
732655e776 fix(gateway): 语义门收口——type白名单对齐WfTypes(防误拒存量)+透传下游结构化errors+TOCTOU文档
评审 T3.2 收口(2 Important + 2 Minor):
- I-1(功能回归):ModelSemanticValidator.TYPE_WHITELIST 10 种→16 种,对齐 flowable-service WfTypes
  配置类型 + OrgDirectoryJdbc 运行期分派(权威源,非 BasePropertiesConverter,注释已改)。
  psql 窄查询实证:缺失 6 种里 initiatorDepartManager(24 文档)/fixedDimension(12 文档)在真实
  candidateUsers 有非零命中,旧白名单会 422 误拒这些存量流程(载入→编辑无关节点→发布)。
  网关不依赖 flowable-service 故复刻常量并注同步提醒。
- I-2(UX):FlowRemoteException 加 responseBody;FlowableClient.execute 携带下游原始体;
  FlowGatewayExceptionHandler.onRemote 解析并把下游 errors 数组并入网关响应顶层——发布下游 422
  的引擎结构校验 errors[{activityId,problem,defaultDescription}] 现能到前端,与网关语义 422 顶层
  errors 契约统一(前端 T3.3 同一渲染)。非发布路径纯文本体照旧不加 errors 键(无回归)。
- I-3(TOCTOU):deploy 端点加「已接受风险」javadoc(超管低频+窄窗+非安全洞,v1 不做 content-hash 409)。
- 补测 M-1(flowable: 前缀 candidateUsers 按本地名匹配同校验)+ M-2(新增 4 种 type 放行,锁 I-1)+
  I-2 客户端携带体/handler 并入顶层 errors 两用例。

测试:语义 19(+2)、审计 3、客户端 24(+1)、控制器 30(+1)。全 reactor mvn clean install 退出码 0,
零 <<< FAILURE,ArchitectureRulesTest 6/6。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 14:52:03 +08:00
5eed5f0b26 feat(gateway): 发布语义校验门(ModelSemanticValidator)+部署审计(V4/FlowDeployAuditService)
网关发布门收口(T3.2):
- ModelSemanticValidator(@Service):钉 JDK 解析器解析 bpmn XML,校验办理人/会签内嵌
  JSON(全角【】→半角)items 非空+type 白名单、formKey 存在于 view_wftemplate(读库降级放行)、
  会签 completionCondition 预设∪自定义非空(自定义不阻断,保留 T2.4 自定义态);返 List<String> 错误清单。
- Flyway V4 建 sys_flow_deploy_audit(平台表);FlowDeployAuditService(@Service)收口 INSERT,
  写失败不反噬已成功的部署。SQL 全收口 @Service,@RestController 不直用 JdbcTemplate(ArchUnit 棘轮)。
- ProcessModelerController 加 POST /models/{id}/deploy(超管门→语义校验 fail 则 422 零转发→
  转发 deploy→审计 INSERT operator=userId)+ GET /models/{id}/impact(超管门转发)。
- FlowableClient 加 deployModel(id)/modelImpact(id)(uri 变量转发)。

测试:语义校验 17(各错误类型+通过+items 空 error+自定义完成条件不阻断+读库降级+XXE)、
审计 3、客户端转发 +3、控制器 deploy/impact +7。全 reactor mvn clean install 绿,
ArchitectureRulesTest 6/6(@RestController 未新增直用 JdbcTemplate)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 14:12:21 +08:00
529f73f8f5 fix(flow): 发布门坏key地雷收口——metaInfo不可读fail-fast(防部署净化key)+危险分支补测
评审 I1(高后果):readIdMap 把三种情况塌成「空 idMap→跳过还原」——(a)真新建 (b)JSON 解析失败
(c)解析成功但缺 eip4IdMap 键。对 from-procdef 存量草稿(editorSource 的 <process id> 是净化 nXXX),
(b)/(c) 会跳过还原 → 静默部署 key=nXXX 而非中文原 key(HTTP 200,违 D7,且与 restore 非双射 fail-fast 自相矛盾)。

修:readIdMap→resolveIdMap,据 from-procdef 写的 sourceProcDefId/originalKey 标记分流——
metaInfo 非空且(解析失败 或 带标记但缺/非-Map eip4IdMap)→ IllegalStateException fail-fast,
deploy catch→422「草稿 id 映射不可用,无法还原原 key」,不部署。eip4IdMap 存在(含空 {})即可用
(空=全 ASCII 存量流程无需还原);真·新建(metaInfo {}/null、无标记)仍空 map 正常放行。impact 只读
最终回退 model.key(from-procdef 的 model.key 即中文原 key),不 500。

补测(评审 I2):非双射 idMap→IllegalArgumentException→422;存量草稿缺 eip4IdMap→422;metaInfo 坏 JSON→422;
存量空 eip4IdMap 全 ASCII 不误拒正常部署;deploy 路径字节级 DOCTYPE 守卫→422。Minor:M1 注释钉边界
(EIP4 语义校验在网关 ModelSemanticValidator/T3.2,此处仅引擎结构校验);M3 impact 注释说明为何不需独立 DOCTYPE 守卫。

ProcessModelControllerTest 30/30(19 既有零改动 + 11 T3.1:6 首轮 + 5 本轮);全 reactor clean install 绿
(ArchitectureRulesTest 6/6)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 13:48:36 +08:00
6f180522f3 feat(flow): 草稿发布(incoming/outgoing剥除+id还原中文key+ProcessValidator校验门+disableSchemaValidation)+影响摘要
POST /models/{id}/deploy:剥除 bpmn-js 补的 incoming/outgoing 文本引用元素
(Flowable 从 sequenceFlow 自行推导,不剥则 restore 只还原属性位→落库脏 XML,T1.3 I-2)
→ BpmnIdSanitizer.restore 依 eip4IdMap 还原中文原 key(存量 D7 硬需求,新建流程无 idMap 跳过)
→ ProcessValidator 语义校验门(仅 ERROR 级阻断,返 422 {errors:[{activityId,problem,defaultDescription}]}
不部署;WARNING 放行)→ createDeployment().disableSchemaValidation()(只跳 XSD:bpmn-js 默认命名空间
与严格 XSD 已知不兼容,语义已在上一步)部署 → {status,deploymentId,processKey,newVersion}。

GET /models/{id}/impact:还原后解析 processKey → {processKey,currentVersion(最新已部署版本),
runningInstances(运行中实例数)},供同人确认弹窗展示。

控制器加 @Autowired(RepositoryService,RuntimeService) 构造(保留单参构造零改动既有 CRUD 单测)+
全参构造注入 mock ProcessValidator。发布/影响端点 8 单测(还原中文key+剥除无残留净化id+disableSchemaValidation
验证/ERROR 422 不部署/WARNING 放行/404/impact 计数),既有 17 单测零改动;全 reactor clean install 绿
(ArchitectureRulesTest 6/6)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 13:32:31 +08:00
14 changed files with 1630 additions and 14 deletions

View File

@@ -317,6 +317,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`。

View File

@@ -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,语义不符)。

View File

@@ -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("\"");

View File

@@ -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);

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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 语义

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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 &quot;}(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 双引号 → &quot;)。 */
private static String attr(String s) {
return s.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;");
}
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();
}
}

View File

@@ -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("节点未连出边"));
}
}