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:
@@ -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_]", "?");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 规则过滤。
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.eip4.platform.metadata.security;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.POJOInfo;
|
||||
import com.dsasp.server.common.dataDic.bean.Rule;
|
||||
import com.dsasp.server.common.privilege.bean.DataFilterRule;
|
||||
|
||||
/**
|
||||
* 单测用最小 POJOInfo 假实现:只承载 getTableName / getColumnCount / getColumnName
|
||||
* (IdentifierWhitelist.loadColumns 仅用这三者)。其余方法不在白名单路径上,抛异常即可。
|
||||
* 经反射注入 AbstractPOJOInfo.s_cache 后,POInfo.getPOInfo 即可在无 DB 时返回本实例。
|
||||
*/
|
||||
class FakeColumns implements POJOInfo {
|
||||
|
||||
private final String tableName;
|
||||
private final String[] columns;
|
||||
|
||||
FakeColumns(String tableName, String[] columns) {
|
||||
this.tableName = tableName;
|
||||
this.columns = columns;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColumnCount() {
|
||||
return columns.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnName(int index) {
|
||||
return columns[index];
|
||||
}
|
||||
|
||||
// ---- 以下方法不在白名单路径上 ----
|
||||
|
||||
private static UnsupportedOperationException nope() {
|
||||
return new UnsupportedOperationException("FakeColumns: 不应被白名单路径调用");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAD_Table_ID() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasKeyColumn() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAccessLevel() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColumnIndexByName(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColumnIndexByID(String adColumnId) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAD_Column_ID(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnSQL(int index, String prefix, StringBuffer lateral) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVirtualColumn(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnLabel(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnDescription(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getColumnClass(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnDisplayType(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDefaultLogic(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isColumnMandatory(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isColumnUpdateable(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColumnUpdateable(int index, boolean updateable) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUpdateable(boolean updateable) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isColumnLookup(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isKey(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAllowLogging(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFieldLength(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFieldLength(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String validate(int index, Object value) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String validateValue(int index, Object value) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StringBuffer buildSelect() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StringBuffer buildSelect(List<String> cols) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StringBuffer buildSelect(List<String> cols, String prefix) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StringBuffer buildCount() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isChangeLog() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceValue(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceValue(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDisplayIndex() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceValueTable(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceValueTable(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceValueColumnName(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceValueColumnName(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIdentifier(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCombidentifier(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Rule> getRules() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTableType() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKeyColumnName() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableDisplayName() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DataFilterRule> getDataFilterRules() {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> get_ColumnsByDisplayType(String displayType) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceTable(int index) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceTable(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEnumerateType(String columnName) {
|
||||
throw nope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEnumerateType(int index) {
|
||||
throw nope();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.eip4.platform.metadata.security;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.AbstractPOJOInfo;
|
||||
import com.dsasp.server.common.dataDic.bean.POJOInfo;
|
||||
import com.dsasp.server.common.dataDic.bean.SYS_Entity;
|
||||
import com.dsasp.server.common.dataDic.service.DataDicService;
|
||||
|
||||
/**
|
||||
* P1-3 标识符白名单单测(安全第 1 层)。
|
||||
*
|
||||
* <p>不依赖 DB/Spring:把假 POJOInfo(只实现 getColumnCount/getColumnName)经反射注入
|
||||
* {@code AbstractPOJOInfo.s_cache},使 {@code POInfo.getPOInfo(table)} 从缓存命中;
|
||||
* {@code DataDicService.getSYSEntityByTableName} 用 Mockito 桩,控制「表是否存在」。
|
||||
*
|
||||
* <p>覆盖:合法/非法列名、ORDER BY 注入负例(' OR 1=1-- / ;DROP 进列名与排序参数 → 拒绝)、
|
||||
* 合法表/非法表、保留键放行(保留键在 Controller 层,本类验证列校验本身)。
|
||||
*/
|
||||
class IdentifierWhitelistTest {
|
||||
|
||||
private static final String TABLE = "EIP4PT_ORDER";
|
||||
|
||||
private DataDicService dataDicService;
|
||||
private IdentifierWhitelist whitelist;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
dataDicService = mock(DataDicService.class);
|
||||
whitelist = new IdentifierWhitelist(dataDicService);
|
||||
|
||||
// 表存在 → 返回非 null SYS_Entity 桩
|
||||
SYS_Entity entityStub = mock(SYS_Entity.class);
|
||||
lenient().when(dataDicService.getSYSEntityByTableName(TABLE)).thenReturn(entityStub);
|
||||
lenient().when(dataDicService.getSYSEntityByTableName("NOPE_TABLE")).thenReturn(null);
|
||||
|
||||
// 合法列集合经假 POJOInfo + 静态缓存暴露给 POInfo.getPOInfo
|
||||
injectPoInfo(TABLE, new FakeColumns(TABLE,
|
||||
new String[] {"EIP4PT_ORDER_ID", "ORDERNO", "CUSTOMER", "TOTAL", "UPDATETIME"}));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearCache() throws Exception {
|
||||
staticCache().clear();
|
||||
whitelist.evictAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 合法列名通过() {
|
||||
whitelist.requireLegalColumn(TABLE, "ORDERNO", "查询条件");
|
||||
whitelist.requireLegalColumn(TABLE, "customer", "查询条件"); // 大小写不敏感
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非法列名拒绝() {
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> whitelist.requireLegalColumn(TABLE, "NOT_A_COLUMN", "查询条件"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ORDER_BY_注入_OR_负例拒绝() {
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> whitelist.requireLegalColumn(TABLE, "ORDERNO' OR 1=1--", "排序列"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ORDER_BY_注入_DROP_负例拒绝() {
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> whitelist.requireLegalColumn(TABLE, "ORDERNO; DROP TABLE EIP4PT_ORDER", "排序列"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 查询条件注入分号负例拒绝() {
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> whitelist.requireLegalColumn(TABLE, "1; DELETE FROM EIP4PT_ORDER", "查询条件"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 合法表通过() {
|
||||
assertTrue(whitelist.tableExists(TABLE));
|
||||
whitelist.requireLegalTable(TABLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非法表拒绝() {
|
||||
assertFalse(whitelist.tableExists("NOPE_TABLE"));
|
||||
assertThrows(IllegalIdentifierException.class, () -> whitelist.requireLegalTable("NOPE_TABLE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 报错文案不回显注入载荷() {
|
||||
IllegalIdentifierException ex = assertThrows(IllegalIdentifierException.class,
|
||||
() -> whitelist.requireLegalColumn(TABLE, "X' OR '1'='1", "查询条件"));
|
||||
// 不得把用户传入的注入载荷原样回显(避免反射式信息泄露):
|
||||
// 校验载荷特征字符(单引号、等号)与片段都不出现在报错文案里
|
||||
assertFalse(ex.getMessage().contains("'"));
|
||||
assertFalse(ex.getMessage().contains("="));
|
||||
assertFalse(ex.getMessage().contains("X' OR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 合法列集合归一化大写() {
|
||||
assertEquals(5, whitelist.legalColumns(TABLE).size());
|
||||
assertTrue(whitelist.legalColumns(TABLE).contains("ORDERNO"));
|
||||
assertFalse(whitelist.legalColumns(TABLE).contains("orderno"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 失效后重读元数据() throws Exception {
|
||||
assertTrue(whitelist.legalColumns(TABLE).contains("CUSTOMER"));
|
||||
// 模拟元数据变更:列集合收缩,仅在 evict 后才反映
|
||||
injectPoInfo(TABLE, new FakeColumns(TABLE, new String[] {"EIP4PT_ORDER_ID"}));
|
||||
// 未失效 → 仍是旧缓存
|
||||
assertTrue(whitelist.legalColumns(TABLE).contains("CUSTOMER"));
|
||||
whitelist.evict(TABLE);
|
||||
// 失效后 → 新元数据
|
||||
assertFalse(whitelist.legalColumns(TABLE).contains("CUSTOMER"));
|
||||
assertEquals(1, whitelist.legalColumns(TABLE).size());
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, POJOInfo> staticCache() throws Exception {
|
||||
Field f = AbstractPOJOInfo.class.getDeclaredField("s_cache");
|
||||
f.setAccessible(true);
|
||||
return (Map<String, POJOInfo>) f.get(null);
|
||||
}
|
||||
|
||||
private void injectPoInfo(String table, POJOInfo info) throws Exception {
|
||||
staticCache().put(table, info);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
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.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
|
||||
import com.eip4.platform.metadata.security.IdentifierWhitelist;
|
||||
import com.eip4.platform.metadata.security.IdentifierWhitelistExceptionHandler;
|
||||
import com.eip4.platform.metadata.security.IllegalIdentifierException;
|
||||
|
||||
/**
|
||||
* P1-3 端到端单测:EntityController.list 经 IdentifierWhitelist 校验路径。
|
||||
* 沿用本模块单测惯例——直接 new 控制器 + mock 引擎/白名单,不起 Spring 上下文。
|
||||
*
|
||||
* <p>覆盖:非法表名拒绝、非法查询条件列拒绝、非法排序方向拒绝(Controller 自身判 asc/desc)、
|
||||
* 合法请求放行且排序参数安全装配为引擎 ORDER 串、保留键不过白名单。
|
||||
* 末尾另测 {@link IdentifierWhitelistExceptionHandler} 把异常转 {status:1} 400 体。
|
||||
*/
|
||||
class EntityControllerWhitelistTest {
|
||||
|
||||
private static final String TABLE = "EIP4PT_ORDER";
|
||||
|
||||
@Test
|
||||
void 非法表名拒绝() {
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
doThrow(new IllegalIdentifierException("非法实体或元数据不存在: NOPE"))
|
||||
.when(wl).requireLegalTable(eq("NOPE"));
|
||||
EntityController c = new EntityController(engine, wl);
|
||||
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> c.list("NOPE", 1, 10, null, null, null, null, new HashMap<>()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非法查询条件列拒绝() {
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
doThrow(new IllegalIdentifierException("查询条件含非法列标识符,已拒绝"))
|
||||
.when(wl).requireLegalColumn(eq(TABLE), any(), eq("查询条件"));
|
||||
EntityController c = new EntityController(engine, wl);
|
||||
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("XX' OR 1=1--", "x");
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> c.list(TABLE, 1, 10, null, null, null, null, params));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非法排序方向拒绝() {
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
EntityController c = new EntityController(engine, wl);
|
||||
|
||||
// orderBy 列合法(白名单不抛),但 orderDir=drop 非 asc/desc → Controller 抛
|
||||
IllegalIdentifierException ex = assertThrows(IllegalIdentifierException.class,
|
||||
() -> c.list(TABLE, 1, 10, null, null, "ORDERNO", "drop", new HashMap<>()));
|
||||
assertFalse(ex.getMessage().contains("drop")); // 不回显非法值
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void 合法请求放行并安全装配排序串() {
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
Map<String, Object> engineResult = new HashMap<>();
|
||||
engineResult.put(POJOCRUDService.LIST_RESULT, java.util.List.of());
|
||||
engineResult.put(POJOCRUDService.PAGE_COUNT, 0L);
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(engineResult);
|
||||
EntityController c = new EntityController(engine, wl);
|
||||
|
||||
Map<String, Object> resp = c.list(TABLE, 1, 10, null, null, "ORDERNO", "asc", new HashMap<>());
|
||||
assertEquals(0, resp.get("status"));
|
||||
|
||||
// 引擎拿到的 cond.ORDER 必须是安全装配的 " ORDER BY ORDERNO ASC"
|
||||
ArgumentCaptor<Map<String, Object>> condCap = ArgumentCaptor.forClass(Map.class);
|
||||
verify(engine).listSelect(condCap.capture(), eq(TABLE), any(Properties.class));
|
||||
assertEquals(" ORDER BY ORDERNO ASC", condCap.getValue().get(POJOCRUDService.ORDER));
|
||||
// 排序列过了白名单
|
||||
verify(wl).requireLegalColumn(eq(TABLE), eq("ORDERNO"), eq("排序列"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void 保留键不过白名单只放行() {
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(new HashMap<>());
|
||||
EntityController c = new EntityController(engine, wl);
|
||||
|
||||
// page/perPage/asUser/roles 是保留键(经方法签名绑定),allParams 里只放保留键不应触发列校验
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("page", "1");
|
||||
params.put("perPage", "10");
|
||||
params.put("asUser", "u1");
|
||||
params.put("roles", "r1");
|
||||
c.list(TABLE, 1, 10, "u1", "r1", null, null, params);
|
||||
|
||||
// 表名仍校验,但保留键不进 requireLegalColumn
|
||||
verify(wl).requireLegalTable(TABLE);
|
||||
verify(wl, org.mockito.Mockito.never()).requireLegalColumn(any(), any(), eq("查询条件"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 异常处理器转400不回显载荷() {
|
||||
IdentifierWhitelistExceptionHandler handler = new IdentifierWhitelistExceptionHandler();
|
||||
var resp = handler.handle(new IllegalIdentifierException("查询条件含非法列标识符,已拒绝"));
|
||||
assertEquals(400, resp.getStatusCode().value());
|
||||
assertEquals(1, resp.getBody().get("status"));
|
||||
assertFalse(String.valueOf(resp.getBody().get("msg")).contains("'"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user