feat(P0②): 引擎ALTER安全通道 + AI安全门enforced
- AlterTableSqlGuard(legacy-core,纯静态白名单):只允许 加列/同族扩长/改可空,
拒 DROP COLUMN/RENAME/SET NOT NULL/多语句/跨族/小写绕过;放legacy-core避免反向依赖
- DataDicService.executeAlterSql 受控通道(过Guard再execute,defense-in-depth)
- MetaController POST /api/meta/entity/{table}/attributes 加列端点
(saveAttr元数据+alterAddColumnDdl镜像appendColumnDdl类型映射+evictByTable+补索引,恒可空)
- AiAgentService.applyLocalRelease 织入 AiToolRegistry.check:安全门 advisory→enforced
(local.apply工具身份,非本机/越权写路径403)
- 单测 Guard15/alter2/gate22(112基线无回归);scripts/p0-alter-acceptance.sh 真库验收
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -275,6 +275,89 @@ public class MetaController {
|
||||
return resp;
|
||||
}
|
||||
|
||||
@Operation(summary = "为已建实体加列(ALTER ADD COLUMN):写 SYS_ENTITYATTRIBUTE 元数据 + 受控 ALTER 物理表(只加列,恒可空)")
|
||||
@PostMapping("/api/meta/entity/{table}/attributes")
|
||||
public Map<String, Object> addAttributes(@PathVariable String table, @RequestBody Map<String, Object> req) {
|
||||
Properties ctx = UserSession.getAdmin();
|
||||
String t = table.toUpperCase();
|
||||
if (!t.matches("[A-Z][A-Z0-9_]{2,40}")) {
|
||||
return err("tablename 不合法: " + t);
|
||||
}
|
||||
Entity ent = (Entity) dataDicService.getSYSEntityByTableName(t);
|
||||
if (ent == null) {
|
||||
return err("实体不存在: " + t);
|
||||
}
|
||||
String entityId = idOf(ent);
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> attrs = (List<Map<String, Object>>) req.get("attributes");
|
||||
if (attrs == null || attrs.isEmpty()) {
|
||||
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<>();
|
||||
for (Map<String, Object> a : attrs) {
|
||||
String col = String.valueOf(a.get("column")).toUpperCase();
|
||||
if (!col.matches("[A-Z][A-Z0-9_]{1,60}")) {
|
||||
return err("字段名不合法: " + col);
|
||||
}
|
||||
Integer exists = jdbcTemplate.queryForObject(
|
||||
"SELECT COUNT(*) FROM SYS_ENTITYATTRIBUTE WHERE ENTITYID=? AND COLUMNNAME=?",
|
||||
Integer.class, entityId, col);
|
||||
if (exists != null && exists > 0) {
|
||||
return err("字段已存在: " + col);
|
||||
}
|
||||
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 = a.get("referenceTable") == null
|
||||
? null : String.valueOf(a.get("referenceTable")).toUpperCase();
|
||||
if (refTable == null || dataDicService.getSYSEntityByTableName(refTable) == null) {
|
||||
return err("引用目标实体不存在: " + refTable);
|
||||
}
|
||||
String referenceId = findOrCreateReference(refTable, col, ctx);
|
||||
saveAttr(attrTpl, entityId, col, display, referenceId, 36, false, false, ctx);
|
||||
ddl = alterAddColumnDdl(t, col, referenceId, 36, refTable);
|
||||
} else {
|
||||
String ref = switch (type) {
|
||||
case "integer" -> "INTEGER";
|
||||
case "number" -> "DECIMAL";
|
||||
case "date" -> "DATE";
|
||||
case "datetime" -> "TIME";
|
||||
case "boolean" -> "BOOLEAN";
|
||||
default -> "NVARCHAR";
|
||||
};
|
||||
Integer len = "NVARCHAR".equals(ref)
|
||||
? (a.get("length") instanceof Number n ? n.intValue() : 100) : null;
|
||||
saveAttr(attrTpl, entityId, col, display, ref, len, false, false, ctx);
|
||||
ddl = alterAddColumnDdl(t, col, ref, len, null);
|
||||
}
|
||||
// 受控 ALTER:经 AlterTableSqlGuard 白名单(defense-in-depth,executeAlterSql 内也再校验)
|
||||
String alterErr = dataDicService.executeAlterSql(ddl);
|
||||
if (alterErr != null) {
|
||||
return err("加列失败[" + col + "]: " + alterErr);
|
||||
}
|
||||
added.add(col);
|
||||
}
|
||||
// 失效 POInfo + 白名单缓存,使后续读写立即拿到新列(免重启)
|
||||
cacheInvalidator.evictByTable(t);
|
||||
// 新外键列补索引(IF NOT EXISTS 幂等)
|
||||
List<String> indexes = indexEnhancer.enhanceForNewEntity(t);
|
||||
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("status", 0);
|
||||
resp.put("msg", "altered");
|
||||
resp.put("data", Map.of(
|
||||
"tablename", t,
|
||||
"addedColumns", added,
|
||||
"indexCount", indexes.size()));
|
||||
return resp;
|
||||
}
|
||||
|
||||
/**
|
||||
* P1-4 手动失效 POInfo + 白名单缓存(C1 坑 3 修复的运维出口)。
|
||||
* 元数据被旁路写入(直改 SYS_ENTITYATTRIBUTE 等)后调用本接口,使变更立即生效,无需重启。
|
||||
@@ -449,6 +532,33 @@ public class MetaController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成单列 ALTER ADD COLUMN(P0②/P1④:已建实体加列)。恒可空——有数据的表加 NOT NULL 列会失败。
|
||||
* 类型映射镜像 {@link #appendColumnDdl}(NVARCHAR→varchar / INTEGER|BOOLEAN→integer /
|
||||
* DECIMAL|MONEY→numeric(18,6) / DATE|TIME→bigint / CHAR|引用→character(36))。
|
||||
* 结果须经 {@code AlterTableSqlGuard} 白名单后才执行。
|
||||
*/
|
||||
static String alterAddColumnDdl(String table, String col, String ref, Integer len, String refTable) {
|
||||
return "ALTER TABLE " + table + " ADD COLUMN " + col + " " + columnSqlType(ref, len, refTable);
|
||||
}
|
||||
|
||||
static String columnSqlType(String ref, Integer len, String refTable) {
|
||||
if ("NVARCHAR".equals(ref) || "CODE".equals(ref)) {
|
||||
int n = len != null && len > 0 ? len : 100;
|
||||
return "character varying(" + n + ")";
|
||||
} else if ("INTEGER".equals(ref) || "BOOLEAN".equals(ref) || "ENUMERATE".equals(ref)) {
|
||||
return "integer";
|
||||
} else if ("DECIMAL".equals(ref) || "MONEY".equals(ref)) {
|
||||
return "numeric(18,6)";
|
||||
} else if ("DATE".equals(ref) || "TIME".equals(ref)) {
|
||||
return "bigint";
|
||||
} else if ("CHAR".equals(ref)) {
|
||||
return "character(36)";
|
||||
}
|
||||
// 引用列:ref=SYS_REFERENCE_ID(uuid),外键指向 refTable
|
||||
return "character(36) REFERENCES " + (refTable != null ? refTable : "");
|
||||
}
|
||||
|
||||
private static int positiveInt(Object value, int defaultValue) {
|
||||
if (value instanceof Number n && n.intValue() > 0) {
|
||||
return n.intValue();
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.dsasp.server.dataDic.service.AlterTableSqlGuard;
|
||||
|
||||
/**
|
||||
* P0②/P1④ 加列 DDL 生成 + 安全契约。验证 {@code MetaController.alterAddColumnDdl} 的类型映射
|
||||
* 与 {@code appendColumnDdl} 一致,且<b>每一种生成形态都能通过 {@code AlterTableSqlGuard} 白名单</b>
|
||||
* (生成器只产守卫批准的 DDL,杜绝控制器侧生成出守卫会拒的语句)。
|
||||
*/
|
||||
class MetaControllerAlterTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("加列 DDL 按引擎类型映射生成,且全部通过 ALTER 安全守卫")
|
||||
void alterAddColumnDdlMatchesEngineTypesAndPassesGuard() {
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN AMOUNT numeric(18,6)",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "AMOUNT", "DECIMAL", null, null));
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN NAME character varying(200)",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "NAME", "NVARCHAR", 200, null));
|
||||
// NVARCHAR 缺长度 → 默认 100(对齐 appendColumnDdl)
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN NICK character varying(100)",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "NICK", "NVARCHAR", null, null));
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN QTY integer",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "QTY", "INTEGER", null, null));
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN FLAG integer",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "FLAG", "BOOLEAN", null, null));
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN HAPPENED bigint",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "HAPPENED", "DATE", null, null));
|
||||
assertGuarded("ALTER TABLE EIP4_X ADD COLUMN CREATED_AT bigint",
|
||||
MetaController.alterAddColumnDdl("EIP4_X", "CREATED_AT", "TIME", null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("引用列加列:外键指向目标表,通过安全守卫")
|
||||
void referenceColumnPointsAtTargetTableAndPassesGuard() {
|
||||
String referenceUuid = "11111111-1111-1111-1111-111111111111";
|
||||
assertGuarded("ALTER TABLE EIP4_ORDER ADD COLUMN CUSTOMERID character(36) REFERENCES EIP4_CUSTOMER",
|
||||
MetaController.alterAddColumnDdl("EIP4_ORDER", "CUSTOMERID", referenceUuid, 36, "EIP4_CUSTOMER"));
|
||||
}
|
||||
|
||||
private static void assertGuarded(String expectedDdl, String actualDdl) {
|
||||
assertEquals(expectedDdl, actualDdl);
|
||||
// 安全契约:生成的每条 ALTER 都必须被守卫接受(否则真实加列时会被引擎层拒)
|
||||
assertEquals(expectedDdl, assertDoesNotThrow(() -> AlterTableSqlGuard.guard(actualDdl),
|
||||
"生成的 ALTER 应通过安全守卫: " + actualDdl));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user