feat(metadata): P1-3 标识符白名单(安全第1层)——列名/表名/排序列过元数据白名单

EntityController.list 入口全部过白名单:表名须存在 SYS_ENTITY;查询条件 key
与 orderBy 须是该实体 SYS_ENTITYATTRIBUTE 已登记列;orderDir 限 asc/desc。
非法标识符 → HTTP 400 且不回显注入载荷('OR 1=1-- / ;DROP 进列名/排序参数均拒绝)。
保留键放行清单:page/perPage/asUser/roles/orderBy/orderDir。
IdentifierWhitelist 从 POInfo 取合法列集 + Caffeine 缓存;单测 16 个。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 12:10:42 +08:00
parent 185c18d38f
commit ad95e7d482
7 changed files with 792 additions and 7 deletions

View File

@@ -0,0 +1,134 @@
package com.eip4.platform.metadata.security;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.stereotype.Component;
import com.dsasp.server.common.dataDic.bean.POJOInfo;
import com.dsasp.server.common.dataDic.service.DataDicService;
import com.dsasp.server.dataDic.bean.POInfo;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* 标识符白名单(安全第 1 层 / 最优先,《架构设计》(docs/架构设计.md) 第四节)。
*
* <p><b>元数据即白名单,零维护零误杀</b>:动态 SQL 引擎独有的安全红利——一个实体的
* 「合法列名集合」就是它在 {@code SYS_ENTITYATTRIBUTE} 里登记的属性列。任何进入
* WHERE 列名 / ORDER BY 排序列 / 字段投影的标识符,必须存在于该集合,否则拒绝。
* 表名本身也必须存在于 {@code SYS_ENTITY}。
*
* <p>合法列集合从引擎 {@link POInfo} 取({@code POInfo.getPOInfo} 已走 POInfo 缓存),
* 此处再叠一层 Caffeine 缓存归一化后的大写列名集合,避免每请求重建 Set。元数据写路径
* 变更后由 {@link com.eip4.platform.metadata.perf.PoInfoCacheInvalidator} 调 {@link #evict}
* 失效(与 P1-4 POInfo 缓存失效同源,保证白名单不滞后于元数据)。
*/
@Component
public class IdentifierWhitelist {
private final DataDicService dataDicService;
/** 归一化(全大写)后的合法列名集合,按表名缓存。 */
private final Cache<String, Set<String>> columnCache = Caffeine.newBuilder()
.maximumSize(2_000)
.build();
public IdentifierWhitelist(DataDicService dataDicService) {
this.dataDicService = dataDicService;
}
/**
* 表名是否为已登记实体(存在于 SYS_ENTITY)。
* @param table 调用方传入的表名(任意大小写)
*/
public boolean tableExists(String table) {
if (isBlank(table)) {
return false;
}
return !legalColumns(table).isEmpty();
}
/**
* 该实体的合法列名集合(全大写归一化)。表不存在或无属性时返回空集。
*/
public Set<String> legalColumns(String table) {
if (isBlank(table)) {
return Set.of();
}
return columnCache.get(table.toUpperCase(), this::loadColumns);
}
/**
* 校验列标识符合法(存在于该实体元数据),否则抛 {@link IllegalIdentifierException}。
* 不回显传入内容,只报「哪一类参数 + 哪个实体」。
*
* @param table 实体表名
* @param column 待校验列名
* @param kind 参数语义(如「查询条件」「排序列」「字段投影」),用于报错归类
*/
public void requireLegalColumn(String table, String column, String kind) {
Set<String> cols = legalColumns(table);
if (cols.isEmpty()) {
throw new IllegalIdentifierException("非法实体或元数据不存在: " + safeTable(table));
}
if (column == null || !cols.contains(column.toUpperCase())) {
throw new IllegalIdentifierException(
kind + "含非法列标识符,已拒绝(必须是实体 " + safeTable(table) + " 的已登记列)");
}
}
/**
* 校验表名合法(存在于 SYS_ENTITY),否则抛 {@link IllegalIdentifierException}。
*/
public void requireLegalTable(String table) {
if (!tableExists(table)) {
throw new IllegalIdentifierException("非法实体或元数据不存在: " + safeTable(table));
}
}
/** 元数据变更后失效某表的白名单缓存(与 POInfo 缓存失效同步调用)。 */
public void evict(String table) {
if (!isBlank(table)) {
columnCache.invalidate(table.toUpperCase());
}
}
/** 全量失效(删除实体等粗粒度变更时用)。 */
public void evictAll() {
columnCache.invalidateAll();
}
private Set<String> loadColumns(String table) {
// table 此处已是大写。getSYSEntityByTableName 命中才算已登记实体;
// 未登记直接回空集(tableExists/ requireLegalTable 据此判 400)。
if (dataDicService.getSYSEntityByTableName(table) == null) {
return Set.of();
}
POJOInfo info = POInfo.getPOInfo(table);
if (info == null) {
return Set.of();
}
Set<String> cols = new LinkedHashSet<>();
int count = info.getColumnCount();
for (int i = 0; i < count; i++) {
String name = info.getColumnName(i);
if (name != null && !name.isBlank()) {
cols.add(name.toUpperCase());
}
}
return cols.isEmpty() ? Set.of() : Set.copyOf(cols);
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
/** 表名只放行白名单字符做日志/报错回显,杜绝把注入载荷反射回去。 */
private static String safeTable(String table) {
if (table == null) {
return "";
}
return table.toUpperCase().replaceAll("[^A-Z0-9_]", "?");
}
}

View File

@@ -0,0 +1,28 @@
package com.eip4.platform.metadata.security;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 标识符白名单拒绝 → HTTP 400(安全第 1 层兜底)。
*
* <p>返回 amis 约定的 {@code {status:1, msg}} 体,{@code msg} 只来自
* {@link IllegalIdentifierException} 的归类文案(已剔除用户原始拼接内容),
* <b>不回显注入载荷</b>。HTTP 状态码 400 让调用方/网关可据此拦截与告警。
*/
@RestControllerAdvice
public class IdentifierWhitelistExceptionHandler {
@ExceptionHandler(IllegalIdentifierException.class)
public ResponseEntity<Map<String, Object>> handle(IllegalIdentifierException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", 1);
body.put("msg", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
}

View File

@@ -0,0 +1,17 @@
package com.eip4.platform.metadata.security;
/**
* 标识符白名单校验失败(安全第 1 层,《架构设计》(docs/架构设计.md) 第四节)。
*
* <p>抛出时 {@code message} 只描述「哪一类参数非法」,<b>绝不</b>回显用户传入的
* 原始拼接内容,避免把注入载荷反射回响应(错误回显本身是一种信息泄露面)。
* 由 {@link IdentifierWhitelistExceptionHandler} 统一转 400。
*/
public class IllegalIdentifierException extends RuntimeException {
private static final long serialVersionUID = 1L;
public IllegalIdentifierException(String message) {
super(message);
}
}

View File

@@ -6,6 +6,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -17,6 +18,7 @@ import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
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.security.IdentifierWhitelist;
/**
* WS1 冒烟接口:直接驱动移植后的 POJOCRUDService 引擎。
@@ -26,10 +28,20 @@ import com.dsasp.server.common.util.UserSession;
@RequestMapping("/api/entity")
public class EntityController {
private final POJOCRUDService pojoCRUDService;
/**
* amis filter / 分页 / 权限上下文透传的保留键放行清单(安全第 1 层白名单的「非列名」豁免)。
* 这些键不是实体列,是协议/控制参数,不过白名单(但仍各自做语义校验,见 list 方法)。
*/
private static final Set<String> RESERVED_KEYS = Set.of(
"page", "perPage", "asUser", "roles", "orderBy", "orderDir");
public EntityController(POJOCRUDService pojoCRUDService) {
private final POJOCRUDService pojoCRUDService;
private final IdentifierWhitelist identifierWhitelist;
public EntityController(POJOCRUDService pojoCRUDService,
IdentifierWhitelist identifierWhitelist) {
this.pojoCRUDService = pojoCRUDService;
this.identifierWhitelist = identifierWhitelist;
}
/**
@@ -46,20 +58,31 @@ public class EntityController {
@RequestParam(defaultValue = "10") int perPage,
@RequestParam(required = false) String asUser,
@RequestParam(required = false) String roles,
@RequestParam(required = false) String orderBy,
@RequestParam(required = false) String orderDir,
@RequestParam Map<String, String> allParams) {
String t = table.toUpperCase();
// 安全第 1 层:表名必须存在于 SYS_ENTITY,否则 400(非法表名不进引擎拼接)
identifierWhitelist.requireLegalTable(t);
Properties ctx = buildCtx(asUser, roles);
Map<String, Object> cond = new HashMap<>();
cond.put(POJOCRUDService.PAGE_START, (page - 1) * perPage);
cond.put(POJOCRUDService.PAGE_SIZE, perPage);
// amis filter 表单值透传为引擎查询条件(保留大写列名约定,跳过分页参数、权限参数与空值)
// amis filter 表单值透传为引擎查询条件:保留键放行,其余 key 必须是合法列(过白名单),空值跳过
allParams.forEach((k, v) -> {
if (!"page".equals(k) && !"perPage".equals(k) && !"asUser".equals(k) && !"roles".equals(k)
&& v != null && !v.isBlank()) {
cond.put(k.toUpperCase(), v);
if (RESERVED_KEYS.contains(k) || v == null || v.isBlank()) {
return;
}
// 查询条件 key 进引擎 WHERE 列名拼接,必须过白名单(非法列名 ' OR 1=1-- / ;DROP 等 → 400)
identifierWhitelist.requireLegalColumn(t, k, "查询条件");
cond.put(k.toUpperCase(), v);
});
Map<String, Object> result = pojoCRUDService.listSelect(cond, table.toUpperCase(), ctx);
// 排序参数:orderBy 必须是合法列、orderDir 限 asc/desc,引擎按 ORDER 键拼 ORDER BY(同样裸拼,须过白名单)
applyOrder(cond, t, orderBy, orderDir);
Map<String, Object> result = pojoCRUDService.listSelect(cond, t, ctx);
Map<String, Object> data = new HashMap<>();
data.put("items", toRows(result.get(POJOCRUDService.LIST_RESULT)));
@@ -84,6 +107,28 @@ public class EntityController {
return resp;
}
/**
* 校验并装配排序参数。orderBy 列名过白名单(非法列名/ORDER BY 注入 → 400),
* orderDir 限定 {@code asc/desc}(非法值 → 400)。合法时按引擎 {@code ORDER} 键
* 拼 {@code " ORDER BY <col> <dir>"}(引擎将其裸拼到 SQL 末尾,故必须先过白名单)。
*/
private void applyOrder(Map<String, Object> cond, String table, String orderBy, String orderDir) {
if (orderBy == null || orderBy.isBlank()) {
return;
}
identifierWhitelist.requireLegalColumn(table, orderBy, "排序列");
String dir = "asc";
if (orderDir != null && !orderDir.isBlank()) {
String d = orderDir.trim().toLowerCase();
if (!"asc".equals(d) && !"desc".equals(d)) {
throw new com.eip4.platform.metadata.security.IllegalIdentifierException(
"排序方向非法,只允许 asc/desc");
}
dir = d;
}
cond.put(POJOCRUDService.ORDER, " ORDER BY " + orderBy.toUpperCase() + " " + dir.toUpperCase());
}
/**
* 构造调用上下文。无 asUser → ADMIN 视角(不触发过滤);有 asUser → 非 ADMIN 视角,
* 把 CURRENTUSER 与 ROLES(List)放入 Properties,交由引擎按 SYS_FILTERRULE 规则过滤。