security(P0③): 脚本端点拆分隔离 RCE + 路径穿越守卫 + Poc 控制器门禁

拆 ScriptExecuteController(执行请求体任意 Groovy=RCE)为 @Profile(BYPASS) 仅非生产装配;生产改写脚本重放迁至新 ScriptReplayController(只取脚本库内已审产物)。RewrittenScriptStore.load 加 templateId 路径包含校验(resolve+normalize+startsWith,+NUL 字节兜底)防穿越读库外脚本。三个 Poc*Controller(含裸拼 DROP TABLE)全 @Profile(BYPASS)。抽 ScriptFacadeRunner 共享。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-25 11:41:21 +08:00
parent 1f2365fa26
commit 980d83ed15
10 changed files with 390 additions and 260 deletions

View File

@@ -33,7 +33,8 @@ public class RewrittenScriptStore {
public RewrittenScriptStore(
@Value("${eip4.script.rewritten-root:tools/s3_rewriter/output/rewritten}") String rewrittenRoot) {
this.root = Path.of(rewrittenRoot);
// normalize 一次,后续 load 用 startsWith(root) 做路径包含校验防 ../ 穿越。
this.root = Path.of(rewrittenRoot).normalize();
}
/**
@@ -47,8 +48,16 @@ public class RewrittenScriptStore {
if (templateId == null || templateId.isBlank()) {
return null;
}
Path dir = root.resolve(templateId);
if (!Files.isDirectory(dir)) {
// P0 安全(2026-06-24 架构评审):templateId 来自请求体,resolve 后 normalize 并校验仍在
// root 之内,防 `../../` 穿越读取脚本库外任意 .groovy 文件并交保真层执行(路径穿越→RCE)。
Path dir;
try {
dir = root.resolve(templateId).normalize();
} catch (java.nio.file.InvalidPathException e) {
// 非法路径字符(如 NUL 字节)→ 当作未找到,优雅降级而非 500。
return null;
}
if (!dir.startsWith(root) || !Files.isDirectory(dir)) {
return null;
}
String prefix = seq + ".";

View File

@@ -0,0 +1,36 @@
package com.eip4.platform.metadata.script;
import java.util.List;
import java.util.Map;
import javax.script.Bindings;
import com.dsasp.server.dataDic.binding.ScriptingEnginesManager;
/**
* 脚本 facade 执行的共享原语:把脚本经保真层 {@link ScriptingEnginesManager} 执行,
* 行数据上下文 + facade 动词注入 {@link Bindings},返回捕获的 amis 事件动作指令。
*
* <p>P0 拆分(2026-06-24 架构评审)后,「生产改写脚本重放」({@code ScriptReplayController})与
* 「开发任意脚本执行」({@code ScriptExecuteController},@Profile 旁路限定)共用本原语,避免重复。
*/
public final class ScriptFacadeRunner {
private ScriptFacadeRunner() {
}
/**
* 用 facade 动词表执行脚本,返回捕获的 amis 指令。
*
* @param key 缓存/诊断键(模板/序号派生),允许 null
* @param script 脚本正文
* @param item 当前行数据域(facade 动词读写)
*/
public static List<Map<String, Object>> run(String key, String script, Map<String, Object> item) {
ScriptFacade facade = new ScriptFacade(item);
Bindings bindings = facade.buildBindings(item);
ScriptingEnginesManager.getScriptingEnginesManager()
.evaluateGroovy(key, script, bindings);
return facade.getCommands();
}
}

View File

@@ -7,6 +7,7 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@@ -15,6 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.auth.security.SecurityProfiles;
/**
* WS1 主子表级联验证:SYS_DATA_LOG(主) → DETAILLIST → SYS_DATA_LOGITEM(子)。
@@ -23,6 +25,7 @@ import com.dsasp.server.common.util.UserSession;
* 测试行以 COLUMNNAME=EIP4POC_* 标记,结束后行数断言复原,残留兜底清理。
*/
@RestController
@Profile(SecurityProfiles.BYPASS)
public class PocMasterSubController {
// 首选 SYS_DATA_LOG 对在 diff 更新时暴露了选表不当:其子表为 insert-only 设计

View File

@@ -11,12 +11,14 @@ import javax.script.SimpleBindings;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.dataDic.binding.ScriptingEnginesManager;
import com.eip4.platform.auth.security.SecurityProfiles;
import groovy.lang.Closure;
@@ -27,6 +29,7 @@ import groovy.lang.Closure;
* 指令列表——即「脚本文本零修改,换 facade 实现」方案的最小实证。
*/
@RestController
@Profile(SecurityProfiles.BYPASS)
public class PocScriptTestController {
private final JdbcTemplate jdbcTemplate;

View File

@@ -7,11 +7,14 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.eip4.platform.auth.security.SecurityProfiles;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.DataDicService;
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
@@ -22,8 +25,13 @@ import com.dsasp.server.dataDic.bean.Entity;
* WS1 写路径一键验证(PoC 方案 3.1 步骤 7):
* 克隆既有小实体的元数据 → 动态生成并执行 CREATE TABLE → CRUD 往返 → 全量清理。
* 所有产物以 target 表名隔离(默认 EIP4POCTEST),结束后物理表与元数据一并删除。
*
* <p><strong>P0 安全(2026-06-24 架构评审)</strong>:本 PoC 控制器 {@code cleanup} 以
* {@code DROP TABLE IF EXISTS <target>} 裸拼请求参数(可传 {@code target=SYS_USER} 任意删表),
* 严禁随生产 jar 装配。故 {@code @Profile(SecurityProfiles.BYPASS)}——仅 dev/local/ci/parity 装配。
*/
@RestController
@Profile(SecurityProfiles.BYPASS)
public class PocWriteTestController {
private final DataDicService dataDicService;

View File

@@ -4,56 +4,40 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.script.Bindings;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.dataDic.binding.ScriptingEnginesManager;
import com.eip4.platform.metadata.flow.EnumDisplayResolver;
import com.eip4.platform.metadata.script.RewrittenScriptStore;
import com.eip4.platform.metadata.script.ScriptFacade;
import com.eip4.platform.auth.security.SecurityProfiles;
import com.eip4.platform.metadata.script.ScriptFacadeRunner;
/**
* 脚本执行端点(P4 脚本迁移线 任务2 集成)。
* 脚本<strong>开发/调试</strong>执行端点——执行<em>请求体里的任意脚本</em>,仅供改写验证用。
*
* <p>把(改写后的)Groovy 脚本经保真层 {@link ScriptingEnginesManager} 执行,行数据上下文 +
* 31 个 facade 动词由 {@link ScriptFacade} 注入 {@link Bindings}:
* <ul>
* <li>服务端语义动词(getFieldValue 等)在服务端求值;</li>
* <li>UI 语义动词(setFieldVisible/showToast/addSubTableButton…)捕获为 amis 事件动作
* 指令 JSON 数组(actionType/componentId/args)返回前端。</li>
* </ul>
* <p><strong>P0 安全(2026-06-24 架构评审)</strong>:本控制器的 {@code /api/script/execute}
* 直接执行请求体携带的任意 Groovy(= 远程代码执行 RCE),严禁随生产 jar 装配。故全类
* {@code @Profile(SecurityProfiles.BYPASS)}——<strong>仅 dev/local/ci/parity 装配,生产不可达</strong>。
*
* <p>架构:本控制器与 {@link ScriptFacade} 均在现代层 {@code com.eip4.*},仅向保真层注入闭包,
* <p>生产运行时的「改写后脚本重放」(脚本来源 = 脚本库内已审产物,非请求体)已隔离到
* {@code ScriptReplayController}(/api/script/execute-template,无 @Profile,随生产装配)。
*
* <p>架构:本控制器在现代层 {@code com.eip4.*},仅经 {@link ScriptFacadeRunner} 向保真层注入闭包,
* 不改 {@code com.dsasp} 源码。
*/
@RestController
@Profile(SecurityProfiles.BYPASS)
public class ScriptExecuteController {
private final JdbcTemplate jdbcTemplate;
private final RewrittenScriptStore rewrittenScriptStore;
/** 小修#2:脚本执行前给 item 注入枚举列显示串(复刻老系统 grid 行 item 语义),修 {@code item['ISPLACE']=="未归档"} 类脚本。 */
private final EnumDisplayResolver enumDisplayResolver;
@Autowired
public ScriptExecuteController(JdbcTemplate jdbcTemplate, RewrittenScriptStore rewrittenScriptStore,
EnumDisplayResolver enumDisplayResolver) {
public ScriptExecuteController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.rewrittenScriptStore = rewrittenScriptStore;
this.enumDisplayResolver = enumDisplayResolver;
}
/** 兼容旧 2 参构造(单测/旧接线):从 jdbcTemplate 自建枚举显示值解析器。 */
public ScriptExecuteController(JdbcTemplate jdbcTemplate, RewrittenScriptStore rewrittenScriptStore) {
this(jdbcTemplate, rewrittenScriptStore, new EnumDisplayResolver(jdbcTemplate));
}
/**
@@ -76,7 +60,7 @@ public class ScriptExecuteController {
? (Map<String, Object>) body.get("item") : new LinkedHashMap<>();
try {
List<Map<String, Object>> commands = runWithFacade(null, script, item);
List<Map<String, Object>> commands = ScriptFacadeRunner.run(null, script, item);
resp.put("passed", true);
resp.put("item", item);
resp.put("commands", commands);
@@ -92,9 +76,6 @@ public class ScriptExecuteController {
/**
* 按模板名从客户库取「库内原始脚本」执行(P4-2 端到端验证端点,保留兼容)。
*
* <p>注:P4-5 改写后脚本挂回链路走 {@link #executeTemplateRewritten}(按 templateId/seq 取
* 改写产物);本端点按模板名取库内 XML 原始脚本,端点路径区隔为 {@code -by-name}。
*
* @param template 模板名(VIEW_TEMPLATE.NAME)
* @param state 注入 item.ISPLACE 的取值,便于驱动分支
*/
@@ -115,89 +96,13 @@ public class ScriptExecuteController {
}
resp.put("template", template);
resp.put("scriptSource", script);
List<Map<String, Object>> commands = runWithFacade("tpl:" + template, script, item);
List<Map<String, Object>> commands = ScriptFacadeRunner.run("tpl:" + template, script, item);
resp.put("commands", commands);
resp.put("commandCount", commands.size());
resp.put("passed", true);
return resp;
}
/**
* 改写后脚本挂回 onEvent 重放链路的执行端点(P4-5)。
*
* <p>转换器在 amis 页面 onEvent 里配置「调本端点,传 templateId/seq/item」;本端点按
* {@code (templateId, seq)} 从改写后脚本库({@link RewrittenScriptStore})取脚本正文,
* 经 facade 执行,返回 amis 事件动作指令数组供前端逐条重放(show/hidden/setValue/setOptions/toast 等)。
*
* <p>请求体:{@code {"templateId":"021e...","seq":2,"item":{"STORE_ID":"X",...}}}<br>
* 返回 :{@code {"commands":[{actionType,componentId,args},...], "passed":true, "item":{...}}}
*
* @param body templateId(落盘目录名)+ seq(脚本序号)+ item(amis 表单当前数据域)
*/
@PostMapping("/api/script/execute-template")
public Map<String, Object> executeTemplateRewritten(@RequestBody Map<String, Object> body) {
Map<String, Object> resp = new LinkedHashMap<>();
String templateId = body.get("templateId") == null ? null : String.valueOf(body.get("templateId"));
if (templateId == null || templateId.isBlank()) {
resp.put("passed", false);
resp.put("error", "缺少 templateId");
return resp;
}
int seq = body.get("seq") instanceof Number n ? n.intValue() : parseSeq(body.get("seq"));
@SuppressWarnings("unchecked")
Map<String, Object> item = body.get("item") instanceof Map
? (Map<String, Object>) body.get("item") : new LinkedHashMap<>();
String script = rewrittenScriptStore.load(templateId, seq);
if (script == null || script.isBlank()) {
// WS-B C1-b:脚本未找到(残余缺脚本/seq 偏差)退化为「无联动」no-op,而非用户可见 ajax 报错。
// 转换期 fail-closed 已尽量不挂缺文件的绑定;此处兜底任何残余,返空 commands → 前端无动作可重放。
resp.put("templateId", templateId);
resp.put("seq", seq);
resp.put("passed", true);
resp.put("commands", List.of());
resp.put("commandCount", 0);
resp.put("note", "改写后脚本未找到,按无联动处理(no-op): templateId=" + templateId + " seq=" + seq);
return resp;
}
// 小修#2:脚本执行前把 item 里枚举列的裸码换成显示串(复刻老系统 grid 行 item 语义),使
// onselectedscript 里 `item['ISPLACE'] == "未归档"` 类显示串比较成立(否则裸码 0 != "未归档"
// → 文件归档等按钮永不点亮)。表名从 item 的 <TABLE>_ID 主键反推;失败静默跳过不影响主路径。
if (enumDisplayResolver != null) {
enumDisplayResolver.enrichItem(null, item);
}
resp.put("templateId", templateId);
resp.put("seq", seq);
try {
List<Map<String, Object>> commands = runWithFacade("rw:" + templateId + ":" + seq, script, item);
resp.put("passed", true);
resp.put("item", item);
resp.put("commands", commands);
resp.put("commandCount", commands.size());
} catch (Exception e) {
resp.put("passed", false);
resp.put("error", e.getMessage());
}
return resp;
}
private static int parseSeq(Object raw) {
try {
return raw == null ? 1 : Integer.parseInt(String.valueOf(raw).trim());
} catch (NumberFormatException e) {
return 1;
}
}
/** 用 facade 动词表执行脚本,返回捕获的 amis 指令。 */
private List<Map<String, Object>> runWithFacade(String key, String script, Map<String, Object> item) {
ScriptFacade facade = new ScriptFacade(item);
Bindings bindings = facade.buildBindings(item);
ScriptingEnginesManager.getScriptingEnginesManager()
.evaluateGroovy(key, script, bindings);
return facade.getCommands();
}
/** 从 VIEW_TEMPLATE 取模板第一段实质脚本(getText 保留换行,见迁移手册 5.3)。 */
private String extractScript(String template) throws Exception {
List<String> xmls = jdbcTemplate.queryForList(

View File

@@ -0,0 +1,100 @@
package com.eip4.platform.metadata.web;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.eip4.platform.metadata.flow.EnumDisplayResolver;
import com.eip4.platform.metadata.script.RewrittenScriptStore;
import com.eip4.platform.metadata.script.ScriptFacadeRunner;
/**
* 改写后脚本挂回 onEvent 重放执行端点(P4-5)——<strong>生产运行时依赖</strong>。
*
* <p>转换器在 amis 页面 onEvent 里配置「调本端点,传 templateId/seq/item」;本端点按
* {@code (templateId, seq)} 从改写后脚本库({@link RewrittenScriptStore})取<em>已落盘、已审</em>
* 的脚本正文,经 facade 执行,返回 amis 事件动作指令数组供前端逐条重放。
*
* <p><strong>P0 安全拆分(2026-06-24 架构评审)</strong>:本控制器只重放<em>脚本库内</em>脚本
* (脚本来源 = S3 改写器落盘产物,非请求体),不接受请求体里的任意脚本,故可随生产 jar 装配。
* 「执行请求体任意 Groovy(RCE)」的开发端点已隔离到 {@code ScriptExecuteController}
* (@Profile 旁路限定,生产不装配)。{@link RewrittenScriptStore} 另对 {@code templateId} 做
* 路径包含校验,防 {@code ../} 穿越读任意 {@code .groovy} 文件。
*/
@RestController
public class ScriptReplayController {
private final RewrittenScriptStore rewrittenScriptStore;
/** 脚本执行前给 item 注入枚举列显示串(复刻老系统 grid 行 item 语义),修 {@code item['ISPLACE']=="未归档"} 类脚本。 */
private final EnumDisplayResolver enumDisplayResolver;
public ScriptReplayController(RewrittenScriptStore rewrittenScriptStore,
EnumDisplayResolver enumDisplayResolver) {
this.rewrittenScriptStore = rewrittenScriptStore;
this.enumDisplayResolver = enumDisplayResolver;
}
/**
* 改写后脚本挂回 onEvent 重放链路的执行端点(P4-5)。
*
* <p>请求体:{@code {"templateId":"021e...","seq":2,"item":{"STORE_ID":"X",...}}}<br>
* 返回 :{@code {"commands":[{actionType,componentId,args},...], "passed":true, "item":{...}}}
*/
@PostMapping("/api/script/execute-template")
public Map<String, Object> executeTemplateRewritten(@RequestBody Map<String, Object> body) {
Map<String, Object> resp = new LinkedHashMap<>();
String templateId = body.get("templateId") == null ? null : String.valueOf(body.get("templateId"));
if (templateId == null || templateId.isBlank()) {
resp.put("passed", false);
resp.put("error", "缺少 templateId");
return resp;
}
int seq = body.get("seq") instanceof Number n ? n.intValue() : parseSeq(body.get("seq"));
@SuppressWarnings("unchecked")
Map<String, Object> item = body.get("item") instanceof Map
? (Map<String, Object>) body.get("item") : new LinkedHashMap<>();
String script = rewrittenScriptStore.load(templateId, seq);
if (script == null || script.isBlank()) {
// WS-B C1-b:脚本未找到(残余缺脚本/seq 偏差)退化为「无联动」no-op,而非用户可见 ajax 报错。
resp.put("templateId", templateId);
resp.put("seq", seq);
resp.put("passed", true);
resp.put("commands", List.of());
resp.put("commandCount", 0);
resp.put("note", "改写后脚本未找到,按无联动处理(no-op): templateId=" + templateId + " seq=" + seq);
return resp;
}
// 执行前把 item 里枚举列的裸码换成显示串(复刻老系统 grid 行 item 语义),使
// onselectedscript 里 `item['ISPLACE'] == "未归档"` 类显示串比较成立。失败静默跳过不影响主路径。
if (enumDisplayResolver != null) {
enumDisplayResolver.enrichItem(null, item);
}
resp.put("templateId", templateId);
resp.put("seq", seq);
try {
List<Map<String, Object>> commands =
ScriptFacadeRunner.run("rw:" + templateId + ":" + seq, script, item);
resp.put("passed", true);
resp.put("item", item);
resp.put("commands", commands);
resp.put("commandCount", commands.size());
} catch (Exception e) {
resp.put("passed", false);
resp.put("error", e.getMessage());
}
return resp;
}
private static int parseSeq(Object raw) {
try {
return raw == null ? 1 : Integer.parseInt(String.valueOf(raw).trim());
} catch (NumberFormatException e) {
return 1;
}
}
}

View File

@@ -59,4 +59,20 @@ class RewrittenScriptStoreTest {
assertNull(store.load("", 1));
assertFalse(store.load("no-such-tid", 9) != null);
}
/** P0:templateId 路径穿越(../)不得读取脚本库根之外的 .groovy 文件,返回 null。 */
@Test
void load_路径穿越templateId拒绝读库外文件(@TempDir Path tmp) throws IOException {
Path root = tmp.resolve("rewritten");
Files.createDirectories(root);
// 在 root 之外(同 tmp 下的兄弟目录)放一个真实可读的脚本目录
Path evil = tmp.resolve("evil");
Files.createDirectories(evil);
Files.writeString(evil.resolve("1.x.groovy"), "showToast(\"pwned\");", StandardCharsets.UTF_8);
RewrittenScriptStore store = new RewrittenScriptStore(root.toString());
// ../evil 解析后落在 root 之外 → 包含校验拒绝 → null(即便目标文件真实存在)
assertNull(store.load("../evil", 1), "穿越出脚本库根必须拒绝");
assertNull(store.load("../../evil", 1));
}
}

View File

@@ -1,169 +1,28 @@
package com.eip4.platform.metadata.web;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.jdbc.core.JdbcTemplate;
import com.eip4.platform.metadata.flow.EnumDisplayResolver;
import com.eip4.platform.metadata.script.RewrittenScriptStore;
/**
* P4-5 单测:改写后脚本挂回执行端点(/api/script/execute-template)。
* 开发/调试脚本执行端点单测(/api/script/execute,执行请求体里的任意脚本)。
*
* <p>构造一个落盘的改写后脚本(templateId/seq 命名 + 头注释块),经端点取出去头执行,
* 断言返回 amis 事件动作指令数组(actionType/componentId/args),是「改写后脚本挂回」取数→
* 执行→指令产出的端到端单测(脚本经保真层引擎真实跑通,非桩)。
* <p>P0 拆分(2026-06-24 架构评审)后,本控制器 {@code @Profile(SecurityProfiles.BYPASS)}
* 仅 dev/local/ci/parity 装配,生产不可达;改写后脚本「生产重放」端点已迁至
* {@link ScriptReplayController}(见 {@code ScriptReplayControllerTest})。
*/
class ScriptExecuteControllerTest {
private ScriptExecuteController controller(Path root) {
return new ScriptExecuteController(mock(JdbcTemplate.class), new RewrittenScriptStore(root.toString()));
}
private void writeScript(Path root, String tid, String fileName, String content) throws IOException {
Path dir = root.resolve(tid);
Files.createDirectories(dir);
Files.writeString(dir.resolve(fileName), content, StandardCharsets.UTF_8);
}
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_取改写脚本执行产出amis指令(@TempDir Path root) throws IOException {
// 福利保险结算单 seq=1:setFieldVisible("BEGINDATE", false) → hidden
writeScript(root, "0d9eac07", "1.FULL_AUTO.groovy",
"// === EIP4 P4 脚本迁移产出 ===\n// seq : 1\n\nsetFieldVisible(\"BEGINDATE\", false);");
ScriptExecuteController c = controller(root);
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "0d9eac07");
body.put("seq", 1);
body.put("item", new LinkedHashMap<>());
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals(1, cmds.size());
assertEquals("hidden", cmds.get(0).get("actionType"));
assertEquals("BEGINDATE", cmds.get(0).get("componentId"));
}
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_服务端语义动词从item求值并联动(@TempDir Path root) throws IOException {
// 办公用品领用申请 seq=2:addSubTableButton + bindField(getFieldValue("STORE_ID"))
writeScript(root, "021e3ba7", "2.FULL_AUTO.groovy",
"// header\naddSubTableButton(\"GOODSDETAIL\", \"SELECT\", 0);\n"
+ "bindField(\"OLD_STORE_ID\",getFieldValue(\"STORE_ID\"));");
ScriptExecuteController c = controller(root);
Map<String, Object> item = new LinkedHashMap<>();
item.put("STORE_ID", "S-99");
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "021e3ba7");
body.put("seq", "2"); // 字符串 seq 也能解析
body.put("item", item);
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals(2, cmds.size());
assertEquals("addSubTableButton", cmds.get(0).get("actionType"));
Map<String, Object> setValue = cmds.get(1);
assertEquals("setValue", setValue.get("actionType"));
assertEquals("OLD_STORE_ID", setValue.get("componentId"));
Map<String, Object> args = (Map<String, Object>) setValue.get("args");
assertEquals("S-99", args.get("value")); // getFieldValue 从 item 求值闭环
}
/** 缺 templateId 是真错 → passed=false + error(保留)。 */
@Test
void executeTemplateRewritten_缺templateId时passed为false(@TempDir Path root) {
ScriptExecuteController c = controller(root);
Map<String, Object> noTid = new LinkedHashMap<>();
Map<String, Object> r1 = c.executeTemplateRewritten(noTid);
assertEquals(Boolean.FALSE, r1.get("passed"));
assertNotNull(r1.get("error"));
assertTrue(((String) r1.get("error")).contains("templateId"));
}
/** WS-B C1-b:脚本未找到(残余缺脚本/seq 偏差)退化为 no-op(passed=true + 空 commands),不报 ajax 错。 */
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_脚本未找到时退化为noop(@TempDir Path root) {
ScriptExecuteController c = controller(root);
Map<String, Object> missing = new LinkedHashMap<>();
missing.put("templateId", "no-such");
missing.put("seq", 1);
Map<String, Object> r2 = c.executeTemplateRewritten(missing);
assertEquals(Boolean.TRUE, r2.get("passed")); // no-op,非用户可见报错
assertNull(r2.get("error")); // 不再返 error
List<Map<String, Object>> cmds = (List<Map<String, Object>>) r2.get("commands");
assertTrue(cmds.isEmpty()); // 空 commands → 前端无动作可重放
assertEquals(0, r2.get("commandCount"));
}
/**
* 小修#2:执行前 item 枚举裸码 → 显示串,使 onselectedscript 里 {@code item['ISPLACE'] == "未归档"}
* 成立 → 触发 enableButton("文件归档", true)。复刻新闻 ddb75614 文件归档永不点亮根因的修复闭环。
*/
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_枚举显示值注入使按钮点亮(@TempDir Path root) throws IOException {
// 复刻新闻 seq1 文件归档分支:item['ISPLACE'] 是显示串时点亮文件归档
writeScript(root, "ddb75614", "1.NO_S3.groovy",
"if (item['ISPLACE'] == \"未归档\") enableButton(\"文件归档\", true);");
// 桩 jdbc:ISPLACE→SYS_FILINGUP_STATUS,code 0→未归档
JdbcTemplate jdbc = mock(JdbcTemplate.class);
org.mockito.Mockito.lenient().when(jdbc.queryForList(
org.mockito.ArgumentMatchers.contains("sys_entityattribute"),
org.mockito.ArgumentMatchers.eq("OA_NEWSMANAGE")))
.thenReturn(List.of(Map.of("col", "ISPLACE", "etype", "SYS_FILINGUP_STATUS")));
org.mockito.Mockito.lenient().when(jdbc.queryForList(
org.mockito.ArgumentMatchers.contains("sys_enumerate"),
org.mockito.ArgumentMatchers.eq("SYS_FILINGUP_STATUS")))
.thenReturn(List.of(Map.of("codevalue", 0, "codedes", "未归档")));
ScriptExecuteController c = new ScriptExecuteController(
jdbc, new RewrittenScriptStore(root.toString()), new EnumDisplayResolver(jdbc));
Map<String, Object> item = new LinkedHashMap<>();
item.put("OA_NEWSMANAGE_ID", "row-1");
item.put("ISPLACE", 0); // 裸码(_SEARCH 合成流平展的真实形态)
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "ddb75614");
body.put("seq", 1);
body.put("item", item);
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals(1, cmds.size(), "ISPLACE 富化为「未归档」→ 文件归档点亮 enable 指令");
assertEquals("文件归档", cmds.get(0).get("componentId"));
assertEquals("enabled", cmds.get(0).get("actionType"));
}
@SuppressWarnings("unchecked")
@Test
void execute_直接执行脚本仍可用(@TempDir Path root) {
ScriptExecuteController c = controller(root);
void execute_直接执行脚本仍可用() {
ScriptExecuteController c = new ScriptExecuteController(mock(JdbcTemplate.class));
Map<String, Object> body = new LinkedHashMap<>();
body.put("script", "showToast(\"ok\");");
body.put("item", new LinkedHashMap<>());
@@ -172,4 +31,12 @@ class ScriptExecuteControllerTest {
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals("toast", cmds.get(0).get("actionType"));
}
@Test
void execute_缺script时passed为false() {
ScriptExecuteController c = new ScriptExecuteController(mock(JdbcTemplate.class));
Map<String, Object> resp = c.execute(new LinkedHashMap<>());
assertEquals(Boolean.FALSE, resp.get("passed"));
assertEquals("缺少 script", resp.get("error"));
}
}

View File

@@ -0,0 +1,183 @@
package com.eip4.platform.metadata.web;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.jdbc.core.JdbcTemplate;
import com.eip4.platform.metadata.flow.EnumDisplayResolver;
import com.eip4.platform.metadata.script.RewrittenScriptStore;
/**
* P4-5 单测:改写后脚本挂回执行端点(/api/script/execute-template),P0 拆分后落在生产可装配的
* {@link ScriptReplayController}(脚本只取自脚本库内已审产物,非请求体,故随生产 jar 装配)。
*
* <p>构造一个落盘的改写后脚本(templateId/seq 命名 + 头注释块),经端点取出去头执行,
* 断言返回 amis 事件动作指令数组(脚本经保真层引擎真实跑通,非桩)。
*/
class ScriptReplayControllerTest {
private ScriptReplayController controller(Path root) {
return new ScriptReplayController(new RewrittenScriptStore(root.toString()),
new EnumDisplayResolver(mock(JdbcTemplate.class)));
}
private void writeScript(Path root, String tid, String fileName, String content) throws IOException {
Path dir = root.resolve(tid);
Files.createDirectories(dir);
Files.writeString(dir.resolve(fileName), content, StandardCharsets.UTF_8);
}
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_取改写脚本执行产出amis指令(@TempDir Path root) throws IOException {
writeScript(root, "0d9eac07", "1.FULL_AUTO.groovy",
"// === EIP4 P4 脚本迁移产出 ===\n// seq : 1\n\nsetFieldVisible(\"BEGINDATE\", false);");
ScriptReplayController c = controller(root);
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "0d9eac07");
body.put("seq", 1);
body.put("item", new LinkedHashMap<>());
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals(1, cmds.size());
assertEquals("hidden", cmds.get(0).get("actionType"));
assertEquals("BEGINDATE", cmds.get(0).get("componentId"));
}
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_服务端语义动词从item求值并联动(@TempDir Path root) throws IOException {
writeScript(root, "021e3ba7", "2.FULL_AUTO.groovy",
"// header\naddSubTableButton(\"GOODSDETAIL\", \"SELECT\", 0);\n"
+ "bindField(\"OLD_STORE_ID\",getFieldValue(\"STORE_ID\"));");
ScriptReplayController c = controller(root);
Map<String, Object> item = new LinkedHashMap<>();
item.put("STORE_ID", "S-99");
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "021e3ba7");
body.put("seq", "2"); // 字符串 seq 也能解析
body.put("item", item);
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals(2, cmds.size());
assertEquals("addSubTableButton", cmds.get(0).get("actionType"));
Map<String, Object> setValue = cmds.get(1);
assertEquals("setValue", setValue.get("actionType"));
assertEquals("OLD_STORE_ID", setValue.get("componentId"));
Map<String, Object> args = (Map<String, Object>) setValue.get("args");
assertEquals("S-99", args.get("value")); // getFieldValue 从 item 求值闭环
}
/** 缺 templateId 是真错 → passed=false + error(保留)。 */
@Test
void executeTemplateRewritten_缺templateId时passed为false(@TempDir Path root) {
ScriptReplayController c = controller(root);
Map<String, Object> noTid = new LinkedHashMap<>();
Map<String, Object> r1 = c.executeTemplateRewritten(noTid);
assertEquals(Boolean.FALSE, r1.get("passed"));
assertNotNull(r1.get("error"));
assertTrue(((String) r1.get("error")).contains("templateId"));
}
/** WS-B C1-b:脚本未找到退化为 no-op(passed=true + 空 commands),不报 ajax 错。 */
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_脚本未找到时退化为noop(@TempDir Path root) {
ScriptReplayController c = controller(root);
Map<String, Object> missing = new LinkedHashMap<>();
missing.put("templateId", "no-such");
missing.put("seq", 1);
Map<String, Object> r2 = c.executeTemplateRewritten(missing);
assertEquals(Boolean.TRUE, r2.get("passed"));
assertNull(r2.get("error"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) r2.get("commands");
assertTrue(cmds.isEmpty());
assertEquals(0, r2.get("commandCount"));
}
/**
* P0:路径穿越的 templateId 不得读取脚本库外文件 → 退化 no-op(RewrittenScriptStore 包含校验)。
*/
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_路径穿越templateId退化noop(@TempDir Path tmp) throws IOException {
Path root = tmp.resolve("rewritten");
Files.createDirectories(root);
// 在 root 之外落一个恶意脚本目录
Path outsideDir = tmp.resolve("evil");
Files.createDirectories(outsideDir);
Files.writeString(outsideDir.resolve("1.x.groovy"), "showToast(\"pwned\");", StandardCharsets.UTF_8);
ScriptReplayController c = new ScriptReplayController(
new RewrittenScriptStore(root.toString()), new EnumDisplayResolver(mock(JdbcTemplate.class)));
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "../evil"); // 试图穿越出脚本库根
body.put("seq", 1);
body.put("item", new LinkedHashMap<>());
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed")); // no-op(脚本未找到)
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertTrue(cmds.isEmpty(), "穿越 templateId 必须读不到库外脚本,不得执行");
}
/**
* 执行前 item 枚举裸码 → 显示串,使 onselectedscript 里 {@code item['ISPLACE'] == "未归档"} 成立。
*/
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_枚举显示值注入使按钮点亮(@TempDir Path root) throws IOException {
writeScript(root, "ddb75614", "1.NO_S3.groovy",
"if (item['ISPLACE'] == \"未归档\") enableButton(\"文件归档\", true);");
JdbcTemplate jdbc = mock(JdbcTemplate.class);
org.mockito.Mockito.lenient().when(jdbc.queryForList(
org.mockito.ArgumentMatchers.contains("sys_entityattribute"),
org.mockito.ArgumentMatchers.eq("OA_NEWSMANAGE")))
.thenReturn(List.of(Map.of("col", "ISPLACE", "etype", "SYS_FILINGUP_STATUS")));
org.mockito.Mockito.lenient().when(jdbc.queryForList(
org.mockito.ArgumentMatchers.contains("sys_enumerate"),
org.mockito.ArgumentMatchers.eq("SYS_FILINGUP_STATUS")))
.thenReturn(List.of(Map.of("codevalue", 0, "codedes", "未归档")));
ScriptReplayController c = new ScriptReplayController(
new RewrittenScriptStore(root.toString()), new EnumDisplayResolver(jdbc));
Map<String, Object> item = new LinkedHashMap<>();
item.put("OA_NEWSMANAGE_ID", "row-1");
item.put("ISPLACE", 0); // 裸码
Map<String, Object> body = new LinkedHashMap<>();
body.put("templateId", "ddb75614");
body.put("seq", 1);
body.put("item", item);
Map<String, Object> resp = c.executeTemplateRewritten(body);
assertEquals(Boolean.TRUE, resp.get("passed"));
List<Map<String, Object>> cmds = (List<Map<String, Object>>) resp.get("commands");
assertEquals(1, cmds.size(), "ISPLACE 富化为「未归档」→ 文件归档点亮 enable 指令");
assertEquals("文件归档", cmds.get(0).get("componentId"));
assertEquals("enabled", cmds.get(0).get("actionType"));
}
}