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>
This commit is contained in:
@@ -0,0 +1,18 @@
|
|||||||
|
-- Flyway 迁移 V4:在线流程 Modeler 发布审计表(sys_flow_deploy_audit)。
|
||||||
|
-- 记录每次草稿→流程定义部署:谁(operator)/何时(deployed_at)/发布了哪个草稿(model_id)/产生的部署(deployment_id)/
|
||||||
|
-- 流程 key(可能中文,如「总包合同交底」)+新版本号。供合规审计与发布追溯(D2 同人确认部署的审计要求)。
|
||||||
|
-- 平台表(非引擎表 act_re_*),走 Flyway;写入收口网关 FlowDeployAuditService。
|
||||||
|
-- 幂等:配合 baseline-on-migrate,既有库已有此表也安全。
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_flow_deploy_audit (
|
||||||
|
id bigserial NOT NULL,
|
||||||
|
model_id varchar(64),
|
||||||
|
deployment_id varchar(64),
|
||||||
|
process_key varchar(255),
|
||||||
|
new_version integer,
|
||||||
|
operator varchar(64),
|
||||||
|
deployed_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT pk_sys_flow_deploy_audit PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 按流程 key + 时间倒查发布历史(某流程被谁何时发布过哪些版本)。
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sys_flow_deploy_audit_key ON sys_flow_deploy_audit (process_key, deployed_at);
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.eip4.platform.flowgateway.aggregate;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 流程发布审计:每次草稿→流程定义部署成功后,记一行 {@code sys_flow_deploy_audit}
|
||||||
|
* (谁 operator / 何时 deployed_at / 发布了哪个草稿 model_id / 产生的 deployment_id / 流程 key + 新版本号),
|
||||||
|
* 供合规审计与发布追溯(D2 同人确认部署的审计要求)。表由 Flyway V4 建(平台表,非引擎表)。
|
||||||
|
*
|
||||||
|
* <p><b>为何是 @Service 而非控制器直查</b>:{@code @RestController} 直持 {@link JdbcTemplate} 触架构棘轮
|
||||||
|
* ({@code 控制器不得新增直用JdbcTemplate}),审计 INSERT 与字段抽取收口到本 Service。</p>
|
||||||
|
*
|
||||||
|
* <p><b>旁路写、不反噬部署</b>:本记录发生在下游部署<b>已成功</b>之后。写审计失败(如库抖动)绝不能让整个
|
||||||
|
* 发布请求变 500——那会误导用户以为发布失败而重试,产生重复部署。故 {@link #record} 就地吞异常记 error,
|
||||||
|
* 不上抛。审计缺失可事后追查,重复部署不可逆。</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class FlowDeployAuditService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(FlowDeployAuditService.class);
|
||||||
|
|
||||||
|
static final String INSERT_SQL =
|
||||||
|
"INSERT INTO sys_flow_deploy_audit (model_id, deployment_id, process_key, new_version, operator) "
|
||||||
|
+ "VALUES (?, ?, ?, ?, ?)";
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public FlowDeployAuditService(JdbcTemplate jdbcTemplate) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从下游 deploy 结果 Map 抽 {@code deploymentId/processKey/newVersion} 落审计行。
|
||||||
|
*
|
||||||
|
* @param modelId 被发布的草稿 id
|
||||||
|
* @param deployResult flowable-service deploy 返回体({status,deploymentId,processKey,newVersion})
|
||||||
|
* @param operator 操作者(= principal.userId(),超管门已保证非空)
|
||||||
|
*/
|
||||||
|
public void record(String modelId, Map<String, Object> deployResult, String operator) {
|
||||||
|
String deploymentId = str(deployResult, "deploymentId");
|
||||||
|
String processKey = str(deployResult, "processKey");
|
||||||
|
Integer newVersion = intOf(deployResult, "newVersion");
|
||||||
|
try {
|
||||||
|
jdbcTemplate.update(INSERT_SQL, modelId, deploymentId, processKey, newVersion, operator);
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
// 部署已成功,审计是旁路记录:写失败不回滚不上抛(否则用户误判发布失败→重试→重复部署)。
|
||||||
|
log.error("[发布审计] 写入 sys_flow_deploy_audit 失败(部署已成功,不回滚) modelId={} operator={}: {}",
|
||||||
|
modelId, operator, e.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String str(Map<String, Object> m, String key) {
|
||||||
|
Object v = m == null ? null : m.get(key);
|
||||||
|
return v == null ? null : String.valueOf(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Integer intOf(Map<String, Object> m, String key) {
|
||||||
|
Object v = m == null ? null : m.get(key);
|
||||||
|
return v instanceof Number n ? n.intValue() : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
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(§0 实测 10 种,逐字对齐 BasePropertiesConverter)。 */
|
||||||
|
static final Set<String> TYPE_WHITELIST = Set.of(
|
||||||
|
"user", "depart", "position", "formSpecifiedDimension", "initiator",
|
||||||
|
"sameToTask", "beforeTaskLeader", "beforeTaskDepartManager", "scriptUser", "projectRoleType");
|
||||||
|
|
||||||
|
/** 会签完成条件三预设(与 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -329,6 +329,34 @@ public class FlowableClient {
|
|||||||
return delete("删草稿", "/api/flow/models/{id}", Map.class, id);
|
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}。 */
|
/** 按发起人查询历史流程实例。对应 flowable-service {@code GET /api/flow/process/started}。 */
|
||||||
public List<ProcessInstanceDto> started(String startedBy, int firstResult, int maxResults) {
|
public List<ProcessInstanceDto> started(String startedBy, int firstResult, int maxResults) {
|
||||||
return execute("发起流程列表", () -> restClient.get()
|
return execute("发起流程列表", () -> restClient.get()
|
||||||
@@ -402,6 +430,20 @@ public class FlowableClient {
|
|||||||
.body(respType));
|
.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
|
* PUT 转发(RestClient 无既有封装 → 照 {@link #post} 补)。{@code uriTemplate}+{@code uriVars} 走 RestClient
|
||||||
* 严格编码({@code id} 作 uri 变量,禁字符串拼接);连接级重试 + 4xx/5xx 透传语义与 post 一致。
|
* 严格编码({@code id} 作 uri 变量,禁字符串拼接);连接级重试 + 4xx/5xx 透传语义与 post 一致。
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.eip4.platform.flowgateway.web;
|
package com.eip4.platform.flowgateway.web;
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
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.AuthPrincipal;
|
||||||
import com.eip4.platform.auth.security.EngineContextBinder;
|
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.aggregate.WfTemplatePickerService;
|
||||||
import com.eip4.platform.flowgateway.client.FlowableClient;
|
import com.eip4.platform.flowgateway.client.FlowableClient;
|
||||||
|
|
||||||
@@ -41,11 +44,17 @@ public class ProcessModelerController {
|
|||||||
|
|
||||||
private final FlowableClient flowableClient;
|
private final FlowableClient flowableClient;
|
||||||
private final WfTemplatePickerService wfTemplatePickerService;
|
private final WfTemplatePickerService wfTemplatePickerService;
|
||||||
|
private final ModelSemanticValidator semanticValidator;
|
||||||
|
private final FlowDeployAuditService deployAuditService;
|
||||||
|
|
||||||
public ProcessModelerController(FlowableClient flowableClient,
|
public ProcessModelerController(FlowableClient flowableClient,
|
||||||
WfTemplatePickerService wfTemplatePickerService) {
|
WfTemplatePickerService wfTemplatePickerService,
|
||||||
|
ModelSemanticValidator semanticValidator,
|
||||||
|
FlowDeployAuditService deployAuditService) {
|
||||||
this.flowableClient = flowableClient;
|
this.flowableClient = flowableClient;
|
||||||
this.wfTemplatePickerService = wfTemplatePickerService;
|
this.wfTemplatePickerService = wfTemplatePickerService;
|
||||||
|
this.semanticValidator = semanticValidator;
|
||||||
|
this.deployAuditService = deployAuditService;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- 存量流程源载入(T1.6)
|
// ---------------------------------------------------------------- 存量流程源载入(T1.6)
|
||||||
@@ -158,6 +167,58 @@ public class ProcessModelerController {
|
|||||||
return ResponseEntity.ok(flowableClient.deleteModel(id));
|
return ResponseEntity.ok(flowableClient.deleteModel(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 发布门(T3.2)
|
||||||
|
|
||||||
|
@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)
|
// ---------------------------------------------------------------- formKey 选择器数据源(T2.2)
|
||||||
|
|
||||||
@Operation(summary = "wftemplate 选择器数据源(超管)",
|
@Operation(summary = "wftemplate 选择器数据源(超管)",
|
||||||
@@ -184,9 +245,14 @@ public class ProcessModelerController {
|
|||||||
if (EngineContextBinder.isSystemAdmin(principal)) {
|
if (EngineContextBinder.isSystemAdmin(principal)) {
|
||||||
return null;
|
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<>();
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
body.put("status", 1);
|
body.put("status", 1);
|
||||||
body.put("msg", "仅系统管理员可用");
|
body.put("msg", msg);
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
|
return ResponseEntity.status(httpStatus).body(body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.eip4.platform.flowgateway;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.dao.DataAccessResourceFailureException;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
import com.eip4.platform.flowgateway.aggregate.FlowDeployAuditService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 部署审计 Service 单测:从 deploy 下游结果抽字段 INSERT sys_flow_deploy_audit;写库异常吞掉不反噬已成功的部署。
|
||||||
|
* SQL 收口到本 @Service(@RestController 不得直用 JdbcTemplate,架构棘轮)。
|
||||||
|
*/
|
||||||
|
class FlowDeployAuditServiceTest {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
|
||||||
|
private final FlowDeployAuditService service = new FlowDeployAuditService(jdbcTemplate);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void record_从下游结果抽全字段INSERT() {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("status", 0);
|
||||||
|
result.put("deploymentId", "dep-9");
|
||||||
|
result.put("processKey", "总包合同交底");
|
||||||
|
result.put("newVersion", 4);
|
||||||
|
|
||||||
|
service.record("m1", result, "ADMIN");
|
||||||
|
|
||||||
|
// SQL 用 anyString()(照 WfTemplatePickerServiceTest 惯例,不耦合具体语句);断言抽出的字段值与顺序。
|
||||||
|
verify(jdbcTemplate).update(anyString(),
|
||||||
|
eq("m1"), eq("dep-9"), eq("总包合同交底"), eq(4), eq("ADMIN"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void record_newVersion数字归一为Integer_processKey缺失传null() {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("deploymentId", "dep-1");
|
||||||
|
// 无 processKey/newVersion:抽为 null,不炸
|
||||||
|
service.record("m2", result, "ADMIN");
|
||||||
|
|
||||||
|
verify(jdbcTemplate).update(anyString(),
|
||||||
|
eq("m2"), eq("dep-1"), eq((Object) null), eq((Object) null), eq("ADMIN"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void record_写库异常被吞不抛_部署已成功不回滚() {
|
||||||
|
when(jdbcTemplate.update(anyString(), any(), any(), any(), any(), any()))
|
||||||
|
.thenThrow(new DataAccessResourceFailureException("db down"));
|
||||||
|
Map<String, Object> result = Map.of("deploymentId", "d", "processKey", "k", "newVersion", 1);
|
||||||
|
|
||||||
|
assertThatCode(() -> service.record("m3", result, "ADMIN")).doesNotThrowAnyException();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -430,4 +430,61 @@ class FlowableClientTest {
|
|||||||
.satisfies(e -> assertThat(((FlowRemoteException) e).getStatus().value()).isEqualTo(404));
|
.satisfies(e -> assertThat(((FlowRemoteException) e).getStatus().value()).isEqualTo(404));
|
||||||
server.verify();
|
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 发布影响_GET_models_id_impact_透传下游结果() {
|
||||||
|
FlowGatewayProperties p = props();
|
||||||
|
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
|
||||||
|
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
|
||||||
|
server.expect(ExpectedCount.once(), requestTo("http://localhost:8089/api/flow/models/m1/impact"))
|
||||||
|
.andExpect(method(HttpMethod.GET))
|
||||||
|
.andRespond(withSuccess(
|
||||||
|
"{\"processKey\":\"总包合同交底\",\"currentVersion\":3,\"runningInstances\":7}",
|
||||||
|
MediaType.APPLICATION_JSON));
|
||||||
|
FlowableClient client = new FlowableClient(builder.build(), p);
|
||||||
|
|
||||||
|
Map<String, Object> resp = client.modelImpact("m1");
|
||||||
|
|
||||||
|
assertThat(resp).containsEntry("processKey", "总包合同交底").containsEntry("currentVersion", 3)
|
||||||
|
.containsEntry("runningInstances", 7);
|
||||||
|
server.verify();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package com.eip4.platform.flowgateway;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.dao.DataAccessResourceFailureException;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
import com.eip4.platform.flowgateway.aggregate.ModelSemanticValidator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发布语义校验器单测:办理人/会签内嵌 JSON(全角【】)items 非空 + type 白名单、formKey 存在于
|
||||||
|
* view_wftemplate、completionCondition 预设∪自定义(自定义不阻断)。返回 {@code List<String>} 空=通过。
|
||||||
|
*
|
||||||
|
* <p>fixture 逐字复刻 §0 真实形态:candidateUsers/collection 值是引擎 handler 表达式,内容段花括号全角【】、
|
||||||
|
* XML 属性内引号 {@code "}(DOM 解码回真引号后 validator 再 replace 全角→半角 JSON.parse)。
|
||||||
|
*/
|
||||||
|
class ModelSemanticValidatorTest {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
|
||||||
|
private final ModelSemanticValidator validator = new ModelSemanticValidator(jdbcTemplate);
|
||||||
|
|
||||||
|
private static final String CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
|
||||||
|
private static final String MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'";
|
||||||
|
private static final String SUFFIX = "')}";
|
||||||
|
|
||||||
|
/** formKey 存在性查询恒返回给定 count(一次 stub 覆盖所有 formKey)。 */
|
||||||
|
private void formKeyCount(int count) {
|
||||||
|
when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any())).thenReturn(count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 办理人/会签内容段:半角 JSON → 花括号全角【】(方括号保持半角,逐字对齐存储态)。 */
|
||||||
|
private static String toStored(String halfWidthJson) {
|
||||||
|
return halfWidthJson.replace("{", "【").replace("}", "】");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String candidateExpr(String itemsJson) {
|
||||||
|
return CANDIDATE_PREFIX + toStored("{\"items\":" + itemsJson + "}") + SUFFIX;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String multiExpr(String itemsJson) {
|
||||||
|
return MULTI_PREFIX + toStored("{\"items\":" + itemsJson + "}") + SUFFIX;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** XML 属性值转义(内嵌 JSON 双引号 → ")。 */
|
||||||
|
private static String attr(String s) {
|
||||||
|
return s.replace("&", "&").replace("\"", """).replace("<", "<");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String bpmn(String processInner) {
|
||||||
|
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||||
|
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" "
|
||||||
|
+ "xmlns:activiti=\"http://activiti.org/bpmn\" targetNamespace=\"n\">"
|
||||||
|
+ "<process id=\"p1\" name=\"流程\">" + processInner + "</process></definitions>";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String userTaskWithCandidate(String name, String candidateExpr) {
|
||||||
|
return "<userTask id=\"t1\" name=\"" + name + "\" activiti:candidateUsers=\""
|
||||||
|
+ attr(candidateExpr) + "\"/>";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String cosignUserTask(String name, String collectionExpr, String completion) {
|
||||||
|
String cc = completion == null ? ""
|
||||||
|
: "<completionCondition>" + attr(completion) + "</completionCondition>";
|
||||||
|
return "<userTask id=\"t2\" name=\"" + name + "\">"
|
||||||
|
+ "<multiInstanceLoopCharacteristics isSequential=\"false\" activiti:collection=\""
|
||||||
|
+ attr(collectionExpr) + "\" activiti:elementVariable=\"assignee\">" + cc
|
||||||
|
+ "</multiInstanceLoopCharacteristics></userTask>";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 通过
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 合法流程_办理人items非空白名单_formKey存在_预设完成条件_零错误() {
|
||||||
|
formKeyCount(1);
|
||||||
|
String xml = bpmn(
|
||||||
|
"<userTask id=\"t1\" name=\"审批\" activiti:formKey=\"wft-1\" activiti:candidateUsers=\""
|
||||||
|
+ attr(candidateExpr("[{\"type\":\"user\",\"content\":\"u1,u2\",\"isCandidate\":true}]"))
|
||||||
|
+ "\"/>"
|
||||||
|
+ cosignUserTask("会签", multiExpr("[{\"type\":\"depart\",\"content\":\"d1\"}]"),
|
||||||
|
"${nrOfCompletedInstances/nrOfInstances==1}"));
|
||||||
|
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 裸userTask无办理人无formKey_不属本校验器职责_零错误() {
|
||||||
|
String xml = bpmn("<userTask id=\"t1\" name=\"纯节点\"/>");
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
// 无 formKey → 不查库
|
||||||
|
verify(jdbcTemplate, never()).queryForObject(anyString(), eq(Integer.class), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 非handler裸候选值_非EIP4codec产物_放行不校验JSON() {
|
||||||
|
// 直接写 ${someVar} 等裸表达式:非 EIP4 办理人 handler 形态,不套 JSON 白名单(避免误拒合法 Flowable 裸值)
|
||||||
|
String xml = bpmn("<userTask id=\"t1\" name=\"节点\" activiti:candidateUsers=\"${someVar}\"/>");
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 办理人 JSON 错误
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 办理人items为空数组_error() {
|
||||||
|
String xml = bpmn(userTaskWithCandidate("空办理人", candidateExpr("[]")));
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(1);
|
||||||
|
assertThat(errors.get(0)).contains("空办理人").contains("为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 办理人type非白名单_error() {
|
||||||
|
String xml = bpmn(userTaskWithCandidate("坏type",
|
||||||
|
candidateExpr("[{\"type\":\"bogusType\",\"content\":\"x\"}]")));
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(1);
|
||||||
|
assertThat(errors.get(0)).contains("坏type").contains("bogusType");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 办理人JSON无法解析_error() {
|
||||||
|
// 内容段坏 JSON(缺闭合)——全角还原后仍非法
|
||||||
|
String bad = CANDIDATE_PREFIX + toStored("{\"items\":[{\"type\":") + SUFFIX;
|
||||||
|
String xml = bpmn("<userTask id=\"t1\" name=\"坏JSON\" activiti:candidateUsers=\""
|
||||||
|
+ attr(bad) + "\"/>");
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(1);
|
||||||
|
assertThat(errors.get(0)).contains("坏JSON").contains("JSON");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 办理人多个type_逐项报非法() {
|
||||||
|
String xml = bpmn(userTaskWithCandidate("多项",
|
||||||
|
candidateExpr("[{\"type\":\"user\",\"content\":\"a\"},"
|
||||||
|
+ "{\"type\":\"bad1\",\"content\":\"b\"},{\"type\":\"bad2\",\"content\":\"c\"}]")));
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(2);
|
||||||
|
assertThat(errors).anyMatch(e -> e.contains("bad1")).anyMatch(e -> e.contains("bad2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 会签 collection + 完成条件
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 会签collection的items为空_error() {
|
||||||
|
formKeyCount(1);
|
||||||
|
String xml = bpmn(cosignUserTask("空会签", multiExpr("[]"),
|
||||||
|
"${nrOfCompletedInstances/nrOfInstances==1}"));
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(1);
|
||||||
|
assertThat(errors.get(0)).contains("空会签").contains("为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 会签自定义完成条件_不阻断_零错误() {
|
||||||
|
// T2.4 保留自定义完成条件态:非三预设的合法表达式必须放行(别把存量自定义条件拒了)
|
||||||
|
String xml = bpmn(cosignUserTask("过六成会签",
|
||||||
|
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"),
|
||||||
|
"${nrOfCompletedInstances/nrOfInstances>0.6}"));
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 会签过半预设_不阻断_零错误() {
|
||||||
|
String xml = bpmn(cosignUserTask("过半会签",
|
||||||
|
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"),
|
||||||
|
"${nrOfCompletedInstances/nrOfInstances>0.5}"));
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 会签指定数预设_不阻断_零错误() {
|
||||||
|
String xml = bpmn(cosignUserTask("三票会签",
|
||||||
|
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"),
|
||||||
|
"${nrOfCompletedInstances>=3}"));
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 会签完成条件空白_error() {
|
||||||
|
String xml = bpmn(cosignUserTask("空条件会签",
|
||||||
|
multiExpr("[{\"type\":\"user\",\"content\":\"u1\"}]"), " "));
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(1);
|
||||||
|
assertThat(errors.get(0)).contains("空条件会签").contains("完成条件");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- formKey 存在性
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formKey不存在于模板库_error() {
|
||||||
|
formKeyCount(0);
|
||||||
|
String xml = bpmn("<userTask id=\"t1\" name=\"带表单\" activiti:formKey=\"ghost-uuid\"/>");
|
||||||
|
List<String> errors = validator.validate(xml);
|
||||||
|
assertThat(errors).hasSize(1);
|
||||||
|
assertThat(errors.get(0)).contains("带表单").contains("ghost-uuid").contains("view_wftemplate");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formKey读库异常_降级放行不阻断部署() {
|
||||||
|
when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any()))
|
||||||
|
.thenThrow(new DataAccessResourceFailureException("db down"));
|
||||||
|
String xml = bpmn("<userTask id=\"t1\" name=\"带表单\" activiti:formKey=\"wft-1\"/>");
|
||||||
|
// 读库抖动不因基础设施问题阻断发布(全站降级惯例),该项引用完整性检查跳过
|
||||||
|
assertThat(validator.validate(xml)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- XML 层防御
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 坏XML_error不抛() {
|
||||||
|
List<String> errors = validator.validate("<definitions><process</bad>");
|
||||||
|
assertThat(errors).isNotEmpty();
|
||||||
|
assertThat(errors.get(0)).contains("解析");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 含DOCTYPE_XXE防御_error() {
|
||||||
|
String evil = "<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY x \"y\">]>"
|
||||||
|
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"><process id=\"p\"/></definitions>";
|
||||||
|
List<String> errors = validator.validate(evil);
|
||||||
|
assertThat(errors).isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 空XML_error() {
|
||||||
|
assertThat(validator.validate(" ")).isNotEmpty();
|
||||||
|
assertThat(validator.validate(null)).isNotEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,8 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
|||||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||||
|
|
||||||
import com.eip4.platform.auth.security.AuthPrincipal;
|
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.aggregate.WfTemplatePickerService;
|
||||||
import com.eip4.platform.flowgateway.client.FlowRemoteException;
|
import com.eip4.platform.flowgateway.client.FlowRemoteException;
|
||||||
import com.eip4.platform.flowgateway.client.FlowServiceUnavailableException;
|
import com.eip4.platform.flowgateway.client.FlowServiceUnavailableException;
|
||||||
@@ -47,8 +49,10 @@ class ProcessModelerControllerTest {
|
|||||||
|
|
||||||
private final FlowableClient flowableClient = mock(FlowableClient.class);
|
private final FlowableClient flowableClient = mock(FlowableClient.class);
|
||||||
private final WfTemplatePickerService wfTemplatePickerService = mock(WfTemplatePickerService.class);
|
private final WfTemplatePickerService wfTemplatePickerService = mock(WfTemplatePickerService.class);
|
||||||
private final ProcessModelerController controller =
|
private final ModelSemanticValidator semanticValidator = mock(ModelSemanticValidator.class);
|
||||||
new ProcessModelerController(flowableClient, wfTemplatePickerService);
|
private final FlowDeployAuditService deployAuditService = mock(FlowDeployAuditService.class);
|
||||||
|
private final ProcessModelerController controller = new ProcessModelerController(
|
||||||
|
flowableClient, wfTemplatePickerService, semanticValidator, deployAuditService);
|
||||||
|
|
||||||
/** 真实形态:中文 key + 冒号分隔的 procDefId。 */
|
/** 真实形态:中文 key + 冒号分隔的 procDefId。 */
|
||||||
private static final String CN_PROCDEF = "总包合同交底:3:abc123";
|
private static final String CN_PROCDEF = "总包合同交底:3:abc123";
|
||||||
@@ -368,4 +372,104 @@ class ProcessModelerControllerTest {
|
|||||||
// 路由匹配 PUT 谓词 + {id} 绑定到 "m1" 交给控制器
|
// 路由匹配 PUT 谓词 + {id} 绑定到 "m1" 交给控制器
|
||||||
verify(flowableClient).updateModel(eq("m1"), any());
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user