fix(P0②/P1⑥): 对抗审查收口 4 major + minor

对抗审查 workflow(3 lens)揪出并修复:
- [major] AlterTableSqlGuard 移除 ALTER COLUMN TYPE:静态守卫拿不到旧尺寸,无法
  保证扩长(varchar(1)/numeric(1,0) 缩短会截断/溢出存量数据),一律拒;扩长须由
  MetaController 比对旧列长度后再生成
- [major] addAttributes 校验-写分离 + @Transactional + ALTER 失败抛异常:
  杜绝「元数据写了但物理表没加」孤儿(PG 事务性 DDL 一起回滚)
- [major] createEntity 检查 executeCreateSql 返回值 + @Transactional:引擎拒建表
  不再静默成功
- [major] AiToolRegistry isLocalEnv/isProductionEnv 改 URI host 精确解析:防
  http://127.0.0.1.evil.com / localhost.evil.com 伪本地前缀绕过安全门
- [minor] deleteStandard templateId trim + 菜单查询限 isactive=1(两表口径一致,
  不连带删历史同 templateId 菜单/授权)
- [minor] publish roleIds 只接 String 元素(滤 null/非串);warning 改依据
  roleIds.isEmpty()(重复发布不误报)
- [minor] menuauth grantToRoles 改 INSERT...WHERE NOT EXISTS(sys_role_menu 无
  唯一约束,ON CONFLICT 不去重,重复发布会插重复行)+ columnSqlType 空 refTable 抛错

全单测绿(Failures=0)、p0-alter/p1-6 真库验收绿(含幂等+负控)、浏览器 e2e 6/6 绿

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-21 14:15:29 +08:00
parent ccbed82498
commit 46ff5c5779
9 changed files with 136 additions and 61 deletions

View File

@@ -153,17 +153,40 @@ public final class AiToolRegistry {
} }
private static boolean isLocalEnv(String targetEnv) { private static boolean isLocalEnv(String targetEnv) {
return targetEnv.isBlank() if (targetEnv.isBlank() || targetEnv.equals("local") || targetEnv.equals("dev")) {
|| targetEnv.equals("local") return true;
|| targetEnv.equals("dev") }
|| targetEnv.startsWith("localhost") // 解析 host 精确比对,而非 startsWith 前缀:防 http://127.0.0.1.evil.com / http://localhost.evil.com
|| targetEnv.startsWith("127.0.0.1") // 这类「伪本地」域名绕过(对抗审查 major)。与下游 AiLocalReleaseExecutor.safeLocalBase 同口径。
|| targetEnv.startsWith("http://localhost") String host = hostOf(targetEnv);
|| targetEnv.startsWith("http://127.0.0.1"); return host.equals("localhost") || host.equals("127.0.0.1")
|| host.equals("::1") || host.equals("0:0:0:0:0:0:0:1");
} }
private static boolean isProductionEnv(String targetEnv) { private static boolean isProductionEnv(String targetEnv) {
return targetEnv.equals("prod") || targetEnv.equals("production") || targetEnv.contains("prod"); if (targetEnv.equals("prod") || targetEnv.equals("production")) {
return true;
}
// 只看 host 段含 prod,不再对整 URL/path contains('prod')(避免 http://localhost:8084/prod-test 误判)
return hostOf(targetEnv).contains("prod");
}
/** 从 targetEnv(URL 或裸 host[:port])解析出小写 host(去 IPv6 方括号);解析失败返空串。 */
private static String hostOf(String targetEnv) {
try {
String s = targetEnv.contains("://") ? targetEnv : "http://" + targetEnv;
String host = java.net.URI.create(s).getHost();
if (host == null) {
return "";
}
host = host.toLowerCase(Locale.ROOT);
if (host.startsWith("[") && host.endsWith("]")) {
host = host.substring(1, host.length() - 1);
}
return host;
} catch (RuntimeException e) {
return "";
}
} }
private static String text(String value) { private static String text(String value) {

View File

@@ -17,12 +17,15 @@ import java.util.regex.Pattern;
* <p>受控形态(标识符大小写敏感,必须大写,匹配引擎建表正则;类型 token 小写,匹配 * <p>受控形态(标识符大小写敏感,必须大写,匹配引擎建表正则;类型 token 小写,匹配
* {@code MetaController.appendColumnDdl} 的输出): * {@code MetaController.appendColumnDdl} 的输出):
* <ul> * <ul>
* <li>{@code ALTER TABLE <T> ADD COLUMN <C> <type>} — 加列(可带 REFERENCES 引用)</li> * <li>{@code ALTER TABLE <T> ADD COLUMN <C> <type>} — 加列(可带 REFERENCES 引用,恒可空)</li>
* <li>{@code ALTER TABLE <T> ALTER COLUMN <C> TYPE <varchar(n)|numeric(p,s)>} — 同族扩长</li>
* <li>{@code ALTER TABLE <T> ALTER COLUMN <C> DROP NOT NULL} — 改可空</li> * <li>{@code ALTER TABLE <T> ALTER COLUMN <C> DROP NOT NULL} — 改可空</li>
* </ul> * </ul>
* 其余(DROP COLUMN / RENAME / SET NOT NULL / 跨族类型转换 / 多语句 / 子查询 / 注释 / 小写绕过) * 其余(DROP COLUMN / RENAME / SET NOT NULL / ALTER COLUMN TYPE / 多语句 / 子查询 / 注释 / 小写绕过)
* 一律抛 {@link IllegalArgumentException}。 * 一律抛 {@link IllegalArgumentException}。
*
* <p><b>为何不放行 ALTER COLUMN TYPE「扩长」</b>:纯静态守卫拿不到旧列定义,无法判断新尺寸是否 ≥ 旧尺寸,
* 因此无法区分「扩长」与「缩短」——后者会截断存量数据 / 整表报错。故 TYPE 变更一律拒绝;若将来需扩长,
* 须在 {@code MetaController} 层读旧列长度/精度后断言 new ≥ old 再生成 DDL,而非放给本守卫。
*/ */
public final class AlterTableSqlGuard { public final class AlterTableSqlGuard {
@@ -41,14 +44,8 @@ public final class AlterTableSqlGuard {
+ "|bigint" + "|bigint"
+ "|character\\(36\\)(?: REFERENCES " + TABLE + ")?)"; + "|character\\(36\\)(?: REFERENCES " + TABLE + ")?)";
/** 扩长只允许同族(varchar 改宽 / numeric 改精度),不允许跨族(varchar→int 会丢数据)。 */
private static final String WIDEN_TYPE =
"(?:character varying\\(\\d{1,4}\\)|numeric\\(\\d{1,2},\\d{1,2}\\))";
private static final Pattern ADD_COLUMN = Pattern.compile( private static final Pattern ADD_COLUMN = Pattern.compile(
"ALTER TABLE (" + TABLE + ") ADD COLUMN (" + COLUMN + ") " + ADD_TYPE); "ALTER TABLE (" + TABLE + ") ADD COLUMN (" + COLUMN + ") " + ADD_TYPE);
private static final Pattern ALTER_TYPE = Pattern.compile(
"ALTER TABLE (" + TABLE + ") ALTER COLUMN (" + COLUMN + ") TYPE " + WIDEN_TYPE);
private static final Pattern DROP_NOT_NULL = Pattern.compile( private static final Pattern DROP_NOT_NULL = Pattern.compile(
"ALTER TABLE (" + TABLE + ") ALTER COLUMN (" + COLUMN + ") DROP NOT NULL"); "ALTER TABLE (" + TABLE + ") ALTER COLUMN (" + COLUMN + ") DROP NOT NULL");
@@ -60,6 +57,7 @@ public final class AlterTableSqlGuard {
"--", "/*", "*/", " USING ", "(SELECT", " SELECT ", "--", "/*", "*/", " USING ", "(SELECT", " SELECT ",
" DROP COLUMN", " RENAME ", " SET NOT NULL", " SET DEFAULT", " DROP COLUMN", " RENAME ", " SET NOT NULL", " SET DEFAULT",
" DROP TABLE", " DROP CONSTRAINT", " ADD CONSTRAINT", " DROP TABLE", " DROP CONSTRAINT", " ADD CONSTRAINT",
" TYPE ", // ALTER COLUMN TYPE「扩长/缩短」静态守卫无法判尺寸,一律拒(见类注释)
}; };
/** /**
@@ -94,13 +92,12 @@ public final class AlterTableSqlGuard {
throw new IllegalArgumentException("ALTER 含禁止操作 [" + bad.trim() + "]: " + sql); throw new IllegalArgumentException("ALTER 含禁止操作 [" + bad.trim() + "]: " + sql);
} }
} }
// 必须精确匹配三种受控形态之一(整串 matches,标识符大小写敏感) // 必须精确匹配两种受控形态之一(整串 matches,标识符大小写敏感)
if (ADD_COLUMN.matcher(s).matches() if (ADD_COLUMN.matcher(s).matches()
|| ALTER_TYPE.matcher(s).matches()
|| DROP_NOT_NULL.matcher(s).matches()) { || DROP_NOT_NULL.matcher(s).matches()) {
return s; return s;
} }
throw new IllegalArgumentException( throw new IllegalArgumentException(
"非受控的 ALTER 形态(只允许 加列 / 同族扩长 / 改可空): " + sql); "非受控的 ALTER 形态(只允许 加列 / 改可空): " + sql);
} }
} }

View File

@@ -39,14 +39,18 @@ class AlterTableSqlGuardTest {
"ALTER TABLE EIP4_ORDER ADD COLUMN CUSTOMERID character(36) REFERENCES EIP4_CUSTOMER")); "ALTER TABLE EIP4_ORDER ADD COLUMN CUSTOMERID character(36) REFERENCES EIP4_CUSTOMER"));
} }
// ---------- 允许:同族扩长 ---------- // ---------- 拒绝:ALTER COLUMN TYPE(静态守卫无法判尺寸,一律拒) ----------
@Test @Test
@DisplayName("扩长:ALTER COLUMN ... TYPE varchar(n) / numeric(p,s) 通过") @DisplayName("拒绝:ALTER COLUMN TYPE —— 拿不到旧尺寸无法保证扩长,缩短会截断数据,一律拒(对抗审查 major)")
void widenTypeAllowed() { void rejectTypeChange() {
assertEquals("ALTER TABLE EIP4_X ALTER COLUMN NAME TYPE character varying(400)", // 即便看似「扩长」也拒(无法保证 new>=old)
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN NAME TYPE character varying(400)")); assertThrows(IllegalArgumentException.class,
assertEquals("ALTER TABLE EIP4_X ALTER COLUMN AMOUNT TYPE numeric(20,8)", () -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN NAME TYPE character varying(400)"));
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN AMOUNT TYPE numeric(20,8)")); // 「缩短」反例:varchar(1) 截断存量;numeric(1,0) 溢出
assertThrows(IllegalArgumentException.class,
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN NAME TYPE character varying(1)"));
assertThrows(IllegalArgumentException.class,
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN AMT TYPE numeric(1,0)"));
} }
// ---------- 允许:改可空 ---------- // ---------- 允许:改可空 ----------

View File

@@ -74,25 +74,30 @@ public class MenuRegistrar {
/** /**
* P1⑥:给菜单授权角色(写 sys_role_menu)。发布后若不授权,非超管(无 sys_role_menu 行)看不见新功能。 * P1⑥:给菜单授权角色(写 sys_role_menu)。发布后若不授权,非超管(无 sys_role_menu 行)看不见新功能。
* 复用 {@code AdminWriteController.setRoleMenus} 的 {@code (roleid,menuid) ON CONFLICT DO NOTHING} 幂等范式。 *
* <p><b>幂等实现</b>:{@code sys_role_menu} 无唯一约束/索引(实测),故 {@code ON CONFLICT DO NOTHING}
* 不去重——重复发布会插重复行。这里改用 {@code INSERT ... SELECT ... WHERE NOT EXISTS} 保证幂等
* (已存在则插 0 行)。返回值只计真正新增的授权数。
* *
* @param menuId 菜单 id * @param menuId 菜单 id
* @param roleIds 授权角色 id 列表 * @param roleIds 授权角色 id 列表
* @param operator 操作人(审计) * @param operator 操作人(审计)
* @return 实际写入(授权)的角色数;menuId/roleIds 为空则 0(不写库) * @return 实际新增(授权)的角色数;menuId/roleIds 为空则 0(不写库)
*/ */
public int grantToRoles(String menuId, List<String> roleIds, String operator) { public int grantToRoles(String menuId, List<String> roleIds, String operator) {
if (menuId == null || menuId.isBlank() || roleIds == null || roleIds.isEmpty()) { if (menuId == null || menuId.isBlank() || roleIds == null || roleIds.isEmpty()) {
return 0; return 0;
} }
String mid = menuId.trim();
int granted = 0; int granted = 0;
for (String roleId : roleIds) { for (String roleId : roleIds) {
if (roleId == null || roleId.isBlank()) { if (roleId == null || roleId.isBlank()) {
continue; continue;
} }
granted += jdbcTemplate.update( granted += jdbcTemplate.update(
"INSERT INTO sys_role_menu(roleid, menuid) VALUES(?,?) ON CONFLICT DO NOTHING", "INSERT INTO sys_role_menu(roleid, menuid) SELECT ?, ?"
roleId.trim(), menuId.trim()); + " WHERE NOT EXISTS (SELECT 1 FROM sys_role_menu WHERE TRIM(roleid)=? AND TRIM(menuid)=?)",
roleId.trim(), mid, roleId.trim(), mid);
} }
return granted; return granted;
} }

View File

@@ -396,13 +396,15 @@ public class DesignFeatureController {
data.put("menuId", menuId); data.put("menuId", menuId);
// P1⑥:可选 roleIds 给菜单授权(写 sys_role_menu);缺省则新功能仅超管可见,返 warning。 // P1⑥:可选 roleIds 给菜单授权(写 sys_role_menu);缺省则新功能仅超管可见,返 warning。
@SuppressWarnings("unchecked") // 只接 String 元素(滤掉 null/非字符串,避免 String.valueOf 把 null→"null" 写脏授权);
// warning 依据「是否传了 roleIds」而非「本次新增数」——否则重复发布(已授权→新增0)会误报。
List<String> roleIds = body.get("roleIds") instanceof List<?> rs List<String> roleIds = body.get("roleIds") instanceof List<?> rs
? rs.stream().map(String::valueOf).filter(s -> !s.isBlank()).toList() ? rs.stream().filter(String.class::isInstance).map(String.class::cast)
.map(String::trim).filter(s -> !s.isEmpty()).toList()
: List.of(); : List.of();
int grantedRoles = publishOrchestrator.grantMenuRoles(menuId, roleIds, operator); int grantedRoles = publishOrchestrator.grantMenuRoles(menuId, roleIds, operator);
data.put("grantedRoleCount", grantedRoles); data.put("grantedRoleCount", grantedRoles);
if (grantedRoles == 0) { if (roleIds.isEmpty()) {
data.put("menuVisibilityWarning", data.put("menuVisibilityWarning",
"未指定 roleIds,新功能菜单仅超管可见;请到「角色菜单授权」为业务角色授权"); "未指定 roleIds,新功能菜单仅超管可见;请到「角色菜单授权」为业务角色授权");
} }

View File

@@ -71,6 +71,7 @@ public class MetaController {
@Operation(summary = "创建实体:写入 SYS_ENTITY/SYS_ENTITYATTRIBUTE 元数据并动态创建物理表") @Operation(summary = "创建实体:写入 SYS_ENTITY/SYS_ENTITYATTRIBUTE 元数据并动态创建物理表")
@PostMapping("/api/meta/entity") @PostMapping("/api/meta/entity")
@org.springframework.transaction.annotation.Transactional
public Map<String, Object> createEntity(@RequestBody Map<String, Object> req) { public Map<String, Object> createEntity(@RequestBody Map<String, Object> req) {
Properties ctx = UserSession.getAdmin(); Properties ctx = UserSession.getAdmin();
String table = String.valueOf(req.get("tablename")).toUpperCase(); String table = String.valueOf(req.get("tablename")).toUpperCase();
@@ -169,7 +170,13 @@ public class MetaController {
// 动态建表前先清刚保存实体/属性带来的 POInfo 缓存,保证后续读写立即拿到新字段。 // 动态建表前先清刚保存实体/属性带来的 POInfo 缓存,保证后续读写立即拿到新字段。
cacheInvalidator.evictByEntityId(entityId, table); cacheInvalidator.evictByEntityId(entityId, table);
String ddl = createTableDdl(table, created, refTargets); String ddl = createTableDdl(table, created, refTargets);
dataDicService.executeCreateSql(ddl); // 检查 DDL 返回值:引擎判非法时返回非空错误串。@Transactional + 抛异常 → 回滚已写的实体/属性
// 元数据(对抗审查 major:否则元数据建好但物理表不存在,运行时 list 500)。
String ddlErr = dataDicService.executeCreateSql(ddl);
if (ddlErr != null) {
throw new org.springframework.web.server.ResponseStatusException(
org.springframework.http.HttpStatus.BAD_REQUEST, "建表失败: " + ddlErr);
}
// P1-5:建表后按元数据补索引(外键 uuid 列 + UPDATETIME),引擎只建表不建索引 // P1-5:建表后按元数据补索引(外键 uuid 列 + UPDATETIME),引擎只建表不建索引
List<String> indexes = indexEnhancer.enhanceForNewEntity(table); List<String> indexes = indexEnhancer.enhanceForNewEntity(table);
@@ -277,6 +284,7 @@ public class MetaController {
@Operation(summary = "为已建实体加列(ALTER ADD COLUMN):写 SYS_ENTITYATTRIBUTE 元数据 + 受控 ALTER 物理表(只加列,恒可空)") @Operation(summary = "为已建实体加列(ALTER ADD COLUMN):写 SYS_ENTITYATTRIBUTE 元数据 + 受控 ALTER 物理表(只加列,恒可空)")
@PostMapping("/api/meta/entity/{table}/attributes") @PostMapping("/api/meta/entity/{table}/attributes")
@org.springframework.transaction.annotation.Transactional
public Map<String, Object> addAttributes(@PathVariable String table, @RequestBody Map<String, Object> req) { public Map<String, Object> addAttributes(@PathVariable String table, @RequestBody Map<String, Object> req) {
Properties ctx = UserSession.getAdmin(); Properties ctx = UserSession.getAdmin();
String t = table.toUpperCase(); String t = table.toUpperCase();
@@ -293,11 +301,8 @@ public class MetaController {
if (attrs == null || attrs.isEmpty()) { if (attrs == null || attrs.isEmpty()) {
return err("attributes 为空"); return err("attributes 为空");
} }
// saveAttr 载体:沿用 createEntity 的 SYS_USERGROUP.NAME 属性行模板
Entity tplEnt = (Entity) dataDicService.getSYSEntityByTableName("SYS_USERGROUP");
Map<String, Object> attrTpl = loadAttrTemplate(idOf(tplEnt));
List<String> added = new ArrayList<>(); // ── 校验全部列(不写库)── 任一不合法原子返回 err;此时尚无写入,无回滚问题。
for (Map<String, Object> a : attrs) { for (Map<String, Object> a : attrs) {
String col = String.valueOf(a.get("column")).toUpperCase(); String col = String.valueOf(a.get("column")).toUpperCase();
if (!col.matches("[A-Z][A-Z0-9_]{1,60}")) { if (!col.matches("[A-Z][A-Z0-9_]{1,60}")) {
@@ -309,16 +314,28 @@ public class MetaController {
if (exists != null && exists > 0) { if (exists != null && exists > 0) {
return err("字段已存在: " + col); return err("字段已存在: " + col);
} }
String type = String.valueOf(a.getOrDefault("type", "string")); if ("reference".equals(String.valueOf(a.getOrDefault("type", "string")))) {
String display = String.valueOf(a.getOrDefault("display", col));
// ALTER 加列一律可空:对有数据的表加 NOT NULL 列会失败,故忽略 mandatory。
String ddl;
if ("reference".equals(type)) {
String refTable = a.get("referenceTable") == null String refTable = a.get("referenceTable") == null
? null : String.valueOf(a.get("referenceTable")).toUpperCase(); ? null : String.valueOf(a.get("referenceTable")).toUpperCase();
if (refTable == null || dataDicService.getSYSEntityByTableName(refTable) == null) { if (refTable == null || dataDicService.getSYSEntityByTableName(refTable) == null) {
return err("引用目标实体不存在: " + refTable); return err("引用目标实体不存在: " + refTable);
} }
}
}
// ── 写库 + 受控 ALTER ── @Transactional + PG 事务性 DDL:任一列 ALTER 失败抛异常 → 整批
// (元数据 saveAttr + 已执行的 ALTER)回滚,杜绝「元数据写了但物理表没加」的孤儿(对抗审查 major)。
Entity tplEnt = (Entity) dataDicService.getSYSEntityByTableName("SYS_USERGROUP");
Map<String, Object> attrTpl = loadAttrTemplate(idOf(tplEnt));
List<String> added = new ArrayList<>();
for (Map<String, Object> a : attrs) {
String col = String.valueOf(a.get("column")).toUpperCase();
String type = String.valueOf(a.getOrDefault("type", "string"));
String display = String.valueOf(a.getOrDefault("display", col));
// ALTER 加列一律可空:对有数据的表加 NOT NULL 列会失败,故忽略 mandatory。
String ddl;
if ("reference".equals(type)) {
String refTable = String.valueOf(a.get("referenceTable")).toUpperCase();
String referenceId = findOrCreateReference(refTable, col, ctx); String referenceId = findOrCreateReference(refTable, col, ctx);
saveAttr(attrTpl, entityId, col, display, referenceId, 36, false, false, ctx); saveAttr(attrTpl, entityId, col, display, referenceId, 36, false, false, ctx);
ddl = alterAddColumnDdl(t, col, referenceId, 36, refTable); ddl = alterAddColumnDdl(t, col, referenceId, 36, refTable);
@@ -336,10 +353,11 @@ public class MetaController {
saveAttr(attrTpl, entityId, col, display, ref, len, false, false, ctx); saveAttr(attrTpl, entityId, col, display, ref, len, false, false, ctx);
ddl = alterAddColumnDdl(t, col, ref, len, null); ddl = alterAddColumnDdl(t, col, ref, len, null);
} }
// 受控 ALTER:经 AlterTableSqlGuard 白名单(defense-in-depth,executeAlterSql 内也再校验) // 受控 ALTER:经 AlterTableSqlGuard 白名单(defense-in-depth)。失败抛异常 → 事务回滚。
String alterErr = dataDicService.executeAlterSql(ddl); String alterErr = dataDicService.executeAlterSql(ddl);
if (alterErr != null) { if (alterErr != null) {
return err("加列失败[" + col + "]: " + alterErr); throw new org.springframework.web.server.ResponseStatusException(
org.springframework.http.HttpStatus.BAD_REQUEST, "加列失败[" + col + "]: " + alterErr);
} }
added.add(col); added.add(col);
} }
@@ -555,8 +573,11 @@ public class MetaController {
} else if ("CHAR".equals(ref)) { } else if ("CHAR".equals(ref)) {
return "character(36)"; return "character(36)";
} }
// 引用列:ref=SYS_REFERENCE_ID(uuid),外键指向 refTable // 引用列:ref=SYS_REFERENCE_ID(uuid),外键指向 refTable(不可为空,否则产无效 DDL)
return "character(36) REFERENCES " + (refTable != null ? refTable : ""); if (refTable == null || refTable.isBlank()) {
throw new IllegalStateException("引用列缺目标表,无法生成 ALTER: ref=" + ref);
}
return "character(36) REFERENCES " + refTable;
} }
private static int positiveInt(Object value, int defaultValue) { private static int positiveInt(Object value, int defaultValue) {

View File

@@ -350,22 +350,26 @@ public class PageSchemaController {
public ResponseEntity<Map<String, Object>> deleteStandard(@PathVariable String templateId) { public ResponseEntity<Map<String, Object>> deleteStandard(@PathVariable String templateId) {
requireAdmin(); requireAdmin();
String operator = currentUserId(); String operator = currentUserId();
// 1. 关联菜单(view_templateid=该页),清角色授权 + 软删菜单(对称 publish 的菜单注册/授权) // templateId 统一 trim:sys_page_schema 用精确 template_id=?,sys_menu 用 TRIM(view_templateid)=?,
// 两表对 templateId 的口径保持一致,避免一表命中另一表不命中的半删(对抗审查 minor)。
String tpl = templateId == null ? "" : templateId.trim();
// 1. 关联菜单(只取 active),清角色授权 + 软删菜单(对称 publish 的菜单注册/授权)。
// 限 isactive=1 避免连带删历史已停用的同 templateId 菜单及其授权(对抗审查 minor)。
List<String> menuIds = jdbcTemplate.queryForList( List<String> menuIds = jdbcTemplate.queryForList(
"SELECT sys_menu_id FROM sys_menu WHERE TRIM(view_templateid)=?", String.class, templateId); "SELECT sys_menu_id FROM sys_menu WHERE TRIM(view_templateid)=? AND isactive=1", String.class, tpl);
int roleMenu = 0; int roleMenu = 0;
for (String mid : menuIds) { for (String mid : menuIds) {
roleMenu += jdbcTemplate.update("DELETE FROM sys_role_menu WHERE TRIM(menuid)=?", mid.trim()); roleMenu += jdbcTemplate.update("DELETE FROM sys_role_menu WHERE TRIM(menuid)=?", mid.trim());
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
int menus = jdbcTemplate.update( int menus = jdbcTemplate.update(
"UPDATE sys_menu SET isactive=0, updatetime=?, updateby=? WHERE TRIM(view_templateid)=?", "UPDATE sys_menu SET isactive=0, updatetime=?, updateby=? WHERE TRIM(view_templateid)=? AND isactive=1",
now, operator, templateId); now, operator, tpl);
// 2. 删标准层(收口 PageSchemaWriter,不裸 JDBC) + overlay // 2. 删标准层(收口 PageSchemaWriter,不裸 JDBC) + overlay
int standard = pageSchemaWriter.deleteStandard(templateId, operator); int standard = pageSchemaWriter.deleteStandard(tpl, operator);
int overlay = 0; int overlay = 0;
try { try {
overlay = jdbcTemplate.update("DELETE FROM sys_page_schema_overlay WHERE template_id = ?", templateId); overlay = jdbcTemplate.update("DELETE FROM sys_page_schema_overlay WHERE template_id = ?", tpl);
} catch (DataAccessException ex) { } catch (DataAccessException ex) {
log.debug("[deleteStandard] overlay 表不可用(忽略): {}", ex.getMessage()); log.debug("[deleteStandard] overlay 表不可用(忽略): {}", ex.getMessage());
} }

View File

@@ -60,19 +60,32 @@ class MenuRegistrarTest {
eq("演示功能改名"), eq("TPL-1"), any(), eq("admin"), eq("MENU-EXIST")); eq("演示功能改名"), eq("TPL-1"), any(), eq("admin"), eq("MENU-EXIST"));
} }
// 幂等 INSERT...SELECT...WHERE NOT EXISTS(sys_role_menu 无唯一约束,ON CONFLICT 不去重)
private static final String GRANT_SQL =
"INSERT INTO sys_role_menu(roleid, menuid) SELECT ?, ?"
+ " WHERE NOT EXISTS (SELECT 1 FROM sys_role_menu WHERE TRIM(roleid)=? AND TRIM(menuid)=?)";
@Test @Test
void grantToRolesInsertsPerRole() { void grantToRolesInsertsPerRoleIdempotent() {
JdbcTemplate jdbc = mock(JdbcTemplate.class); JdbcTemplate jdbc = mock(JdbcTemplate.class);
String insert = "INSERT INTO sys_role_menu(roleid, menuid) VALUES(?,?) ON CONFLICT DO NOTHING"; when(jdbc.update(eq(GRANT_SQL), eq("R1"), eq("M9"), eq("R1"), eq("M9"))).thenReturn(1);
when(jdbc.update(eq(insert), eq("R1"), eq("M9"))).thenReturn(1); when(jdbc.update(eq(GRANT_SQL), eq("R2"), eq("M9"), eq("R2"), eq("M9"))).thenReturn(1);
when(jdbc.update(eq(insert), eq("R2"), eq("M9"))).thenReturn(1);
MenuRegistrar reg = new MenuRegistrar(jdbc); MenuRegistrar reg = new MenuRegistrar(jdbc);
int granted = reg.grantToRoles("M9", List.of("R1", "R2"), "admin"); int granted = reg.grantToRoles("M9", List.of("R1", "R2"), "admin");
assertThat(granted).isEqualTo(2); assertThat(granted).isEqualTo(2);
verify(jdbc, times(1)).update(eq(insert), eq("R1"), eq("M9")); verify(jdbc, times(1)).update(eq(GRANT_SQL), eq("R1"), eq("M9"), eq("R1"), eq("M9"));
verify(jdbc, times(1)).update(eq(insert), eq("R2"), eq("M9")); verify(jdbc, times(1)).update(eq(GRANT_SQL), eq("R2"), eq("M9"), eq("R2"), eq("M9"));
}
@Test
void grantToRolesAlreadyGrantedCountsZero() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
// WHERE NOT EXISTS 命中 → 插 0 行(幂等)
when(jdbc.update(eq(GRANT_SQL), any(), any(), any(), any())).thenReturn(0);
MenuRegistrar reg = new MenuRegistrar(jdbc);
assertThat(reg.grantToRoles("M9", List.of("R1"), "admin")).isZero();
} }
@Test @Test
@@ -83,6 +96,6 @@ class MenuRegistrarTest {
assertThat(reg.grantToRoles("M9", List.of(), "admin")).isZero(); assertThat(reg.grantToRoles("M9", List.of(), "admin")).isZero();
assertThat(reg.grantToRoles(" ", List.of("R1"), "admin")).isZero(); assertThat(reg.grantToRoles(" ", List.of("R1"), "admin")).isZero();
assertThat(reg.grantToRoles("M9", List.of(" "), "admin")).isZero(); assertThat(reg.grantToRoles("M9", List.of(" "), "admin")).isZero();
verify(jdbc, times(0)).update(anyString(), anyString(), anyString()); verify(jdbc, times(0)).update(anyString(), any(), any(), any(), any());
} }
} }

View File

@@ -33,6 +33,12 @@ echo "[2] 菜单授权落库:psql 查 sys_role_menu"
N=$(pg "SELECT count(*) FROM sys_role_menu WHERE TRIM(roleid)='$ROLE' AND TRIM(menuid)='$MENUID';") N=$(pg "SELECT count(*) FROM sys_role_menu WHERE TRIM(roleid)='$ROLE' AND TRIM(menuid)='$MENUID';")
[ "$N" = "1" ] && ok "sys_role_menu 有 ($ROLE,$MENUID)" || bad "sys_role_menu 缺授权行(n=$N)" [ "$N" = "1" ] && ok "sys_role_menu 有 ($ROLE,$MENUID)" || bad "sys_role_menu 缺授权行(n=$N)"
echo "[2b] 重复发布(同 roleIds)→ 授权幂等(sys_role_menu 无唯一约束,须不产生重复行)"
GRANTED2=$(curl -s -X POST "$BASE/api/design/publish" "${H[@]}" -d "{\"entityId\":\"$EID\",\"tableName\":\"$TABLE\",\"templateId\":\"$TID\",\"menuName\":\"P16演示\",\"roleIds\":[\"$ROLE\"],\"generateDeploymentPackage\":false}" | jqpy "['data']['grantedRoleCount']")
[ "$GRANTED2" = "0" ] && ok "重复发布 grantedRoleCount=0(幂等)" || bad "重复发布应=0(实=$GRANTED2)"
N=$(pg "SELECT count(*) FROM sys_role_menu WHERE TRIM(roleid)='$ROLE' AND TRIM(menuid)='$MENUID';")
[ "$N" = "1" ] && ok "sys_role_menu 仍仅 1 行(无重复)" || bad "重复授权产生重复行(n=$N)"
echo "[3] 发布无 roleIds → warning(负控)" echo "[3] 发布无 roleIds → warning(负控)"
TABLE2="${TABLE}B" TABLE2="${TABLE}B"
EID2=$(curl -s -X POST "$BASE/api/meta/entity" "${H[@]}" -d "{\"tablename\":\"$TABLE2\",\"name\":\"P16B\",\"attributes\":[{\"column\":\"TITLE\",\"type\":\"string\",\"length\":100,\"mandatory\":true}]}" | jqpy "['data']['entityId']") EID2=$(curl -s -X POST "$BASE/api/meta/entity" "${H[@]}" -d "{\"tablename\":\"$TABLE2\",\"name\":\"P16B\",\"attributes\":[{\"column\":\"TITLE\",\"type\":\"string\",\"length\":100,\"mandatory\":true}]}" | jqpy "['data']['entityId']")