服务流分派: 写流安全闸(读写分类+写流仅POST真实用户+入参类型强制)

写/动作路径改走服务流的后端前置。FlowReadWriteClassifier 按 contentxml
service 节点真实方法判读/写(fail-closed,非后缀/iscontrol);FlowController
写流仅 POST + 真实 JWT 用户上下文执行(拟稿人/写侧权限按真实用户)、GET 写流
403(防 URL 触发写)、引擎 @Transactional 回滚;FlowInputCoercer 按实体列类型
强制写流入参(JSON String→Integer/Long/Boolean/Date)。实测 POST _ADD 落库、
GET _ADD/_SUBMIT→403、读流 GET 200。50+ 单测。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-12 13:53:52 +08:00
parent 895ed54a95
commit 47978e13be
8 changed files with 1174 additions and 84 deletions

View File

@@ -0,0 +1,279 @@
package com.eip4.platform.metadata.flow;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* 写流入参类型强制器(写路径走服务流安全前置之类型兼容修复)。
*
* <p><b>问题根因</b>:{@code POST /api/flow/{servicename}} body 来自 amis JSON,
* 所有值都是 {@code String}。引擎 {@code pojoCRUDService.save(map, tableName, ctx)}
* 调用 {@code new GeneralPO(tableName, map, ctx)} 构造器,内部按 {@code POJOInfo.getColumnClass(i)}
* 直接 {@code (Integer) map.get(columnName)} cast,遇到 {@code String "1"} → {@code ClassCastException}。
*
* <p><b>解法(元数据驱动,按 SYS_ENTITYATTRIBUTE.referenceid 判目标类型)</b>:
* <ol>
* <li>从流的 {@code contentxml} 用正则抽取 {@code <field name="tableName" ... initValue="X">} 得实体表名。</li>
* <li>按表名查 {@code SYS_ENTITYATTRIBUTE},得列名 → referenceid(即 DisplayType 字符串)映射。</li>
* <li>遍历入参 map,对值为 {@code String} 的键,若目标类型是 {@code INTEGER/ENUMERATE/STATUS → Integer}、
* {@code BOOLEAN → Boolean}、{@code DECIMAL/MONEY → BigDecimal},就地 parse;其余(NVARCHAR/CHAR/TIME/DATE/LIST/BLOB)不动。</li>
* </ol>
*
* <p><b>fail-safe(不阻断写路径)</b>:表名提取失败、元数据查不到、parse 失败 → 原值保留,
* 交由引擎校验如实报错;不会因 coerce 本身抛 RuntimeException 阻断写。
*
* <p><b>幂等</b>:值若已经是正确类型(前端传了 Integer)则不重复转换。
*
* <p><b>缓存</b>:表名 → 列类型 map,Caffeine maxSize 2000,与 {@code /api/meta/evict} 对齐。
*
* <p>纪律:零改 {@code com.dsasp};只读 SYS_ENTITYATTRIBUTE 元数据,不写业务表。
*/
@Component
public class FlowInputCoercer {
private static final Logger log = LoggerFactory.getLogger(FlowInputCoercer.class);
/**
* 从 contentxml 抽取 tableName initValue:
* {@code <field name="tableName" ... initValue="X"> } 或自闭合 {@code .../>}。
*/
private static final Pattern TABLE_NAME_PATTERN = Pattern.compile(
"<field\\b[^>]*\\bname\\s*=\\s*\"tableName\"[^>]*\\binitValue\\s*=\\s*\"([^\"]+)\"",
Pattern.CASE_INSENSITIVE);
/** 表名(大写)→ {列名(大写)→ referenceid(DisplayType 字符串)} 映射。 */
private final Cache<String, Map<String, String>> columnTypeCache = Caffeine.newBuilder()
.maximumSize(2_000)
.build();
/**
* flowId → tableName(大写)映射缓存。
* 避免 {@link #coerceByFlowId} 每次重查 contentxml 文本。
* 空字符串 {@code ""} 表示该流无固定 tableName(动态多表流),同样缓存避免重查。
*/
private final Cache<String, String> flowTableCache = Caffeine.newBuilder()
.maximumSize(5_000)
.build();
private final JdbcTemplate jdbcTemplate;
public FlowInputCoercer(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 按 flowId 就地 coerce 写流入参 map:自动查 contentxml 提取表名,再按元数据类型强制转换。
*
* <p>这是 {@link #coerce(String, Map)} 的便捷入口,供 {@code FlowController} 写流路径调用。
* flowId→tableName 和 tableName→columnTypes 均有 Caffeine 缓存,热路径 0 DB 往返。
*
* @param flowId sys_serviceflow 主键(即服务流名)
* @param map 写流入参 map,就地修改
*/
public void coerceByFlowId(String flowId, Map<String, Object> map) {
if (flowId == null || flowId.isBlank() || map == null || map.isEmpty()) {
return;
}
// 先从缓存取 tableName;缓存未命中则查 contentxml
String tableName = flowTableCache.get(flowId, this::resolveTableNameByFlowId);
if (tableName.isEmpty()) {
return; // 无固定 tableName,跳过
}
Map<String, String> colTypes = columnTypeCache.get(tableName, this::queryColumnTypes);
if (colTypes.isEmpty()) {
return;
}
applyCoerce(map, colTypes);
}
/**
* 就地 coerce 写流入参 map:按流 contentxml 里的 tableName 查元数据,把 String 值
* 强制转成引擎期望的 Java 类型(Integer/Boolean/BigDecimal),其余类型不动。
*
* <p>fail-safe:任何步骤失败(无 tableName / DB 异常 / parse 失败)→ 原值保留,不抛异常。
*
* @param contentXml 流的 contentxml(调用方已按 PK 查好);null/空 → 跳过
* @param map 写流入参 map,就地修改;null → 跳过
*/
public void coerce(String contentXml, Map<String, Object> map) {
if (contentXml == null || contentXml.isBlank() || map == null || map.isEmpty()) {
return;
}
String tableName = extractTableName(contentXml);
if (tableName == null) {
return; // 无固定 tableName(如跨表流),不做 coerce
}
Map<String, String> colTypes = columnTypeCache.get(tableName, this::queryColumnTypes);
if (colTypes.isEmpty()) {
return;
}
applyCoerce(map, colTypes);
}
/** 遍历 map,按 colTypes 就地强制转换 String 值为目标 Java 类型。 */
private void applyCoerce(Map<String, Object> map, Map<String, String> colTypes) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object val = entry.getValue();
if (!(val instanceof String)) {
continue; // 已是正确类型,幂等跳过
}
String colUpper = entry.getKey().toUpperCase();
String refId = colTypes.get(colUpper);
if (refId == null) {
continue; // 元数据无此列,不动
}
Object coerced = coerceValue((String) val, refId, colUpper);
if (coerced != val) { // 引用变了才更新
entry.setValue(coerced);
}
}
}
/**
* 按 flowId 从 sys_serviceflow 查 contentxml,提取 tableName。
* 找不到 → 返回 {@code ""}(空字符串,会被缓存以避免重查)。
*/
private String resolveTableNameByFlowId(String flowId) {
try {
String xml = jdbcTemplate.queryForObject(
"SELECT contentxml::text FROM eip3.sys_serviceflow WHERE sys_serviceflow_id = ?",
String.class, flowId);
if (xml == null) {
return "";
}
String tableName = extractTableName(xml);
return tableName != null ? tableName : "";
} catch (org.springframework.dao.EmptyResultDataAccessException e) {
return ""; // 流不存在
} catch (RuntimeException e) {
log.warn("[FLOW-COERCE] 查 contentxml 失败 flowId={}: {}", sanitize(flowId), e.getMessage());
return "";
}
}
/**
* 从 contentxml 抽取固定实体表名({@code <field name="tableName" initValue="X">})。
*
* @return 大写表名,或 null(无 tableName initValue 的流,如动态多表流)
*/
String extractTableName(String contentXml) {
if (contentXml == null || contentXml.isBlank()) {
return null; // 流不存在/无 contentxml → 无固定表名
}
Matcher m = TABLE_NAME_PATTERN.matcher(contentXml);
if (m.find()) {
return m.group(1).trim().toUpperCase();
}
return null;
}
/**
* 按 tableName 查 SYS_ENTITYATTRIBUTE,返回 {列名大写 → referenceid} 映射。
* 结果由 Caffeine 缓存;DB 异常 → 返回空 map(fail-safe)。
*/
private Map<String, String> queryColumnTypes(String upperTable) {
try {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT UPPER(a.columnname) AS col, a.referenceid AS ref "
+ "FROM eip3.sys_entityattribute a "
+ "JOIN eip3.sys_entity e ON UPPER(e.sys_entity_id) = UPPER(a.entityid) "
+ "WHERE UPPER(e.tablename) = ? AND a.isactive = 1",
upperTable);
Map<String, String> result = new HashMap<>(rows.size() * 2);
for (Map<String, Object> r : rows) {
String col = (String) r.get("col");
String ref = (String) r.get("ref");
if (col != null && ref != null) {
result.put(col.trim().toUpperCase(), ref.trim().toUpperCase());
}
}
return result;
} catch (RuntimeException e) {
log.warn("[FLOW-COERCE] 查列类型失败 table={}: {}", upperTable, e.getMessage());
return Map.of(); // fail-safe 空 map
}
}
/**
* 单值 coerce:String → 目标 Java 类型。parse 失败 → 原始 String 保留(fail-safe)。
*
* <p>映射规则(与 {@code DisplayType.getClass} + {@code GeneralPO.load} 期望对齐):
* <ul>
* <li>{@code INTEGER / ENUMERATE / STATUS} → {@code Integer}({@code Integer.parseInt})</li>
* <li>{@code BOOLEAN} → {@code Boolean}("1"/"true"/"Y" → true;"0"/"false"/"N" → false)</li>
* <li>{@code DECIMAL / MONEY} → {@code BigDecimal}</li>
* <li>其余({@code NVARCHAR/CHAR/TIME/DATE/LIST/BLOB/CODE/…})→ 原 String 不动</li>
* </ul>
*
* @param val 原始 String 值
* @param refId referenceid(DisplayType 字符串,已大写)
* @param colName 列名(仅用于日志)
* @return coerced 值,或原始 val(parse 失败 / 不需要转换)
*/
Object coerceValue(String val, String refId, String colName) {
switch (refId) {
case "INTEGER", "ENUMERATE", "STATUS" -> {
try {
return Integer.parseInt(val.trim());
} catch (NumberFormatException e) {
log.debug("[FLOW-COERCE] col={} refId={} val='{}' parseInt failed, keeping String",
colName, refId, val);
return val;
}
}
case "BOOLEAN" -> {
String v = val.trim();
if ("1".equals(v) || "true".equalsIgnoreCase(v) || "Y".equalsIgnoreCase(v)) {
return Boolean.TRUE;
} else if ("0".equals(v) || "false".equalsIgnoreCase(v) || "N".equalsIgnoreCase(v)) {
return Boolean.FALSE;
}
log.debug("[FLOW-COERCE] col={} refId=BOOLEAN val='{}' unrecognized, keeping String", colName, val);
return val;
}
case "DECIMAL", "MONEY" -> {
try {
return new BigDecimal(val.trim());
} catch (NumberFormatException e) {
log.debug("[FLOW-COERCE] col={} refId={} val='{}' parseBD failed, keeping String",
colName, refId, val);
return val;
}
}
default -> {
// NVARCHAR/CHAR/TIME/DATE/LIST/BLOB/CODE/UUID-ref 等 → 不动
return val;
}
}
}
/** 失效单表缓存(元数据变更时,与 /api/meta/evict 钩子对齐)。 */
public void evict(String table) {
if (table != null && !table.isBlank()) {
columnTypeCache.invalidate(table.trim().toUpperCase());
}
}
/** 失效全部缓存(含 flowId→tableName 缓存)。 */
public void evictAll() {
columnTypeCache.invalidateAll();
flowTableCache.invalidateAll();
}
private static String sanitize(String id) {
if (id == null) return "";
return id.replaceAll("[^A-Za-z0-9_\\-]", "?");
}
}

View File

@@ -26,12 +26,17 @@ import com.github.benmanes.caffeine.cache.Caffeine;
* 合成结果走 Caffeine 缓存(maxSize 2000);{@link #evict(String)} 与 * 合成结果走 Caffeine 缓存(maxSize 2000);{@link #evict(String)} 与
* {@code /api/meta/evict} 钩子对齐。</li> * {@code /api/meta/evict} 钩子对齐。</li>
* <li><b>其余命名</b>:按 sys_serviceflow_id 列精确查(主键查,O(1),无需 XML 扫描)→ * <li><b>其余命名</b>:按 sys_serviceflow_id 列精确查(主键查,O(1),无需 XML 扫描)→
* 命中返回哨兵 {@link ResolvedFlow#NAMED_HIT}(调用方用原始名按 PK 直接执行); * 命中后按 contentxml 判读/写,返回 {@link ResolvedFlow#NAMED_READ} 或 {@link ResolvedFlow#NAMED_WRITE}
* 不命中返回 {@link ResolvedFlow#ORPHAN}(调用方应返回 404)。</li> * (调用方用原始名按 PK 执行);不命中返回 {@link ResolvedFlow#ORPHAN}(调用方应返回 404)。</li>
* </ol> * </ol>
* *
* <p>写操作后缀拒绝:{@code _SAVE/_UPDATE/_DELETE} 结尾的名字(非 UUID 且无法按 _SEARCH 路径处理) * <p>读/写分类(取代命名后缀闸):命名服务命中 sys_serviceflow 后,由
* 返回 {@link ResolvedFlow#WRITE_REDIRECT},调用方应引导使用 /api/entity/{x}/save 端点。 * {@link FlowReadWriteClassifier} 按 {@code contentxml} 真实方法判定读/写——
* 读流返回 {@link ResolveType#NAMED_READ}(GET/POST 皆可执行);
* 写流返回 {@link ResolveType#NAMED_WRITE}(仅 POST + 真实用户上下文执行,GET 拒绝)。
* 旧的 {@code _SAVE/_UPDATE/_DELETE} 后缀闸已移除:它既漏挡不带后缀的写流
* ({@code _ADD/_SUBMIT/_PUBLISH/_UPDATE_AC}),又把恰好叫 {@code _UPDATE/_DELETE} 的流一刀切 404,
* 读写门不一致。改按 contentxml 方法判定后门一致。
* *
* <p><b>零改 com.dsasp 文件</b>:DefaultFlowHelper 调用在本类(现代层包),保真层不动。 * <p><b>零改 com.dsasp 文件</b>:DefaultFlowHelper 调用在本类(现代层包),保真层不动。
* SQL 全参数化;表名已经过白名单校验(SYS_ENTITY 存在性 = 白名单)。 * SQL 全参数化;表名已经过白名单校验(SYS_ENTITY 存在性 = 白名单)。
@@ -54,40 +59,38 @@ public class FlowNameResolver {
java.util.regex.Pattern.compile( java.util.regex.Pattern.compile(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
/** 写操作默认后缀,这三种走 /api/entity/{x}/save,不走 flow 查询路径 */
private static final java.util.regex.Pattern WRITE_SUFFIX_PATTERN =
java.util.regex.Pattern.compile("(?i)_SAVE$|_UPDATE$|_DELETE$");
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final SynthesizedFlowRegistry registry; private final SynthesizedFlowRegistry registry;
private final FlowReadWriteClassifier classifier;
public FlowNameResolver(JdbcTemplate jdbcTemplate, SynthesizedFlowRegistry registry) { public FlowNameResolver(JdbcTemplate jdbcTemplate, SynthesizedFlowRegistry registry,
FlowReadWriteClassifier classifier) {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
this.registry = registry; this.registry = registry;
this.classifier = classifier;
} }
/** /**
* 解析结果类型。 * 解析结果类型。
*/ */
public enum ResolveType { public enum ResolveType {
/** UUID 格式,调用方走 PK 查引擎(现状逻辑) */ /** UUID 格式,调用方走 PK 查引擎(现状逻辑)。读写未分类,按写门处理(仅 POST)。 */
UUID_PASSTHROUGH, UUID_PASSTHROUGH,
/** _SEARCH 合成:返回合成 FlowDefinition,调用方直接执行 */ /** _SEARCH 合成:返回合成 FlowDefinition,调用方直接执行(读流)。 */
SYNTHESIZED, SYNTHESIZED,
/** 命名服务命中 sys_serviceflow(PK=id),调用方用原始名按 PK 执行 */ /** 命名读流命中 sys_serviceflow 且 contentxml 全只读 → GET/POST 皆可执行。 */
NAMED_HIT, NAMED_READ,
/** 写操作后缀,应 redirect 到 /api/entity/{x}/save */ /** 命名写流命中 sys_serviceflow 且 contentxml 含写方法 → 仅 POST + 真实用户上下文执行,GET 拒绝。 */
WRITE_REDIRECT, NAMED_WRITE,
/** 孤儿:既不是 UUID,也查不到,也合成不了 → 404 */ /** 孤儿:既不是 UUID,也查不到,也合成不了 → 404 */
ORPHAN ORPHAN
} }
public record ResolvedFlow(ResolveType type, FlowDefinition<?> definition, String message) { public record ResolvedFlow(ResolveType type, FlowDefinition<?> definition, String message) {
public static final ResolvedFlow UUID_PASSTHROUGH = new ResolvedFlow(ResolveType.UUID_PASSTHROUGH, null, null); public static final ResolvedFlow UUID_PASSTHROUGH = new ResolvedFlow(ResolveType.UUID_PASSTHROUGH, null, null);
public static final ResolvedFlow NAMED_HIT = new ResolvedFlow(ResolveType.NAMED_HIT, null, null); public static final ResolvedFlow NAMED_READ = new ResolvedFlow(ResolveType.NAMED_READ, null, null);
public static final ResolvedFlow NAMED_WRITE = new ResolvedFlow(ResolveType.NAMED_WRITE, null, null);
public static final ResolvedFlow ORPHAN = new ResolvedFlow(ResolveType.ORPHAN, null, null); public static final ResolvedFlow ORPHAN = new ResolvedFlow(ResolveType.ORPHAN, null, null);
public static final ResolvedFlow WRITE_REDIRECT = new ResolvedFlow(ResolveType.WRITE_REDIRECT, null,
"写操作请使用 /api/entity/{table}/save 端点,不走 flow 查询路径");
} }
/** /**
@@ -106,12 +109,7 @@ public class FlowNameResolver {
return ResolvedFlow.UUID_PASSTHROUGH; return ResolvedFlow.UUID_PASSTHROUGH;
} }
// 2. 写操作后缀拒绝(_SAVE/_UPDATE/_DELETE) // 2. _SEARCH 后缀 → 运行时合成(读流)
if (WRITE_SUFFIX_PATTERN.matcher(flowId).find()) {
return ResolvedFlow.WRITE_REDIRECT;
}
// 3. _SEARCH 后缀 → 运行时合成
String upper = flowId.toUpperCase(); String upper = flowId.toUpperCase();
if (upper.endsWith("_SEARCH")) { if (upper.endsWith("_SEARCH")) {
String tableName = upper.substring(0, upper.length() - 7); // strip "_SEARCH" String tableName = upper.substring(0, upper.length() - 7); // strip "_SEARCH"
@@ -119,12 +117,12 @@ public class FlowNameResolver {
if (synthesized != null) { if (synthesized != null) {
return synthesized; return synthesized;
} }
// tableName 不在 SYS_ENTITY → 继续走第4步(可能是命名服务 SOMETHING_SEARCH) // tableName 不在 SYS_ENTITY → 继续走第3步(可能是命名服务 SOMETHING_SEARCH)
} }
// 4. 其余命名服务:按 sys_serviceflow_id 精确查(主键查) // 3. 其余命名服务:按 sys_serviceflow_id 精确查(主键查);命中后按 contentxml 真实方法判读/写。
if (existsInServiceFlow(flowId)) { if (existsInServiceFlow(flowId)) {
return ResolvedFlow.NAMED_HIT; return classifier.isReadOnly(flowId) ? ResolvedFlow.NAMED_READ : ResolvedFlow.NAMED_WRITE;
} }
// 孤儿 // 孤儿

View File

@@ -0,0 +1,157 @@
package com.eip4.platform.metadata.flow;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* 服务流读/写分类器(写路径安全前置)。
*
* <p><b>判定依据(择优):按 contentxml 真实方法,而非命名后缀。</b>
* 老系统业务逻辑全在服务流的 {@code contentxml}:每个 {@code <node>} 里的
* {@code <service beanName="..." method="X">} 节点的 {@code method} 即该流真正调用的引擎方法。
* 只读方法({@code listSelect}/{@code loadPOJO}/{@code listSelectBySql}/{@code executeQueryForMap}…)
* 不改库;写方法({@code save}/{@code update}/{@code delete}/{@code insert}/{@code batchSave}/
* {@code startWorkflow}/{@code excute}…)改库或触发副作用。
*
* <p><b>为什么不用命名后缀</b>:研究文档 §5 实测——写流
* {@code OA_NOTICEMANAGE_ADD/_ADD_AND_SUBMIT/_PUBLISH/_UPDATE_AC/_SUBMIT}
* 不带 {@code _SAVE/_UPDATE/_DELETE} 后缀,旧后缀闸会把它们当读流无防护执行。
*
* <p><b>为什么不用 iscontrol</b>:DB 实测有 265 个写流 {@code iscontrol=0}
* (如 {@code HR_CARDCIRCULATION_ADD}/{@code _UPDATE}),仅凭 {@code iscontrol} 会漏判为读流。
* 按 contentxml 方法分类严格更安全。
*
* <p><b>fail-closed(默认拒绝)</b>:只有当流的<strong>每一个</strong> service 节点方法
* 都在只读白名单内时才判读;任一方法不在白名单(含无法识别的自定义方法)、
* 或流不存在、或解析异常 → 一律判写。宁可把读流误判为写(POST 仍可执行、仅 GET 被挡),
* 不可把写流误判为读(GET 即可触发写)。
*
* <p><b>零改 com.dsasp</b>:仅在现代层按 PK 参数化查 contentxml;无注入面。
*/
@Component
public class FlowReadWriteClassifier {
private static final Logger log = LoggerFactory.getLogger(FlowReadWriteClassifier.class);
/**
* 只读方法白名单:流的所有 service 节点方法都在此集合内才判读。
* 取自 DB 实测的全量方法分布;只纳入确定不改库、无副作用的查询方法。
*/
private static final Set<String> READ_ONLY_METHODS = Set.of(
"listselect",
"loadpojo",
"listselectbysql",
"executequeryformap",
"getwhereclause",
"gettabledefaultattribute",
"findmenubymenurootid",
"emptydisplayinfo");
/** 从 contentxml 抽取 {@code <service ... method="X">} 的 method 值。 */
private static final Pattern SERVICE_METHOD_PATTERN =
Pattern.compile("<service\\b[^>]*\\bmethod\\s*=\\s*\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
/** 分类结果。 */
public enum FlowAccess {
/** 只读流:所有 service 节点方法都在只读白名单内。 */
READ,
/** 写流:任一方法非只读、流不存在、或解析失败(fail-closed)。 */
WRITE
}
/** 分类结果缓存(按 flowId 缓存,与 FlowNameResolver evict 钩子语义对齐)。 */
private final Cache<String, FlowAccess> cache = Caffeine.newBuilder()
.maximumSize(5_000)
.build();
private final JdbcTemplate jdbcTemplate;
public FlowReadWriteClassifier(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 按 PK 精确查 contentxml 并分类。
*
* @param flowId sys_serviceflow 主键(= 服务名)
* @return {@link FlowAccess#READ} 仅当所有 service 节点方法都只读;否则 {@link FlowAccess#WRITE}
*/
public FlowAccess classify(String flowId) {
if (flowId == null || flowId.isBlank()) {
return FlowAccess.WRITE; // fail-closed
}
return cache.get(flowId, this::classifyUncached);
}
/** 便捷判定:是否只读流。 */
public boolean isReadOnly(String flowId) {
return classify(flowId) == FlowAccess.READ;
}
private FlowAccess classifyUncached(String flowId) {
String xml;
try {
// contentxml 是 xml 类型列,按 text 取出做正则;按 PK 参数化,无注入面。
xml = jdbcTemplate.queryForObject(
"SELECT contentxml::text FROM eip3.sys_serviceflow WHERE sys_serviceflow_id = ?",
String.class, flowId);
} catch (org.springframework.dao.EmptyResultDataAccessException e) {
// 流不存在:判写(fail-closed),让上游按写门处理(GET 挡、POST 由解析器 404)。
return FlowAccess.WRITE;
} catch (RuntimeException e) {
log.warn("[FLOW-CLASSIFY] 读取 contentxml 失败,fail-closed 判写: flowId={} err={}",
sanitize(flowId), e.toString());
return FlowAccess.WRITE;
}
if (xml == null || xml.isBlank()) {
return FlowAccess.WRITE; // 无内容 → fail-closed
}
Matcher m = SERVICE_METHOD_PATTERN.matcher(xml);
boolean sawService = false;
while (m.find()) {
sawService = true;
String method = m.group(1).trim().toLowerCase();
if (!READ_ONLY_METHODS.contains(method)) {
// 任一非只读方法 → 写流
return FlowAccess.WRITE;
}
}
// 无任何 service 节点(纯脚本流,可能含 put/save 副作用或调用其它写函数)→ fail-closed 判写。
if (!sawService) {
return FlowAccess.WRITE;
}
return FlowAccess.READ;
}
/** 失效单条分类缓存(流定义变更时调用,与 /api/meta/evict 钩子对齐)。 */
public void evict(String flowId) {
if (flowId != null && !flowId.isBlank()) {
cache.invalidate(flowId);
}
}
/** 失效全部分类缓存。 */
public void evictAll() {
cache.invalidateAll();
}
private static String sanitize(String id) {
if (id == null) {
return "";
}
return id.replaceAll("[^A-Za-z0-9_\\-]", "?");
}
}

View File

@@ -22,8 +22,10 @@ import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO; import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService; import com.dsasp.server.common.dataDic.service.POJOCRUDService;
import com.dsasp.server.common.util.UserSession; import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.metadata.flow.FlowInputCoercer;
import com.eip4.platform.metadata.flow.FlowNameResolver; import com.eip4.platform.metadata.flow.FlowNameResolver;
import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow; import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow;
import com.eip4.platform.metadata.flow.FlowReadWriteClassifier;
import com.eip4.platform.metadata.flow.UserColumnResolver; import com.eip4.platform.metadata.flow.UserColumnResolver;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -42,14 +44,18 @@ import io.swagger.v3.oas.annotations.Operation;
* UUID → 原样走引擎 PK 查;{@code <TABLE>_SEARCH} 且 TABLE 在 SYS_ENTITY → * UUID → 原样走引擎 PK 查;{@code <TABLE>_SEARCH} 且 TABLE 在 SYS_ENTITY →
* 运行时合成默认搜索流;其余命名服务 → 按 sys_serviceflow_id 精确查;孤儿 → 404。 * 运行时合成默认搜索流;其余命名服务 → 按 sys_serviceflow_id 精确查;孤儿 → 404。
* *
* <p><b>读写时机判断(REST 入口仅放行查询类服务流):</b>当前服务流引擎本身不区分读写—— * <p><b>读写门(写动作走服务流的安全前置):</b>{@link FlowNameResolver} 在引擎调用前
* 一个流既可挂 {@code listSelect}(读)也可挂 {@code save/update/delete}(写)service 节点, * 按 {@code contentxml} 真实方法({@link com.eip4.platform.metadata.flow.FlowReadWriteClassifier})
* 引擎统一走 {@code excute}。本 P1 阶段不在门面做引擎级读写闸(避免误判与维护负担), * 判定服务流读/写,门按 HTTP 方法分流:
* 而由调用方/运维按「服务流定义 XML 审阅」确认其为查询/报表类后才经此入口放行; * <ul>
* 客户库只读纪律下,仅执行确认无写动作的流(挑选过程见 P1 服务流实测报告)。 * <li><b>读流(NAMED_READ / SYNTHESIZED)</b>:GET、POST 皆可执行。</li>
* <b>风险与 P2 防护待办</b>:引擎不区分读写 ⇒ 该入口理论上可触发写流。P2 需补 * <li><b>写流(NAMED_WRITE)</b>:仅 POST 执行,且用 <em>真实 JWT 用户上下文</em>
* 「流定义静态扫描(service 节点 method 白名单:仅 listSelect/loadPOJO/executeQueryForMap 等读方法放行) * ({@code UserSession.get()},非 ADMIN)——使流脚本 {@code getCurrentUserId()} 得到真实拟稿人、
* + 最小权限只读连接 + statement_timeout」三层防护(见架构设计第四节安全方案、迁移手册新增坑位)。 * 写侧数据权限生效;GET 触发写流 → 403(防 URL 触发写)。</li>
* <li><b>UUID 直查</b>:读写未知,按写门处理(GET 仅放行经分类确认的读流,写流 403;POST 放行)。</li>
* </ul>
* 事务性:引擎实现 {@code FlowExcuteServiceImpl} 类级 {@code @Transactional},写流抛 RuntimeException 自动回滚。
* servicename 仅按 PK 精确查 sys_serviceflow(无注入面),不存在 → 404。
*/ */
@RestController @RestController
@RequestMapping("/api/flow") @RequestMapping("/api/flow")
@@ -58,20 +64,37 @@ public class FlowController {
private final FlowExcuteService flowExcuteService; private final FlowExcuteService flowExcuteService;
private final FlowNameResolver flowNameResolver; private final FlowNameResolver flowNameResolver;
private final UserColumnResolver userColumnResolver; private final UserColumnResolver userColumnResolver;
private final FlowReadWriteClassifier classifier;
private final FlowInputCoercer inputCoercer;
/** Spring 注入入口:带用户引用列解析器(read-path issue D1=603 修复)。 /** Spring 注入入口(5 参:读写分类器 + 类型强制器)。
* 多构造器场景须显式 @Autowired 指明注入构造,否则 Spring 回退无参构造致启动失败。 */ * 多构造器场景须显式 @Autowired 指明注入构造,否则 Spring 回退无参构造致启动失败。 */
@org.springframework.beans.factory.annotation.Autowired @org.springframework.beans.factory.annotation.Autowired
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver, public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver) { UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier,
FlowInputCoercer inputCoercer) {
this.flowExcuteService = flowExcuteService; this.flowExcuteService = flowExcuteService;
this.flowNameResolver = flowNameResolver; this.flowNameResolver = flowNameResolver;
this.userColumnResolver = userColumnResolver; this.userColumnResolver = userColumnResolver;
this.classifier = classifier;
this.inputCoercer = inputCoercer;
} }
/** 兼容老单测的两参构造(无用户列解析,行为同未修复前)。生产由 Spring 走三参构造。 */ /** 兼容老单测的四参构造(无类型强制器:写流跳过 coerce)。生产由 Spring 走五参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier) {
this(flowExcuteService, flowNameResolver, userColumnResolver, classifier, null);
}
/** 兼容老单测的三参构造(无分类器、无类型强制器)。生产由 Spring 走五参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver) {
this(flowExcuteService, flowNameResolver, userColumnResolver, null, null);
}
/** 兼容老单测的两参构造(无用户列解析、无分类器、无类型强制器)。生产由 Spring 走五参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver) { public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver) {
this(flowExcuteService, flowNameResolver, null); this(flowExcuteService, flowNameResolver, null, null, null);
} }
/** amis crud 默认每页条数(与前端 amis 默认 perPage 一致)。 */ /** amis crud 默认每页条数(与前端 amis 默认 perPage 一致)。 */
@@ -84,7 +107,7 @@ public class FlowController {
@RequestParam Map<String, String> allParams) { @RequestParam Map<String, String> allParams) {
Map<String, Object> map = new HashMap<>(allParams); Map<String, Object> map = new HashMap<>(allParams);
applyPaging(map); applyPaging(map);
return run(id, map); return run(id, map, false);
} }
/** POST 执行:JSON body 透传为服务流入参 map。body 为空时按空 map 执行。 */ /** POST 执行:JSON body 透传为服务流入参 map。body 为空时按空 map 执行。 */
@@ -94,7 +117,7 @@ public class FlowController {
@RequestBody(required = false) Map<String, Object> body) { @RequestBody(required = false) Map<String, Object> body) {
Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body); Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body);
applyPaging(map); applyPaging(map);
return run(id, map); return run(id, map, true);
} }
/** /**
@@ -133,43 +156,65 @@ public class FlowController {
} }
/** /**
* 统一执行 + 响应封装(F2-14 三级解析)。 * 统一执行 + 响应封装(含读写门)。
* *
* <ol> * <ol>
* <li>UUID → 原样传给引擎,按 PK 查 sys_serviceflow(现状逻辑)。</li> * <li>UUID → 直查引擎。读写未知:按 contentxml 分类,GET 上写流 403、POST 放行。</li>
* <li>{@code <TABLE>_SEARCH} 且 TABLE 在 SYS_ENTITY → 运行时合成搜索流并直接执行。</li> * <li>{@code <TABLE>_SEARCH} 合成 → 读流,GET/POST 皆执行。</li>
* <li>其余命名服务存在于 sys_serviceflow → 用原名传给引擎(PK 即名字)。</li> * <li>命名读流(NAMED_READ)→ GET/POST 皆执行。</li>
* <li>写操作后缀 (_SAVE/_UPDATE/_DELETE) → 404 + 引导提示。</li> * <li>命名写流(NAMED_WRITE)→ 仅 POST + 真实用户上下文执行;GET → 403。</li>
* <li>孤儿 → 404 + 明确错误体。</li> * <li>孤儿 → 404。</li>
* </ol> * </ol>
*
* @param isPost 是否 POST 请求(GET=false)。写流仅 POST 放行,防 URL 触发写。
*/ */
private ResponseEntity<Map<String, Object>> run(String id, Map<String, Object> map) { private ResponseEntity<Map<String, Object>> run(String id, Map<String, Object> map, boolean isPost) {
ResolvedFlow resolved = flowNameResolver.resolve(id); ResolvedFlow resolved = flowNameResolver.resolve(id);
return switch (resolved.type()) { return switch (resolved.type()) {
case UUID_PASSTHROUGH, NAMED_HIT -> { case UUID_PASSTHROUGH -> {
// UUID 或命名命中:直接走引擎(引擎按 PK 查 sys_serviceflow)。 // UUID 直查:读写未知。GET 上须确认是读流才放行(写流 403);POST 一律放行。
// 非合成路径无法稳妥推断实体表,故不做用户列解析(table=null)。 // 分类器缺省(老两/三参单测)时退回现状:GET 也放行(不破坏既有 UUID 报表)。
if (!isPost && classifier != null && !classifier.isReadOnly(id)) {
yield forbiddenWriteViaGet(id);
}
Properties ctx = UserSession.getAdmin(); Properties ctx = UserSession.getAdmin();
Object output = flowExcuteService.excute(map, ctx, id); Object output = flowExcuteService.excute(map, ctx, id);
yield ok(output, null); yield ok(output, null);
} }
case NAMED_READ -> {
// 命名读流:GET/POST 皆可。非合成路径无法稳妥推断实体表,故不做用户列解析(table=null)。
Properties ctx = UserSession.getAdmin();
Object output = flowExcuteService.excute(map, ctx, id);
yield ok(output, null);
}
case NAMED_WRITE -> {
// 命名写流:GET 拒绝(防 URL 触发写);POST 用真实 JWT 用户上下文执行
// (getCurrentUserId() 得真实拟稿人、写侧数据权限生效)。
// 事务由引擎 @Transactional 提供:写流抛 RuntimeException 自动回滚。
if (!isPost) {
yield forbiddenWriteViaGet(id);
}
// amis JSON body 全为 String,引擎 GeneralPO.load 按 POJOInfo 列类型直接 cast:
// ENUMERATE/INTEGER/STATUS→Integer、BOOLEAN→Boolean、DECIMAL→BigDecimal。
// coerceByFlowId 按 SYS_ENTITYATTRIBUTE 就地转换,fail-safe 不阻断写路径。
if (inputCoercer != null) {
inputCoercer.coerceByFlowId(id, map);
}
Properties ctx = currentCtx();
Object output = flowExcuteService.excute(map, ctx, id);
yield ok(output, null);
}
case SYNTHESIZED -> { case SYNTHESIZED -> {
// _SEARCH 合成:合成流已注册到 SynthesizedFlowRegistry, // _SEARCH 合成:合成流已注册到 SynthesizedFlowRegistry,
// FlowServiceWithSynthesis.getFlowDefinition 会按 key 命中, // FlowServiceWithSynthesis.getFlowDefinition 会按 key 命中,
// 直接用原始 flowId(已大写 = TABLE_SEARCH)调引擎。 // 直接用原始 flowId(已大写 = TABLE_SEARCH)调引擎。读流,GET/POST 皆可。
Properties ctx = UserSession.getAdmin(); Properties ctx = UserSession.getAdmin();
String flowKey = resolved.definition().getKey(); String flowKey = resolved.definition().getKey();
Object output = flowExcuteService.excute(map, ctx, flowKey); Object output = flowExcuteService.excute(map, ctx, flowKey);
// 合成搜索流的 key = <TABLE>_SEARCH,剥后缀即数据源实体表名,用于用户引用列 id→姓名解析 // 合成搜索流的 key = <TABLE>_SEARCH,剥后缀即数据源实体表名,用于用户引用列 id→姓名解析
yield ok(output, tableFromSearchKey(flowKey)); yield ok(output, tableFromSearchKey(flowKey));
} }
case WRITE_REDIRECT -> {
Map<String, Object> err = new LinkedHashMap<>();
err.put("status", 1);
err.put("msg", resolved.message());
yield ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
}
case ORPHAN -> { case ORPHAN -> {
Map<String, Object> err = new LinkedHashMap<>(); Map<String, Object> err = new LinkedHashMap<>();
err.put("status", 1); err.put("status", 1);
@@ -179,6 +224,26 @@ public class FlowController {
}; };
} }
/** 写流经 GET 触发 → 403(防 URL 触发写)。 */
private static ResponseEntity<Map<String, Object>> forbiddenWriteViaGet(String id) {
Map<String, Object> err = new LinkedHashMap<>();
err.put("status", 1);
err.put("msg", "写服务流不允许经 GET 执行,请用 POST: " + sanitize(id));
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(err);
}
/**
* 取当前请求的引擎上下文(JwtAuthFilter 已把真实用户绑到 UserSession,fallback ADMIN)。
* 写流用此 ctx:使 {@code getCurrentUserId()} 得真实拟稿人、写侧数据权限按真实用户生效。
*/
private static Properties currentCtx() {
Properties bound = UserSession.get();
if (bound != null) {
return bound;
}
return UserSession.getAdmin();
}
private ResponseEntity<Map<String, Object>> ok(Object output, String table) { private ResponseEntity<Map<String, Object>> ok(Object output, String table) {
Object data = unwrapCrudResult(normalize(output)); Object data = unwrapCrudResult(normalize(output));
// read-path issue D1=603:把元数据标记为用户引用的列 id/工号 → 姓名(仅在已知数据源实体的合成搜索流上) // read-path issue D1=603:把元数据标记为用户引用的列 id/工号 → 姓名(仅在已知数据源实体的合成搜索流上)

View File

@@ -0,0 +1,290 @@
package com.eip4.platform.metadata.flow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* FlowInputCoercer 单测:按 contentxml tableName + SYS_ENTITYATTRIBUTE 做 String→Java 类型强制转换。
* mock JdbcTemplate,不连库。
*/
class FlowInputCoercerTest {
private JdbcTemplate jdbc;
private FlowInputCoercer coercer;
@BeforeEach
void setUp() {
jdbc = mock(JdbcTemplate.class);
coercer = new FlowInputCoercer(jdbc);
}
// ── extractTableName ─────────────────────────────────────────────────────
@Test
@DisplayName("extractTableName: 正常格式 initValue 提取表名(大写)")
void extractTableNameNormal() {
String xml = "<flow><input>"
+ "<field name=\"tableName\" type=\"java.lang.String\" required=\"true\" initValue=\"OA_NOTICEMANAGE\"/>"
+ "</input></flow>";
assertEquals("OA_NOTICEMANAGE", coercer.extractTableName(xml));
}
@Test
@DisplayName("extractTableName: 无 tableName initValue → null(跨表流)")
void extractTableNameAbsent() {
String xml = "<flow><input><field name=\"other\" initValue=\"X\"/></input></flow>";
assertNull(coercer.extractTableName(xml));
}
@Test
@DisplayName("extractTableName: 空 contentxml → null")
void extractTableNameEmpty() {
assertNull(coercer.extractTableName(""));
assertNull(coercer.extractTableName(null));
}
// ── coerceValue ──────────────────────────────────────────────────────────
@Test
@DisplayName("coerceValue: INTEGER '1' → Integer(1)")
void coerceInteger() {
Object result = coercer.coerceValue("1", "INTEGER", "VERSION");
assertEquals(Integer.valueOf(1), result);
}
@Test
@DisplayName("coerceValue: ENUMERATE '0' → Integer(0)(IMPORTANT/APPROVALTYPE 场景)")
void coerceEnumerate() {
Object result = coercer.coerceValue("0", "ENUMERATE", "IMPORTANT");
assertEquals(Integer.valueOf(0), result);
}
@Test
@DisplayName("coerceValue: STATUS '2' → Integer(2)")
void coerceStatus() {
assertEquals(Integer.valueOf(2), coercer.coerceValue("2", "STATUS", "STATUS"));
}
@Test
@DisplayName("coerceValue: BOOLEAN '1' → Boolean.TRUE")
void coerceBooleanOne() {
assertEquals(Boolean.TRUE, coercer.coerceValue("1", "BOOLEAN", "ISACTIVE"));
}
@Test
@DisplayName("coerceValue: BOOLEAN '0' → Boolean.FALSE")
void coerceBooleanZero() {
assertEquals(Boolean.FALSE, coercer.coerceValue("0", "BOOLEAN", "ISDEL"));
}
@Test
@DisplayName("coerceValue: BOOLEAN 'true'/'false' 字符串识别")
void coerceBooleanTrueFalse() {
assertEquals(Boolean.TRUE, coercer.coerceValue("true", "BOOLEAN", "ISSEND"));
assertEquals(Boolean.FALSE, coercer.coerceValue("false", "BOOLEAN", "ISSEND"));
assertEquals(Boolean.TRUE, coercer.coerceValue("Y", "BOOLEAN", "ISSEND"));
assertEquals(Boolean.FALSE, coercer.coerceValue("N", "BOOLEAN", "ISSEND"));
}
@Test
@DisplayName("coerceValue: DECIMAL '3.14' → BigDecimal")
void coerceDecimal() {
assertEquals(new BigDecimal("3.14"), coercer.coerceValue("3.14", "DECIMAL", "AMOUNT"));
}
@Test
@DisplayName("coerceValue: NVARCHAR 不动(String 类型列直接返回原值)")
void coerceNvarcharNoOp() {
String val = "通知标题";
assertSame(val, coercer.coerceValue(val, "NVARCHAR", "TITLE"));
}
@Test
@DisplayName("coerceValue: CHAR 不动(UUID 主键列)")
void coerceCharNoOp() {
String val = "94b11e78-14e0-4a30-8be1-0c6fd913ccc6";
assertSame(val, coercer.coerceValue(val, "CHAR", "OA_NOTICEMANAGE_ID"));
}
@Test
@DisplayName("coerceValue: INTEGER parse 失败(非数字字符串)→ 原 String 保留(fail-safe)")
void coerceIntegerParseFail() {
Object result = coercer.coerceValue("abc", "INTEGER", "VERSION");
assertEquals("abc", result); // 原值保留,不抛异常
}
@Test
@DisplayName("coerceValue: BOOLEAN 无法识别 → 原 String 保留(fail-safe)")
void coerceBooleanUnrecognized() {
Object result = coercer.coerceValue("maybe", "BOOLEAN", "ISACTIVE");
assertEquals("maybe", result);
}
// ── coerce(contentXml, map) ───────────────────────────────────────────────
@Test
@DisplayName("coerce: 从 contentXml 提取表名,按元数据转换 ENUMERATE String→Integer")
void coerceFromContentXml() {
String xml = "<flow><input>"
+ "<field name=\"tableName\" initValue=\"OA_NOTICEMANAGE\"/>"
+ "</input></flow>";
// 模拟 SYS_ENTITYATTRIBUTE 查询返回 IMPORTANT→ENUMERATE, TITLE→NVARCHAR
when(jdbc.queryForList(anyString(), eq("OA_NOTICEMANAGE")))
.thenReturn(List.of(
Map.of("col", "IMPORTANT", "ref", "ENUMERATE"),
Map.of("col", "APPROVALTYPE","ref", "ENUMERATE"),
Map.of("col", "TITLE", "ref", "NVARCHAR"),
Map.of("col", "ISACTIVE", "ref", "BOOLEAN")
));
Map<String, Object> map = new HashMap<>();
map.put("IMPORTANT", "1");
map.put("APPROVALTYPE","0");
map.put("TITLE", "新通知");
map.put("ISACTIVE", "1");
coercer.coerce(xml, map);
assertEquals(Integer.valueOf(1), map.get("IMPORTANT"), "ENUMERATE String→Integer");
assertEquals(Integer.valueOf(0), map.get("APPROVALTYPE"), "ENUMERATE String→Integer");
assertEquals("新通知", map.get("TITLE"), "NVARCHAR 不动");
assertEquals(Boolean.TRUE, map.get("ISACTIVE"), "BOOLEAN String→Boolean");
}
@Test
@DisplayName("coerce: 值已是 Integer(非 String),幂等不重复转换")
void coerceIdempotent() {
String xml = "<flow><input><field name=\"tableName\" initValue=\"T\"/></input></flow>";
when(jdbc.queryForList(anyString(), eq("T")))
.thenReturn(List.of(Map.of("col", "CNT", "ref", "INTEGER")));
Map<String, Object> map = new HashMap<>();
map.put("CNT", Integer.valueOf(5)); // 已是 Integer
coercer.coerce(xml, map);
assertEquals(Integer.valueOf(5), map.get("CNT")); // 不变
}
@Test
@DisplayName("coerce: null map → 不查库,不崩")
void coerceNullMap() {
coercer.coerce("<flow/>", null); // 不抛
verify(jdbc, org.mockito.Mockito.never()).queryForList(anyString(), anyString());
}
@Test
@DisplayName("coerce: 无 tableName initValue → 不查库(跨表流跳过)")
void coerceNoTableName() {
coercer.coerce("<flow><input></input></flow>", Map.of("X", "1"));
verify(jdbc, org.mockito.Mockito.never()).queryForList(anyString(), anyString());
}
// ── coerceByFlowId ───────────────────────────────────────────────────────
@Test
@DisplayName("coerceByFlowId: 按 flowId 查 contentxml 提取表名,再 coerce map")
void coerceByFlowId() {
String flowId = "OA_NOTICEMANAGE_ADD";
String xml = "<flow><input><field name=\"tableName\" initValue=\"OA_NOTICEMANAGE\"/></input></flow>";
when(jdbc.queryForObject(anyString(), eq(String.class), eq(flowId))).thenReturn(xml);
when(jdbc.queryForList(anyString(), eq("OA_NOTICEMANAGE")))
.thenReturn(List.of(Map.of("col", "IMPORTANT", "ref", "ENUMERATE")));
Map<String, Object> map = new HashMap<>();
map.put("IMPORTANT", "1");
coercer.coerceByFlowId(flowId, map);
assertEquals(Integer.valueOf(1), map.get("IMPORTANT"));
}
@Test
@DisplayName("coerceByFlowId: flowId→tableName 缓存,第二次不再查 contentxml")
void coerceByFlowIdCached() {
String flowId = "OA_NOTICEMANAGE_ADD";
String xml = "<flow><input><field name=\"tableName\" initValue=\"OA_NOTICEMANAGE\"/></input></flow>";
when(jdbc.queryForObject(anyString(), eq(String.class), eq(flowId))).thenReturn(xml);
when(jdbc.queryForList(anyString(), eq("OA_NOTICEMANAGE")))
.thenReturn(List.of(Map.of("col", "IMPORTANT", "ref", "ENUMERATE")));
Map<String, Object> map1 = new HashMap<>(Map.of("IMPORTANT", "1"));
Map<String, Object> map2 = new HashMap<>(Map.of("IMPORTANT", "0"));
coercer.coerceByFlowId(flowId, map1);
coercer.coerceByFlowId(flowId, map2);
// contentxml 只查一次(tableName 已缓存)
verify(jdbc, times(1)).queryForObject(anyString(), eq(String.class), eq(flowId));
assertEquals(Integer.valueOf(1), map1.get("IMPORTANT"));
assertEquals(Integer.valueOf(0), map2.get("IMPORTANT"));
}
@Test
@DisplayName("coerceByFlowId: flowId 不存在(EmptyResultDataAccessException)→ 跳过,不崩")
void coerceByFlowIdFlowNotFound() {
when(jdbc.queryForObject(anyString(), eq(String.class), eq("GHOST")))
.thenThrow(new EmptyResultDataAccessException(1));
Map<String, Object> map = new HashMap<>(Map.of("X", "1"));
coercer.coerceByFlowId("GHOST", map);
assertEquals("1", map.get("X")); // 原值保留(fail-safe)
}
@Test
@DisplayName("coerceByFlowId: DB 异常 → 跳过,不崩(fail-safe)")
void coerceByFlowIdDbError() {
when(jdbc.queryForObject(anyString(), eq(String.class), eq("BOOM")))
.thenThrow(new RuntimeException("connection reset"));
Map<String, Object> map = new HashMap<>(Map.of("X", "1"));
coercer.coerceByFlowId("BOOM", map);
assertEquals("1", map.get("X"));
}
@Test
@DisplayName("coerceByFlowId: null/空 flowId → 不查库,不崩")
void coerceByFlowIdNullId() {
coercer.coerceByFlowId(null, new HashMap<>());
coercer.coerceByFlowId("", new HashMap<>());
verify(jdbc, org.mockito.Mockito.never()).queryForObject(anyString(), eq(String.class), anyString());
}
@Test
@DisplayName("evictAll: 失效后重新查库")
void evictAllReclassifies() {
String flowId = "X_WRITE";
String xml = "<flow><input><field name=\"tableName\" initValue=\"T\"/></input></flow>";
when(jdbc.queryForObject(anyString(), eq(String.class), eq(flowId))).thenReturn(xml);
when(jdbc.queryForList(anyString(), eq("T")))
.thenReturn(List.of(Map.of("col", "CNT", "ref", "INTEGER")));
coercer.coerceByFlowId(flowId, new HashMap<>(Map.of("CNT", "1")));
coercer.evictAll();
coercer.coerceByFlowId(flowId, new HashMap<>(Map.of("CNT", "2")));
verify(jdbc, times(2)).queryForObject(anyString(), eq(String.class), eq(flowId));
}
}

View File

@@ -31,13 +31,17 @@ class FlowNameResolverTest {
private JdbcTemplate jdbc; private JdbcTemplate jdbc;
private SynthesizedFlowRegistry registry; private SynthesizedFlowRegistry registry;
private FlowReadWriteClassifier classifier;
private FlowNameResolver resolver; private FlowNameResolver resolver;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
jdbc = mock(JdbcTemplate.class); jdbc = mock(JdbcTemplate.class);
registry = new SynthesizedFlowRegistry(); registry = new SynthesizedFlowRegistry();
resolver = new FlowNameResolver(jdbc, registry); classifier = mock(FlowReadWriteClassifier.class);
// 默认把命名命中判为读流;写流用例单独覆盖(isReadOnly=false)。
when(classifier.isReadOnly(anyString())).thenReturn(true);
resolver = new FlowNameResolver(jdbc, registry, classifier);
} }
// ── 第一级:UUID ────────────────────────────────────────────────────────── // ── 第一级:UUID ──────────────────────────────────────────────────────────
@@ -124,14 +128,28 @@ class FlowNameResolverTest {
// ── 第三级:命名服务 ───────────────────────────────────────────────────── // ── 第三级:命名服务 ─────────────────────────────────────────────────────
@Test @Test
@DisplayName("非 UUID 非 _SEARCH 且在 sys_serviceflow → NAMED_HIT") @DisplayName("非 UUID 非 _SEARCH 且在 sys_serviceflow + 分类读 → NAMED_READ")
void namedServiceHit() { void namedReadServiceHit() {
when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class), when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class),
eq("loadTreeChild"))) eq("loadTreeChild")))
.thenReturn(1); .thenReturn(1);
when(classifier.isReadOnly("loadTreeChild")).thenReturn(true);
ResolvedFlow r = resolver.resolve("loadTreeChild"); ResolvedFlow r = resolver.resolve("loadTreeChild");
assertEquals(ResolveType.NAMED_HIT, r.type()); assertEquals(ResolveType.NAMED_READ, r.type());
}
@Test
@DisplayName("命名命中 + 分类写(contentxml 含写方法)→ NAMED_WRITE,不再按后缀")
void namedWriteServiceHit() {
// 写流不带 _SAVE/_UPDATE/_DELETE 后缀(如 _ADD),旧后缀闸会漏挡;新分类按 contentxml 判写。
when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class),
eq("OA_NOTICEMANAGE_ADD")))
.thenReturn(1);
when(classifier.isReadOnly("OA_NOTICEMANAGE_ADD")).thenReturn(false);
ResolvedFlow r = resolver.resolve("OA_NOTICEMANAGE_ADD");
assertEquals(ResolveType.NAMED_WRITE, r.type());
} }
@Test @Test
@@ -145,26 +163,27 @@ class FlowNameResolverTest {
assertEquals(ResolveType.ORPHAN, r.type()); assertEquals(ResolveType.ORPHAN, r.type());
} }
// ── 写操作后缀拒绝 ─────────────────────────────────────────────────────── // ── 读写分类(取代命名后缀闸)───────────────────────────────────────────
@Test @Test
@DisplayName("_SAVE 后缀 → WRITE_REDIRECT,不查库") @DisplayName("名为 _UPDATE 但 contentxml 只读 → NAMED_READ(旧后缀闸会误判 404,新分类放行读)")
void saveSuffixWriteRedirect() { void updateNamedButReadOnlyClassifiedRead() {
ResolvedFlow r = resolver.resolve("SYS_USER_SAVE"); // 旧逻辑:_UPDATE 后缀 → WRITE_REDIRECT(404)。新逻辑按 contentxml 真实方法判定。
assertEquals(ResolveType.WRITE_REDIRECT, r.type()); when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class),
verify(jdbc, never()).queryForList(anyString(), any(Object[].class)); eq("SYS_ROLE_UPDATE")))
.thenReturn(1);
when(classifier.isReadOnly("SYS_ROLE_UPDATE")).thenReturn(true);
assertEquals(ResolveType.NAMED_READ, resolver.resolve("SYS_ROLE_UPDATE").type());
} }
@Test @Test
@DisplayName("_UPDATE 后缀 → WRITE_REDIRECT") @DisplayName("名为 _ADD(无 _SAVE/_UPDATE/_DELETE 后缀)但 contentxml 含写方法 → NAMED_WRITE(旧后缀闸漏挡)")
void updateSuffixWriteRedirect() { void addNamedWriteClassifiedWrite() {
assertEquals(ResolveType.WRITE_REDIRECT, resolver.resolve("SYS_ROLE_UPDATE").type()); when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class),
} eq("VIEW_JGGL_ADD")))
.thenReturn(1);
@Test when(classifier.isReadOnly("VIEW_JGGL_ADD")).thenReturn(false);
@DisplayName("_DELETE 后缀 → WRITE_REDIRECT") assertEquals(ResolveType.NAMED_WRITE, resolver.resolve("VIEW_JGGL_ADD").type());
void deleteSuffixWriteRedirect() {
assertEquals(ResolveType.WRITE_REDIRECT, resolver.resolve("VIEW_JGGL_DELETE").type());
} }
// ── null / 空 ────────────────────────────────────────────────────────────── // ── null / 空 ──────────────────────────────────────────────────────────────

View File

@@ -0,0 +1,149 @@
package com.eip4.platform.metadata.flow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import com.eip4.platform.metadata.flow.FlowReadWriteClassifier.FlowAccess;
/**
* 读写分类器单测:按 contentxml 真实方法判读/写,fail-closed。
* mock JdbcTemplate(返回 contentxml::text),不连库。
*/
class FlowReadWriteClassifierTest {
private JdbcTemplate jdbc;
private FlowReadWriteClassifier classifier;
@BeforeEach
void setUp() {
jdbc = mock(JdbcTemplate.class);
classifier = new FlowReadWriteClassifier(jdbc);
}
private void stubXml(String flowId, String xml) {
when(jdbc.queryForObject(anyString(), eq(String.class), eq(flowId))).thenReturn(xml);
}
@Test
@DisplayName("所有 service 节点都是只读方法 → READ")
void allReadMethods() {
stubXml("X_SEARCH", "<flow><node><service beanName=\"pojoCRUDService\" method=\"listSelect\"/></node></flow>");
assertEquals(FlowAccess.READ, classifier.classify("X_SEARCH"));
}
@Test
@DisplayName("loadPOJO 读流 → READ(大小写不敏感)")
void loadPojoRead() {
stubXml("X_LOAD", "<flow><node><service beanName=\"pojoCRUDService\" method=\"LOADPOJO\"/></node></flow>");
assertEquals(FlowAccess.READ, classifier.classify("X_LOAD"));
}
@Test
@DisplayName("含 save 写方法 → WRITE(OA_NOTICEMANAGE_ADD 形态,不带 _SAVE 后缀也被判写)")
void saveMethodWrite() {
stubXml("OA_NOTICEMANAGE_ADD",
"<flow><start><script>map.put(\"USER_ID\",getCurrentUserId())</script></start>"
+ "<node><service beanName=\"pojoCRUDService\" method=\"save\"/></node></flow>");
assertEquals(FlowAccess.WRITE, classifier.classify("OA_NOTICEMANAGE_ADD"));
}
@Test
@DisplayName("含 update 写方法 → WRITE")
void updateMethodWrite() {
stubXml("X_UPDATE_AC", "<flow><node><service beanName=\"pojoCRUDService\" method=\"update\"/></node></flow>");
assertEquals(FlowAccess.WRITE, classifier.classify("X_UPDATE_AC"));
}
@Test
@DisplayName("含 startWorkflow(审批副作用)→ WRITE")
void startWorkflowWrite() {
stubXml("X_SUBMIT", "<flow><node><service beanName=\"workflowService\" method=\"startWorkflow\"/></node></flow>");
assertEquals(FlowAccess.WRITE, classifier.classify("X_SUBMIT"));
}
@Test
@DisplayName("混合:一读一写 → WRITE(任一非只读即写)")
void mixedReadAndWrite() {
stubXml("X_MIX",
"<flow><node><service method=\"listSelect\"/></node>"
+ "<node><service method=\"delete\"/></node></flow>");
assertEquals(FlowAccess.WRITE, classifier.classify("X_MIX"));
}
@Test
@DisplayName("无 service 节点(纯脚本流,可能含副作用)→ WRITE(fail-closed)")
void noServiceNodeFailClosed() {
stubXml("X_SCRIPT", "<flow><start><script>map.put(\"A\",1)</script></start><end/></flow>");
assertEquals(FlowAccess.WRITE, classifier.classify("X_SCRIPT"));
}
@Test
@DisplayName("流不存在(EmptyResultDataAccessException)→ WRITE(fail-closed)")
void flowNotFoundFailClosed() {
when(jdbc.queryForObject(anyString(), eq(String.class), eq("GHOST")))
.thenThrow(new EmptyResultDataAccessException(1));
assertEquals(FlowAccess.WRITE, classifier.classify("GHOST"));
}
@Test
@DisplayName("DB 异常 → WRITE(fail-closed)")
void dbErrorFailClosed() {
when(jdbc.queryForObject(anyString(), eq(String.class), eq("BOOM")))
.thenThrow(new RuntimeException("connection reset"));
assertEquals(FlowAccess.WRITE, classifier.classify("BOOM"));
}
@Test
@DisplayName("null contentxml → WRITE(fail-closed)")
void nullXmlFailClosed() {
when(jdbc.queryForObject(anyString(), eq(String.class), eq("NULLXML"))).thenReturn(null);
assertEquals(FlowAccess.WRITE, classifier.classify("NULLXML"));
}
@Test
@DisplayName("null/空 flowId → WRITE(fail-closed),不查库")
void nullFlowIdFailClosed() {
assertEquals(FlowAccess.WRITE, classifier.classify(null));
assertEquals(FlowAccess.WRITE, classifier.classify(" "));
verify(jdbc, org.mockito.Mockito.never()).queryForObject(anyString(), eq(String.class), anyString());
}
@Test
@DisplayName("结果缓存:第二次 classify 不再查库")
void resultIsCached() {
stubXml("X_SEARCH", "<flow><node><service method=\"listSelect\"/></node></flow>");
classifier.classify("X_SEARCH");
classifier.classify("X_SEARCH");
verify(jdbc, times(1)).queryForObject(anyString(), eq(String.class), eq("X_SEARCH"));
}
@Test
@DisplayName("evict 后重新查库")
void evictReclassifies() {
stubXml("X_SEARCH", "<flow><node><service method=\"listSelect\"/></node></flow>");
classifier.classify("X_SEARCH");
classifier.evict("X_SEARCH");
classifier.classify("X_SEARCH");
verify(jdbc, times(2)).queryForObject(anyString(), eq(String.class), eq("X_SEARCH"));
}
@Test
@DisplayName("isReadOnly 便捷判定与 classify 一致")
void isReadOnlyConsistent() {
stubXml("R", "<flow><node><service method=\"listSelect\"/></node></flow>");
stubXml("W", "<flow><node><service method=\"save\"/></node></flow>");
org.junit.jupiter.api.Assertions.assertTrue(classifier.isReadOnly("R"));
org.junit.jupiter.api.Assertions.assertFalse(classifier.isReadOnly("W"));
}
}

View File

@@ -21,10 +21,14 @@ import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.mockito.MockedStatic;
import com.dsasp.server.common.core.FlowDefinition; import com.dsasp.server.common.core.FlowDefinition;
import com.dsasp.server.common.core.service.FlowExcuteService; import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO; import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService; import com.dsasp.server.common.dataDic.service.POJOCRUDService;
import com.dsasp.server.common.user.service.LoggedInUser;
import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.metadata.flow.FlowNameResolver; import com.eip4.platform.metadata.flow.FlowNameResolver;
import com.eip4.platform.metadata.flow.FlowNameResolver.ResolveType; import com.eip4.platform.metadata.flow.FlowNameResolver.ResolveType;
import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow; import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow;
@@ -64,9 +68,14 @@ class FlowControllerTest {
return ResolvedFlow.UUID_PASSTHROUGH; return ResolvedFlow.UUID_PASSTHROUGH;
} }
/** NAMED_HIT 解析结果 */ /** NAMED_READ 解析结果(命名读流,GET/POST 皆执行) */
private static ResolvedFlow namedHit() { private static ResolvedFlow namedHit() {
return ResolvedFlow.NAMED_HIT; return ResolvedFlow.NAMED_READ;
}
/** NAMED_WRITE 解析结果(命名写流,仅 POST 执行) */
private static ResolvedFlow namedWrite() {
return ResolvedFlow.NAMED_WRITE;
} }
/** SYNTHESIZED 解析结果(带 mock FlowDefinition) */ /** SYNTHESIZED 解析结果(带 mock FlowDefinition) */
@@ -250,16 +259,19 @@ class FlowControllerTest {
} }
@Test @Test
@DisplayName("11. WRITE_REDIRECT: _SAVE 后缀 → 404 + 引导提示") @DisplayName("11. NAMED_WRITE 经 GET → 403(防 URL 触发写),引擎不被调用")
void writeSuffixReturns404() { void writeFlowViaGetForbidden() {
String flowId = "SYS_USER_SAVE"; String flowId = "OA_NOTICEMANAGE_ADD";
FlowExcuteService engine = mock(FlowExcuteService.class); FlowExcuteService engine = mock(FlowExcuteService.class);
FlowController controller = new FlowController(engine, resolverReturning(flowId, ResolvedFlow.WRITE_REDIRECT)); FlowController controller = new FlowController(engine, resolverReturning(flowId, namedWrite()));
ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>()); ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>());
assertEquals(HttpStatus.NOT_FOUND, resp.getStatusCode()); assertEquals(HttpStatus.FORBIDDEN, resp.getStatusCode());
assertEquals(1, resp.getBody().get("status")); assertEquals(1, resp.getBody().get("status"));
assertNotNull(resp.getBody().get("msg")); assertNotNull(resp.getBody().get("msg"));
// 关键安全断言:写流经 GET 绝不触达引擎。
org.mockito.Mockito.verify(engine, org.mockito.Mockito.never())
.excute(any(), any(), org.mockito.ArgumentMatchers.anyString());
} }
@Test @Test
@@ -396,4 +408,125 @@ class FlowControllerTest {
org.junit.jupiter.api.Assertions.assertFalse(sent.containsKey(POJOCRUDService.PAGE_SIZE)); org.junit.jupiter.api.Assertions.assertFalse(sent.containsKey(POJOCRUDService.PAGE_SIZE));
assertEquals("财务", sent.get("DEPT"), "过滤键保留"); assertEquals("财务", sent.get("DEPT"), "过滤键保留");
} }
// ── 读写门安全测试(写路径走服务流)────────────────────────────────────
@Test
@DisplayName("17. NAMED_WRITE 经 POST → 执行,且用真实 JWT 用户上下文(非 ADMIN),拟稿人正确")
void writeFlowViaPostUsesRealUserCtx() {
String flowId = "OA_NOTICEMANAGE_ADD";
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), eq(flowId))).thenReturn(new HashMap<>());
FlowController controller = new FlowController(engine, resolverReturning(flowId, namedWrite()));
// 真实用户 ctx(JWT 绑定到 UserSession.get())—— ceshi 而非 ADMIN
Properties realUser = new Properties();
realUser.setProperty(LoggedInUser.CURRENTUSER, "ceshi");
try (MockedStatic<UserSession> us = org.mockito.Mockito.mockStatic(UserSession.class)) {
us.when(UserSession::get).thenReturn(realUser);
Map<String, Object> body = new HashMap<>();
body.put("TITLE", "新通知");
ResponseEntity<Map<String, Object>> resp = controller.executePost(flowId, body);
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
// 关键安全断言:写流用真实用户 ctx 执行(getCurrentUserId 得 ceshi、写侧数据权限生效),非 ADMIN。
ArgumentCaptor<Properties> ctxCap = ArgumentCaptor.forClass(Properties.class);
org.mockito.Mockito.verify(engine).excute(any(), ctxCap.capture(), eq(flowId));
assertEquals("ceshi", ctxCap.getValue().getProperty(LoggedInUser.CURRENTUSER),
"写流须用真实 JWT 用户上下文执行(拟稿人=ceshi),不得用 ADMIN");
}
}
@Test
@DisplayName("18. NAMED_WRITE 经 POST 但未登录(UserSession.get()=null) → 回退 ADMIN 执行(不崩)")
void writeFlowViaPostFallsBackToAdminWhenUnbound() {
String flowId = "OA_NOTICEMANAGE_ADD";
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), eq(flowId))).thenReturn(new HashMap<>());
FlowController controller = new FlowController(engine, resolverReturning(flowId, namedWrite()));
try (MockedStatic<UserSession> us = org.mockito.Mockito.mockStatic(UserSession.class)) {
us.when(UserSession::get).thenReturn(null);
us.when(UserSession::getAdmin).thenReturn(adminCtx());
ResponseEntity<Map<String, Object>> resp = controller.executePost(flowId, new HashMap<>());
assertEquals(HttpStatus.OK, resp.getStatusCode());
org.mockito.Mockito.verify(engine).excute(any(), any(Properties.class), eq(flowId));
}
}
@Test
@DisplayName("19. NAMED_READ 经 GET → 正常执行(读流 GET 放行)")
void readFlowViaGetExecutes() {
String flowId = "OA_NOTICEMANAGE_LOAD";
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), eq(flowId))).thenReturn(new HashMap<>());
FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit()));
ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>());
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
org.mockito.Mockito.verify(engine).excute(any(), any(), eq(flowId));
}
@Test
@DisplayName("20. UUID 直查写流经 GET → 403(按 contentxml 分类为写则 GET 拒绝),引擎不被调用")
void uuidWriteFlowViaGetForbidden() {
String flowId = "550e8400-e29b-41d4-a716-446655440000";
FlowExcuteService engine = mock(FlowExcuteService.class);
com.eip4.platform.metadata.flow.FlowReadWriteClassifier classifier =
mock(com.eip4.platform.metadata.flow.FlowReadWriteClassifier.class);
when(classifier.isReadOnly(flowId)).thenReturn(false); // contentxml 判写
FlowController controller = new FlowController(engine,
resolverReturning(flowId, uuidPassthrough()), null, classifier);
ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>());
assertEquals(HttpStatus.FORBIDDEN, resp.getStatusCode());
org.mockito.Mockito.verify(engine, org.mockito.Mockito.never())
.excute(any(), any(), org.mockito.ArgumentMatchers.anyString());
}
@Test
@DisplayName("21. UUID 直查读流经 GET → 执行(contentxml 判读则放行)")
void uuidReadFlowViaGetExecutes() {
String flowId = "550e8400-e29b-41d4-a716-446655440000";
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), eq(flowId))).thenReturn(new HashMap<>());
com.eip4.platform.metadata.flow.FlowReadWriteClassifier classifier =
mock(com.eip4.platform.metadata.flow.FlowReadWriteClassifier.class);
when(classifier.isReadOnly(flowId)).thenReturn(true); // contentxml 判读
FlowController controller = new FlowController(engine,
resolverReturning(flowId, uuidPassthrough()), null, classifier);
ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>());
assertEquals(HttpStatus.OK, resp.getStatusCode());
org.mockito.Mockito.verify(engine).excute(any(), any(), eq(flowId));
}
@Test
@DisplayName("22. UUID 直查写流经 POST → 执行(POST 放行写流)")
void uuidWriteFlowViaPostExecutes() {
String flowId = "550e8400-e29b-41d4-a716-446655440000";
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), eq(flowId))).thenReturn(new HashMap<>());
com.eip4.platform.metadata.flow.FlowReadWriteClassifier classifier =
mock(com.eip4.platform.metadata.flow.FlowReadWriteClassifier.class);
when(classifier.isReadOnly(flowId)).thenReturn(false);
FlowController controller = new FlowController(engine,
resolverReturning(flowId, uuidPassthrough()), null, classifier);
ResponseEntity<Map<String, Object>> resp = controller.executePost(flowId, new HashMap<>());
assertEquals(HttpStatus.OK, resp.getStatusCode());
org.mockito.Mockito.verify(engine).excute(any(), any(), eq(flowId));
}
/** ADMIN 上下文桩(CURRENTUSER=ADMIN)。 */
private static Properties adminCtx() {
Properties p = new Properties();
p.setProperty(LoggedInUser.CURRENTUSER, LoggedInUser.ADMIN);
return p;
}
} }