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:
@@ -406,6 +406,16 @@ public class AiAgentService {
|
||||
|
||||
public AiApplyRun applyLocalRelease(String taskId, String changeSetId, String baseUrl) {
|
||||
getTask(taskId);
|
||||
// P0②(c) 安全门 enforced:把 AiToolRegistry 策略引擎织入真实写路径。此前 check() 仅挂在
|
||||
// /api/ai/tools/check-access 咨询端点(只读返决策),写路径仅靠 requireAdmin + localhost 兜底,
|
||||
// scope/localOnly/productionWrite 策略形同 advisory。这里以 local.apply 工具身份过门:
|
||||
// targetEnv=baseUrl,非本机 / 越权 → 403,localReleaseExecutor.apply 不被触发。
|
||||
AiToolAccessDecision gate = toolRegistry.check(new AiToolAccessRequest(
|
||||
"agent-developer", "local.apply", List.of("ai:local:apply"), baseUrl, false));
|
||||
if (gate == null || !gate.allowed()) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
|
||||
"本地应用被安全门拒绝: " + (gate == null ? "no-decision" : String.join("; ", gate.blockers())));
|
||||
}
|
||||
AiChangeSet changeSet = findChangeSet(taskId, changeSetId);
|
||||
if (!"READY_FOR_REVIEW".equals(changeSet.status())) {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包状态不可本地应用: " + changeSet.status());
|
||||
|
||||
@@ -48,6 +48,17 @@ class AiAgentServiceTest {
|
||||
assertEquals(3, service.listAudit(task.id()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("P0②(c) 安全门 enforced:非本机 baseUrl 的本地应用被拒(FORBIDDEN),写路径不被触发")
|
||||
void localApplyRejectedForNonLocalBaseUrl() {
|
||||
AiAgentService service = newService();
|
||||
var task = service.createTask("安全门测试");
|
||||
// 非本机 targetEnv → AiToolRegistry.check 不通过(local-only + production-write 拦截)
|
||||
var ex = assertThrows(ResponseStatusException.class,
|
||||
() -> service.applyLocalRelease(task.id(), "any-change-set", "http://prod-host:9000"));
|
||||
assertEquals(org.springframework.http.HttpStatus.FORBIDDEN, ex.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无效 schema 草稿会阻止生成变更包")
|
||||
void invalidSchemaBlocksChangeSet() throws Exception {
|
||||
|
||||
@@ -101,6 +101,13 @@ public interface DataDicService {
|
||||
* @return
|
||||
*/
|
||||
public String executeCreateSql(String sql);
|
||||
|
||||
/**
|
||||
* 受控变更实体表结构(只允许 加列 / 同族扩长 / 改可空,经 AlterTableSqlGuard 白名单校验)。
|
||||
* @param sql ALTER 语句
|
||||
* @return null=成功;非空=失败原因
|
||||
*/
|
||||
public String executeAlterSql(String sql);
|
||||
|
||||
/**
|
||||
* get entity by table name
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.dsasp.server.dataDic.service;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* P0② 引擎 ALTER 安全通道守卫(纯静态 / 无 Spring 依赖,便于单测)。
|
||||
*
|
||||
* <p>保真层(com.dsasp.*)的 DDL 此前只接受 CREATE({@code DataDicServiceImpl.executeCreateSql}),
|
||||
* 完全不支持 ALTER。本守卫把 ALTER 从「完全不可达」收窄为「只允许 加列 / 同族扩长 / 改可空」
|
||||
* 的最小安全集,显式拒绝一切破坏性 / 不可逆 DDL。
|
||||
*
|
||||
* <p>放在 legacy-core(而非 platform-metadata)以避免 legacy-core→metadata 的反向(循环)依赖:
|
||||
* 引擎层 {@code executeAlterSql} 与控制层 {@code MetaController} 都引用本类,形成 defense-in-depth
|
||||
* 双层校验。
|
||||
*
|
||||
* <p>受控形态(标识符大小写敏感,必须大写,匹配引擎建表正则;类型 token 小写,匹配
|
||||
* {@code MetaController.appendColumnDdl} 的输出):
|
||||
* <ul>
|
||||
* <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>
|
||||
* </ul>
|
||||
* 其余(DROP COLUMN / RENAME / SET NOT NULL / 跨族类型转换 / 多语句 / 子查询 / 注释 / 小写绕过)
|
||||
* 一律抛 {@link IllegalArgumentException}。
|
||||
*/
|
||||
public final class AlterTableSqlGuard {
|
||||
|
||||
private AlterTableSqlGuard() {
|
||||
}
|
||||
|
||||
/** 表名/列名规则与 MetaController 建表白名单一致(大写起头,大写数字下划线)。 */
|
||||
private static final String TABLE = "[A-Z][A-Z0-9_]{2,40}";
|
||||
private static final String COLUMN = "[A-Z][A-Z0-9_]{1,60}";
|
||||
|
||||
/** 加列允许的引擎类型(对齐 appendColumnDdl:字符串/数值/整型/时间戳/定长/引用列)。 */
|
||||
private static final String ADD_TYPE =
|
||||
"(?:character varying\\(\\d{1,4}\\)"
|
||||
+ "|numeric\\(\\d{1,2},\\d{1,2}\\)"
|
||||
+ "|integer"
|
||||
+ "|bigint"
|
||||
+ "|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(
|
||||
"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(
|
||||
"ALTER TABLE (" + TABLE + ") ALTER COLUMN (" + COLUMN + ") DROP NOT NULL");
|
||||
|
||||
/**
|
||||
* 注意:不含 " NOT NULL"(会误伤合法的 "DROP NOT NULL");ADD COLUMN ... NOT NULL 由
|
||||
* 「不匹配任何受控形态」自然拒绝。"SET NOT NULL" 明确列出(不会误伤 DROP NOT NULL)。
|
||||
*/
|
||||
private static final String[] DENY_TOKENS = {
|
||||
"--", "/*", "*/", " USING ", "(SELECT", " SELECT ",
|
||||
" DROP COLUMN", " RENAME ", " SET NOT NULL", " SET DEFAULT",
|
||||
" DROP TABLE", " DROP CONSTRAINT", " ADD CONSTRAINT",
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验并归一化一条 ALTER 语句。
|
||||
*
|
||||
* @param sql 原始 SQL
|
||||
* @return 归一后的安全 SQL(折叠空白、去尾分号),可直接交给 jdbcTemplate.execute
|
||||
* @throws IllegalArgumentException 非白名单 / 危险 / 非受控形态
|
||||
*/
|
||||
public static String guard(String sql) {
|
||||
if (sql == null) {
|
||||
throw new IllegalArgumentException("ALTER 脚本为空");
|
||||
}
|
||||
String s = sql.strip();
|
||||
if (s.endsWith(";")) {
|
||||
s = s.substring(0, s.length() - 1).strip();
|
||||
}
|
||||
s = s.replaceAll("\\s+", " ");
|
||||
if (s.isEmpty()) {
|
||||
throw new IllegalArgumentException("ALTER 脚本为空");
|
||||
}
|
||||
// 单语句:折叠后不得再含分号(分号注入第二句)
|
||||
if (s.indexOf(';') >= 0) {
|
||||
throw new IllegalArgumentException("只允许单条 ALTER 语句: " + sql);
|
||||
}
|
||||
String upper = s.toUpperCase(Locale.ROOT);
|
||||
if (!upper.startsWith("ALTER TABLE ")) {
|
||||
throw new IllegalArgumentException("只允许 ALTER TABLE 语句: " + sql);
|
||||
}
|
||||
for (String bad : DENY_TOKENS) {
|
||||
if (upper.contains(bad)) {
|
||||
throw new IllegalArgumentException("ALTER 含禁止操作 [" + bad.trim() + "]: " + sql);
|
||||
}
|
||||
}
|
||||
// 必须精确匹配三种受控形态之一(整串 matches,标识符大小写敏感)
|
||||
if (ADD_COLUMN.matcher(s).matches()
|
||||
|| ALTER_TYPE.matcher(s).matches()
|
||||
|| DROP_NOT_NULL.matcher(s).matches()) {
|
||||
return s;
|
||||
}
|
||||
throw new IllegalArgumentException(
|
||||
"非受控的 ALTER 形态(只允许 加列 / 同族扩长 / 改可空): " + sql);
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,18 @@ public class DataDicServiceImpl implements DataDicService {
|
||||
return "非合法的创建表脚本";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String executeAlterSql(String sql) {
|
||||
String safe;
|
||||
try {
|
||||
safe = AlterTableSqlGuard.guard(sql);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return e.getMessage();
|
||||
}
|
||||
jdbcTemplate.execute(safe);
|
||||
return null;
|
||||
}
|
||||
|
||||
@OriginServiceMethod(name="新增实体的默认属性", type = "dataDic" , description = "新增实体,默认产生createby,updatby,createtime,updatetime,version,isactive,orgid,departid")
|
||||
@Override
|
||||
public GeneralPOJO getTableDefaultAttribute() {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.dsasp.server.dataDic.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* P0② 引擎 ALTER 安全通道守卫。保真层(com.dsasp.*)的 DDL 此前只接受 CREATE
|
||||
* (DataDicServiceImpl.executeCreateSql),完全不支持 ALTER。本守卫把 ALTER 从
|
||||
* 「完全不可达」收窄为「只允许 加列 / 同族扩长 / 改可空」的最小安全集,显式拒绝
|
||||
* 一切破坏性/不可逆 DDL(DROP COLUMN / RENAME / SET NOT NULL / 多语句 / 跨族类型 /
|
||||
* 小写绕过 / 子查询)。规则与 MetaController.appendColumnDdl 的类型映射对齐。
|
||||
*/
|
||||
class AlterTableSqlGuardTest {
|
||||
|
||||
// ---------- 允许:加列 ----------
|
||||
@Test
|
||||
@DisplayName("加列:numeric/varchar/integer/bigint/character(36) 五类引擎类型通过,返回归一 SQL")
|
||||
void addColumnAllowedTypes() {
|
||||
assertEquals("ALTER TABLE EIP4_X ADD COLUMN AMOUNT numeric(18,6)",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN AMOUNT numeric(18,6)"));
|
||||
assertEquals("ALTER TABLE EIP4_X ADD COLUMN NAME character varying(200)",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN NAME character varying(200)"));
|
||||
assertEquals("ALTER TABLE EIP4_X ADD COLUMN QTY integer",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN QTY integer"));
|
||||
assertEquals("ALTER TABLE EIP4_X ADD COLUMN WHEN_AT bigint",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN WHEN_AT bigint"));
|
||||
assertEquals("ALTER TABLE EIP4_X ADD COLUMN CODE character(36)",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN CODE character(36)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("加引用列:character(36) REFERENCES 目标表 通过")
|
||||
void addReferenceColumnAllowed() {
|
||||
assertEquals("ALTER TABLE EIP4_ORDER ADD COLUMN CUSTOMERID character(36) REFERENCES EIP4_CUSTOMER",
|
||||
AlterTableSqlGuard.guard(
|
||||
"ALTER TABLE EIP4_ORDER ADD COLUMN CUSTOMERID character(36) REFERENCES EIP4_CUSTOMER"));
|
||||
}
|
||||
|
||||
// ---------- 允许:同族扩长 ----------
|
||||
@Test
|
||||
@DisplayName("扩长:ALTER COLUMN ... TYPE varchar(n) / numeric(p,s) 通过")
|
||||
void widenTypeAllowed() {
|
||||
assertEquals("ALTER TABLE EIP4_X ALTER COLUMN NAME TYPE character varying(400)",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN NAME TYPE character varying(400)"));
|
||||
assertEquals("ALTER TABLE EIP4_X ALTER COLUMN AMOUNT TYPE numeric(20,8)",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN AMOUNT TYPE numeric(20,8)"));
|
||||
}
|
||||
|
||||
// ---------- 允许:改可空 ----------
|
||||
@Test
|
||||
@DisplayName("改可空:ALTER COLUMN ... DROP NOT NULL 通过")
|
||||
void dropNotNullAllowed() {
|
||||
assertEquals("ALTER TABLE EIP4_X ALTER COLUMN NAME DROP NOT NULL",
|
||||
AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN NAME DROP NOT NULL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("空白容错:首尾空白 + 单个结尾分号 被归一掉,内部多空格折叠")
|
||||
void whitespaceNormalized() {
|
||||
assertEquals("ALTER TABLE EIP4_X ADD COLUMN AMOUNT numeric(18,6)",
|
||||
AlterTableSqlGuard.guard(" ALTER TABLE EIP4_X ADD COLUMN AMOUNT numeric(18,6) ; "));
|
||||
}
|
||||
|
||||
// ---------- 拒绝:破坏性/不可逆 ----------
|
||||
@Test
|
||||
@DisplayName("拒绝:DROP COLUMN(丢数据)")
|
||||
void rejectDropColumn() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X DROP COLUMN NAME"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:RENAME(破坏引用)")
|
||||
void rejectRename() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X RENAME COLUMN NAME TO NAME2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:SET NOT NULL(收紧约束,对存量数据不可逆)")
|
||||
void rejectSetNotNull() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN NAME SET NOT NULL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:ADD COLUMN ... NOT NULL(有数据的表加非空列会失败)")
|
||||
void rejectAddColumnNotNull() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN NAME character varying(200) NOT NULL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:跨族类型转换(varchar→int 会丢数据/报错)")
|
||||
void rejectCrossFamilyTypeChange() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ALTER COLUMN QTY TYPE integer"));
|
||||
}
|
||||
|
||||
// ---------- 拒绝:注入/越权 ----------
|
||||
@Test
|
||||
@DisplayName("拒绝:多语句(分号注入第二句)")
|
||||
void rejectMultiStatement() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard(
|
||||
"ALTER TABLE EIP4_X ADD COLUMN NAME integer; DROP TABLE EIP4_X"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:DROP TABLE / CREATE 等非 ALTER 语句")
|
||||
void rejectNonAlter() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("DROP TABLE EIP4_X"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("CREATE TABLE EIP4_X (EIP4_X_ID character(36))"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:小写绕过(标识符必须大写,匹配引擎建表规则)")
|
||||
void rejectLowercaseBypass() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("alter table eip4_x add column amount numeric(18,6)"));
|
||||
// 表名小写
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE eip4x ADD COLUMN AMOUNT integer"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:子查询 / USING 强转 / 注释")
|
||||
void rejectSubqueryAndUsing() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard(
|
||||
"ALTER TABLE EIP4_X ALTER COLUMN QTY TYPE integer USING (SELECT 1)"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN NAME integer -- drop"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("拒绝:未知类型 / 空 / null")
|
||||
void rejectUnknownTypeAndEmpty() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard("ALTER TABLE EIP4_X ADD COLUMN ID money(1)"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard(" "));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AlterTableSqlGuard.guard(null));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
71
scripts/p0-alter-acceptance.sh
Normal file
71
scripts/p0-alter-acceptance.sh
Normal file
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
# P0② 引擎 ALTER 安全通道 · 端到端验收
|
||||
#
|
||||
# 证明:已建实体经 POST /api/meta/entity/{table}/attributes 加列后,
|
||||
# ① 元数据(SYS_ENTITYATTRIBUTE)有新列;② 物理表真的 ALTER 加了列(psql 直查 information_schema);
|
||||
# ③ 受控守卫拒绝重复列/不存在的表(负控)。
|
||||
#
|
||||
# 用法(先以 dev profile 起 8094,见 scripts/run-dev.sh / five-ring-acceptance.sh):
|
||||
# BASE=http://localhost:8094 bash scripts/p0-alter-acceptance.sh
|
||||
set -uo pipefail
|
||||
BASE=${BASE:-http://localhost:8094}
|
||||
ACCT=${ACCT:-admin}; PW=${PW:-111111}
|
||||
PGURL=${PGURL:-postgresql://zhengwr@localhost:5433/eip4dev}
|
||||
TS=$(date +%s)
|
||||
TABLE="EIP4PT_ALT${TS}"
|
||||
TBL_LC=$(echo "$TABLE" | tr '[:upper:]' '[:lower:]')
|
||||
FAIL=0
|
||||
jqpy() { python3 -c "import sys,json;d=json.load(sys.stdin,strict=False);print(eval(\"d$1\"))" 2>/dev/null; }
|
||||
say() { echo "$@"; }
|
||||
ok() { echo " ✓ $*"; }
|
||||
bad() { echo " ✗ $*"; FAIL=1; }
|
||||
|
||||
TOK=$(curl -s -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
|
||||
-d "{\"account\":\"$ACCT\",\"password\":\"$PW\"}" | jqpy "['token']")
|
||||
H=(-H "Authorization: Bearer $TOK" -H 'Content-Type: application/json')
|
||||
[ -n "${TOK:-}" ] && [ "$TOK" != "None" ] && ok "login token len=${#TOK}" || { bad "login 失败"; exit 1; }
|
||||
|
||||
say "[1] 建实体 $TABLE(仅 TITLE)"
|
||||
ST=$(curl -s -X POST "$BASE/api/meta/entity" "${H[@]}" -d "{
|
||||
\"tablename\":\"$TABLE\",\"name\":\"ALTER验收\",
|
||||
\"attributes\":[{\"column\":\"TITLE\",\"display\":\"标题\",\"type\":\"string\",\"length\":200,\"mandatory\":true}]}" | jqpy "['status']")
|
||||
[ "$ST" = "0" ] && ok "建表 status=0" || bad "建表失败 status=$ST"
|
||||
|
||||
say "[2] 加列:AMOUNT(number)/QTY(integer)/NOTE(string,len 300)/OWNER(reference→SYS_USER)"
|
||||
R=$(curl -s -X POST "$BASE/api/meta/entity/$TABLE/attributes" "${H[@]}" -d '{
|
||||
"attributes":[{"column":"AMOUNT","display":"金额","type":"number"},
|
||||
{"column":"QTY","display":"数量","type":"integer"},
|
||||
{"column":"NOTE","display":"备注","type":"string","length":300},
|
||||
{"column":"OWNER","display":"负责人","type":"reference","referenceTable":"SYS_USER"}]}')
|
||||
ST=$(echo "$R" | jqpy "['status']")
|
||||
ADDED=$(echo "$R" | jqpy "['data']['addedColumns']")
|
||||
[ "$ST" = "0" ] && ok "加列 status=0 added=$ADDED" || bad "加列失败: $R"
|
||||
|
||||
say "[3] 元数据核对:GET attributes 含新列"
|
||||
COLS=$(curl -s "$BASE/api/meta/entity/$TABLE/attributes" "${H[@]}" | python3 -c "import sys,json;d=json.load(sys.stdin);print(' '.join(c['column'] for c in d['data']['columns']))" 2>/dev/null)
|
||||
for c in AMOUNT QTY NOTE OWNER; do
|
||||
echo "$COLS" | grep -q "$c" && ok "元数据有列 $c" || bad "元数据缺列 $c (cols=$COLS)"
|
||||
done
|
||||
|
||||
say "[4] 物理表核对:psql 直查 information_schema(证明 ALTER 真生效)"
|
||||
if command -v psql >/dev/null 2>&1; then
|
||||
PHYS=$(psql "$PGURL" -At -c "SELECT column_name||':'||data_type FROM information_schema.columns WHERE table_schema='eip3' AND table_name='$TBL_LC' AND column_name IN ('amount','qty','note','owner') ORDER BY column_name;" 2>/dev/null)
|
||||
echo "$PHYS" | grep -q "amount:numeric" && ok "物理列 amount numeric" || bad "物理列 amount 缺/类型错: $PHYS"
|
||||
echo "$PHYS" | grep -q "qty:integer" && ok "物理列 qty integer" || bad "物理列 qty 缺/类型错"
|
||||
echo "$PHYS" | grep -qE "note:character varying" && ok "物理列 note varchar" || bad "物理列 note 缺/类型错"
|
||||
echo "$PHYS" | grep -qE "owner:character" && ok "物理列 owner character(36)" || bad "物理列 owner 缺/类型错"
|
||||
else
|
||||
echo " (psql 不可用,跳过物理核对)"
|
||||
fi
|
||||
|
||||
say "[5] 负控:重复加 AMOUNT → 拒;加到不存在的表 → 拒"
|
||||
ST=$(curl -s -X POST "$BASE/api/meta/entity/$TABLE/attributes" "${H[@]}" -d '{"attributes":[{"column":"AMOUNT","type":"number"}]}' | jqpy "['status']")
|
||||
[ "$ST" != "0" ] && ok "重复列被拒 status=$ST" || bad "重复列未被拒"
|
||||
ST=$(curl -s -X POST "$BASE/api/meta/entity/EIP4PT_NOPE${TS}/attributes" "${H[@]}" -d '{"attributes":[{"column":"X","type":"number"}]}' | jqpy "['status']")
|
||||
[ "$ST" != "0" ] && ok "不存在的表被拒 status=$ST" || bad "不存在的表未被拒"
|
||||
|
||||
say "[6] 清理"
|
||||
curl -s -X DELETE "$BASE/api/meta/entity/$TABLE" "${H[@]}" >/dev/null && ok "删除 $TABLE"
|
||||
|
||||
echo ""
|
||||
[ "$FAIL" = "0" ] && echo "[完成] P0② 引擎 ALTER 安全通道 端到端验收 ✅ 全绿" || { echo "[失败] 存在未通过项 ✗"; exit 1; }
|
||||
Reference in New Issue
Block a user