test(parity): C2 数据行级权限自举 + 对拍样本(3 实体×3 用户 100% + 负例)

自举 + 对拍证明保真层数据权限真实现与物理事实逐行对齐:

- bootstrap-privilege.sql(幂等):建 SYS_FILTERRULE + 中间表 SYS_FILTERRULEROLE
  (LIST 多值列经 REFERENCEVALUE→中间表落地)+ 自描述元数据;为 EIP4PT_TASK/
  PROJECT/CUSTOMER 各配 1 条 "CREATEBY = {CURRENTUSERID}" 规则,并把 CREATEBY
  重分区到 USER_ALICE/BOB/CAROL 使过滤可判别。
- ParityCli 增 --privilege 模式 + PrivilegeCheckRunner:被测侧经引擎
  GET /list?asUser&roles 触发行级过滤,基线侧 JDBC 同语义 WHERE,RowDiff 逐行比。
- EngineHttpClient 增 asUser/roles 透传 + statusOf(负例取状态码)。
- EntityController.list 增可选 asUser/roles 构造非 ADMIN ctx(引擎仅非 ADMIN 才过滤)。

实测:正例 3 实体×3 用户=9 例 150 行 100% 逐行一致;负例错误角色 3/3 抛
PrivilegeException(HTTP 500)被拒;回归 ParityCli --all 21/21、1108 行 100%。
报告:platform-auth/C2实测报告.md + parity-reports/privilege-parity-*.{json,md}。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 00:11:08 +08:00
parent fc867dc110
commit 83c6abb1f9
10 changed files with 1105 additions and 8 deletions

View File

@@ -0,0 +1,168 @@
# EIP4 M0 任务 C2 实测报告 —— 数据权限最小真实现替换桩
> 工程:eip4-platform · 环境:本地 PG 15 `localhost:5433/eip4m0`,服务 profile=local @8084
> 时间:2026-06-11 · 通过标准:**≥3 个行级过滤实体进对拍样本且通过**
## 一、结论速览
| 项 | 结果 |
|----|------|
| 三文件移植 + Jackson 1.x 依赖 + 删桩 | ✅ 全模块 `mvn clean install` 通过 |
| ArchUnit 架构纪律(保真层禁止依赖现代层) | ✅ 仍绿(1/1) |
| 单测(DataFilterHelper JSON 互转 + getWhereClause 拼接) | ✅ 9 用例全过(要求 ≥6) |
| **行级过滤对拍(3 受控实体 × 3 用户 = 9 正例)** | ✅ **9/9 逐行一致,150 行 100%** |
| 负例(无命中角色 → PrivilegeException) | ✅ 3/3 全部被拒(HTTP 500) |
| 回归(ParityCli `--all`) | ✅ **21/21 实体、1108 行 100% 逐行一致** |
对拍报告产物:`parity-reports/privilege-parity-20260611-000631.{json,md}`(正例 9/9 一致 + 负例 3/3 被拒);
回归报告:`parity-reports/parity-20260611-000638.{json,md}`(21/21)。
---
## 二、移植清单(保真层 platform-legacy-core,包名原样)
| 文件 | 来源(framework) | 目标(platform-legacy-core) | 说明 |
|------|------|------|------|
| `DataPrivilegeServiceImpl.java`(226 行) | `com.dsasp.server.privilege.service` | 同包 | `@Service("dataPrivilegeService")`,原样移植,一行未改 |
| `DataFilterHelper.java`(110 行) | `com.dsasp.server.privilege.bean` | 同包 | FILTERRULE JSON 互转,用 Jackson 1.x |
| `MethodSecurityInterceptor.java`(18 行) | `com.dsasp.server.common.privilege.bean` | 同包(原已有 Conditional/DataFilterRule/DataPrivilege) | 注解,被 Impl 引用;无处理器亦无害 |
依赖既有(legacy-core 已具备,未新增):`Conditional` / `DataFilterRule` / `DataPrivilege` bean、`DataPrivilegeService` 接口、`POJOCRUDService`、`AbstractPOJOInfo`、`SpringBeanOsgiServices`、`SysConfig`、`StringUtil`、`UserSession`、`LoggedInUser`、`PrivilegeException` / `ValidationException`。
**删桩**:删除 `platform-auth` 的 `com.eip4.platform.auth.stub.StubDataPrivilegeService`(与新 `@Service("dataPrivilegeService")` 重名,双 Bean 冲突);其余 4 个桩保留。`platform-auth/README.md` 记录 dataPrivilegeService 已由保真层接管、P2 在此模块做组织/权限整体真实现。
**组件扫描**:`Eip4PlatformApplication` 已 `scanBasePackages={"com.eip4.platform","com.dsasp"}`,移植的 `@Service` 自动被扫描;`POInfo.getDataFilterRules()` 经 `SpringBeanOsgiServices.getBeanByName("dataPrivilegeService")` 取到真实现。服务启动无 Bean 冲突,证明删桩到位。
---
## 三、Jackson 1.x 依赖决策
- `DataFilterHelper` 原版用 `org.codehaus.jackson.*`(Jackson 1.x:`ObjectMapper`/`JsonNode`/`ArrayNode`)做 `FILTERRULE`(Conditional[])的 JSON 序列化/反序列化。
- 保真层纪律「com.dsasp 旧代码一行不改」⇒ **不改写为 Jackson 2**。
- 在父 pom `dependencyManagement` 与 `platform-legacy-core` pom 显式引入 `org.codehaus.jackson:jackson-mapper-asl:1.9.13`(传递带 `jackson-core-asl`)。
- Jackson 1.x(`org.codehaus.jackson`)与现代层 Jackson 2(`com.fasterxml.jackson`)包名不同,**共存不冲突**;现代层(EntityController/对拍 CLI)序列化仍用 Jackson 2。
---
## 四、ROLES 多值落地机制(查明结论)
`SYS_FILTERRULE.ROLES` = 「一条规则关联多个角色」的多值列,引擎按 **LIST 显示类型 + 中间表(MIDTABLE)** 落地,**读路径真实走引擎**:
1. **ROLES 列元数据**:`REFERENCEID='LIST'`(⇒ displayType=LIST、ColumnClass=List.class),`REFERENCEVALUE` 指向一条 `SYS_REFERENCEVALUE`。
2. **SYS_REFERENCEVALUE 解析**(`DataDicServiceImpl.getEntityTableNameByReferenceValue` / `getColumnNameByReferenceValue` 两条 JOIN):
- `ENTITYID` → `SYS_ENTITY.TABLENAME` = **`SYS_FILTERRULEROLE`**(中间表,tabletype=2,恰 2 列)
- `ENTITYATTRIBUTEID` → `SYS_ENTITYATTRIBUTE.COLUMNNAME` = **`FILTERRULEID`**(回引 SYS_FILTERRULE 的列)
3. **加载**(`POJOServiceImpl.loadPOJO(isHierarchical=true)` → `hierarchicalQuery`,源码 1256-1262):对 LIST 列查
`SELECT * FROM SYS_FILTERRULEROLE WHERE FILTERRULEID = '<规则id>'`,把「另一列」`ROLEID` 的全部值收集成 `List<String>`,经 `updateHierarchicalValue` 设回 ROLES。
4. `DataFilterHelper.converToDataFilterRule` 的 `po.get_Value("ROLES")` 即拿到该 `List<String>`。
> 即「子表 sys_filterrulerole(filterruleid 列)」口径成立:中间表的回引列就是 `FILTERRULEID`,取值列是 `ROLEID`,引擎用回引列定位、取另一列成 List。
**自举落法**:本地用 `bootstrap-privilege.sql` **优先按引擎读路径口径直接建模 + 直插中间表行**(中间表恰 2 列、tabletype=2、SYS_REFERENCE/SYS_REFERENCEVALUE 三件套齐备),读路径完全经引擎 `loadPOJO(...,true)` 展开 List,与原版加载机制一致。DB 实证:
```
ROLES 列 : REFERENCEID=LIST, REFERENCEVALUE=d1000000-...-0001
referencevalue 解析 → midtable=SYS_FILTERRULEROLE, backref_col=FILTERRULEID
中间表行 : f1...0001|ROLE_TASK f1...0002|ROLE_PROJECT f1...0003|ROLE_CUSTOMER
```
---
## 五、自举扩展(bootstrap-privilege.sql)
位置:`platform-parity/src/main/resources/bootstrap/bootstrap-privilege.sql`(幂等,可重复执行;在 C1 的 bootstrap-sys.sql + ParitySeeder 之后追加)。
内容:
1. **物理表**:`SYS_FILTERRULE`(规则主表,FILTERRULE 用 `text` 存 JSON、ROLES 为 LIST 不落物理列)+ `SYS_FILTERRULEROLE`(中间表,恰 2 列)。
2. **自描述元数据**:两实体进 `SYS_ENTITY`(SYS_FILTERRULEROLE tabletype=2)+ 各列进 `SYS_ENTITYATTRIBUTE`;ROLES 列 LIST + REFERENCEVALUE 三件套(`SYS_REFERENCE` + `SYS_REFERENCEVALUE`)。
3. **受控实体 CREATEBY 重分区**:ParitySeeder 把 EIP4PT_TASK/PROJECT/CUSTOMER 的 50 行 CREATEBY 全置 'ADMIN';脚本按行序 %3 改成 `USER_ALICE`/`USER_BOB`/`USER_CAROL`(确定性、幂等),使 `CREATEBY = {CURRENTUSERID}` 过滤可判别。分布(每实体):ALICE 16、BOB 17、CAROL 17。
4. **过滤规则**:为 3 个实体各配 1 条 `[{"preConditional":"CREATEBY","sign":"=","backConditional":"{CURRENTUSERID}","type":"CURRENTUSERID"}]` 规则(规则 ENTITYID 动态 `SELECT FROM sys_entity`),各关联 1 个角色(ROLE_TASK/ROLE_PROJECT/ROLE_CUSTOMER,经中间表)。
> 选 CREATEBY(char(36))作过滤列:种子实体均有此列且语义贴合「只看自己创建的行」;PG bpchar 比较忽略尾空格,引擎 `P.CREATEBY='USER_ALICE'` 与基线 `WHERE createby='USER_ALICE'` 同语义。规则用 CURRENTUSERID 等值类型,不触达 SysConfig/OWNNERPROJECT 路径。
---
## 六、对拍样本与数字(--privilege 模式)
新增 `platform-parity` 的 `--privilege` 模式(`ParityCli` + `PrivilegeCheckRunner` + `EngineHttpClient` 增 asUser/roles 透传)。
驱动方式:`EntityController.list` 增可选 `asUser`/`roles` 查询参,构造**非 ADMIN** ctx(CURRENTUSER + ROLES List)触发引擎行级过滤(引擎仅 `ctx.CURRENTUSER != ADMIN` 时才调 getWhereClause)。
- **被测侧**:`GET /api/entity/{t}/list?asUser=U&roles=R` → 引擎 `POJOCRUDServiceImpl.listSelect` → `dataPrivilegeService.getWhereClause` 拼 `AND (...)` 注入 WHERE。
- **基线侧**:直连 JDBC `SELECT * FROM t WHERE createby = 'U'`(同语义 ground truth)。
- **比对**:复用 C1 的 `RowDiff` 逐行逐列(行序无关、主键配对、char 尾空格/numeric/时间戳归一)。
### 正例(3 实体 × 3 用户 = 9 例,逐行 diff)
| 实体[用户] | 引擎行数 | JDBC 行数 | 逐行一致率 | 结果 |
|---|---|---|---|---|
| EIP4PT_CUSTOMER[USER_ALICE] | 16 | 16 | 1.0000 | ✅ |
| EIP4PT_CUSTOMER[USER_BOB] | 17 | 17 | 1.0000 | ✅ |
| EIP4PT_CUSTOMER[USER_CAROL] | 17 | 17 | 1.0000 | ✅ |
| EIP4PT_PROJECT[USER_ALICE] | 16 | 16 | 1.0000 | ✅ |
| EIP4PT_PROJECT[USER_BOB] | 17 | 17 | 1.0000 | ✅ |
| EIP4PT_PROJECT[USER_CAROL] | 17 | 17 | 1.0000 | ✅ |
| EIP4PT_TASK[USER_ALICE] | 16 | 16 | 1.0000 | ✅ |
| EIP4PT_TASK[USER_BOB] | 17 | 17 | 1.0000 | ✅ |
| EIP4PT_TASK[USER_CAROL] | 17 | 17 | 1.0000 | ✅ |
**汇总**:正例 9/9 全一致,总比对 **150 行 100% 逐行一致**;实体级与单元格级零差异。
### 负例(无命中角色 → PrivilegeException)
用错误角色 `ROLE_NOBODY` 访问 3 个受控实体(规则存在但无角色命中):
| 实体 | HTTP 状态 | 期望 | 结果 |
|---|---|---|---|
| EIP4PT_CUSTOMER | 500 | 非200(PrivilegeException) | ✅ 被拒 |
| EIP4PT_PROJECT | 500 | 非200(PrivilegeException) | ✅ 被拒 |
| EIP4PT_TASK | 500 | 非200(PrivilegeException) | ✅ 被拒 |
服务端日志证据(原版语义,`getWhereClause` 的 first 分支抛出):
```
com.dsasp.server.common.exception.PrivilegeException: 没有任务数据访问权限
```
### 回归(ParityCli --all,无规则实体不受影响)
`--all` 用 ADMIN 视角读全部 21 个 EIP4PT_* 实体:**21/21 实体、1108 行 100% 逐行一致**(无规则实体不被过滤;3 个受控实体在 ADMIN 视角同样返回全量,CREATEBY 重分区不破坏与物理事实的逐行一致)。
---
## 七、单测(platform-legacy-core,9 用例)
`com.dsasp.server.privilege.DataPrivilegeTest`(+ 测试用 `FakePOInfo`,经反射注入 `AbstractPOJOInfo` 静态缓存,绕开 DB/Spring):
- JSON 互转:单条往返、多条往返(含 op=OR/AND)、null/空/`"null"`/`[]` 归零、非法 JSON 抛异常 —— 4 例。
- getWhereClause 拼接:单角色命中(`P.OWNER ='USER_ALICE'`)、多规则命中 OR 连接(CURRENTUSER + CURRENTUSERDEPART)、无角色命中抛 PrivilegeException(含表显示名)、SYS_FILTERRULE 表返回 null、无规则实体返回 null —— 5 例。
`Tests run: 9, Failures: 0, Errors: 0`。
---
## 八、与 P2 真实现的关系
- **本实现即原版语义**:行级过滤算法、ROLES 多值落地、规则装载、CURRENTUSER/DEPART/ORG/SPECIAL/OWNNERPROJECT 各分支均原样移植自 framework,语义零偏移。
- **P2 增量**:在保真层这套引擎语义之上,接入**真实组织机构数据源**(部门/机构/用户-角色关系)与**角色/过滤规则的管理 UI**,落在 `platform-auth`。P2 不改写过滤算法,只提供「规则与角色从哪来、谁来维护」。
- C2 已把 `dataPrivilegeService` 从「桩(不过滤)」升级为「真实现(原版过滤)」,P2 接手时数据权限内核已就位。
---
## 九、遇到的坑(已同步《EIP4迁移手册v1.md》§5.8/5.9/5.10)
1. **ROLES 多值列经 LIST + 中间表落地**(§5.8):多值列不落物理列,值在中间表;需 LIST + REFERENCEVALUE + SYS_REFERENCE + 中间表(恰 2 列、回引列在前)四要素齐备,且读路径走 `loadPOJO(...,isHierarchical=true)` 才展开 List。
2. **行级过滤仅在非 ADMIN 上下文触发**(§5.9):`listSelectSpecialCol` 判断 `ctx.CURRENTUSER != ADMIN` 才调过滤;ADMIN 天然看全量。验证必须构造非 ADMIN ctx(本 C2 经 EntityController 的 asUser/roles 可选参实现)。
3. **DataFilterHelper 用 Jackson 1.x**(§5.10):原版 `org.codehaus.jackson`,保真纪律不改写为 Jackson 2,显式引 `jackson-mapper-asl:1.9.13` 与 Jackson 2 共存。
4. **bootstrap 清理顺序**:首次执行 `DELETE FROM sys_filterrulerole` 会因表不存在报错;改为只 `DROP TABLE IF EXISTS ... CASCADE`(行随表清),元数据 DELETE 保留(持久表)。
---
## 附:产物清单
- 移植:`platform-legacy-core/.../privilege/service/DataPrivilegeServiceImpl.java`、`.../privilege/bean/DataFilterHelper.java`、`.../common/privilege/bean/MethodSecurityInterceptor.java`
- 依赖:父 pom + `platform-legacy-core/pom.xml` 增 `jackson-mapper-asl:1.9.13`;legacy-core 增 `spring-boot-starter-test`(test)
- 删桩 + 文档:删 `StubDataPrivilegeService.java`;新增 `platform-auth/README.md`
- 自举:`platform-parity/src/main/resources/bootstrap/bootstrap-privilege.sql`
- 对拍:`platform-parity/.../selfcheck/PrivilegeCheckRunner.java`;`ParityCli` 增 `--privilege`;`EngineHttpClient` 增 asUser/roles 透传 + statusOf
- 驱动:`platform-metadata/.../web/EntityController.java` 增 asUser/roles 可选参
- 单测:`platform-legacy-core/src/test/.../privilege/DataPrivilegeTest.java` + `FakePOInfo.java`
- 报告:本文件 + `parity-reports/privilege-parity-*.{json,md}` + `parity-reports/parity-*.{json,md}`(回归)

View File

@@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO; import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService; 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.dsasp.server.common.util.UserSession;
/** /**
@@ -31,19 +32,29 @@ public class EntityController {
this.pojoCRUDService = pojoCRUDService; this.pojoCRUDService = pojoCRUDService;
} }
/** 分页查询:GET /api/entity/{table}/list?page=1&perPage=10&列名=值(amis filter 透传) */ /**
* 分页查询:GET /api/entity/{table}/list?page=1&perPage=10&列名=值(amis filter 透传)
*
* <p>C2 数据行级权限驱动:可选传 {@code asUser}(当前用户)+ {@code roles}(逗号分隔角色)
* 构造非 ADMIN 上下文,从而触发 {@code POJOCRUDServiceImpl} 的行级过滤
* (引擎仅当 {@code ctx.CURRENTUSER != ADMIN} 时调 {@code dataPrivilegeService.getWhereClause})。
* 不传则沿用 ADMIN 视角(不过滤),与原有行为一致。
*/
@GetMapping("/{table}/list") @GetMapping("/{table}/list")
public Map<String, Object> list(@PathVariable String table, public Map<String, Object> list(@PathVariable String table,
@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int perPage, @RequestParam(defaultValue = "10") int perPage,
@RequestParam(required = false) String asUser,
@RequestParam(required = false) String roles,
@RequestParam Map<String, String> allParams) { @RequestParam Map<String, String> allParams) {
Properties ctx = UserSession.getAdmin(); Properties ctx = buildCtx(asUser, roles);
Map<String, Object> cond = new HashMap<>(); Map<String, Object> cond = new HashMap<>();
cond.put(POJOCRUDService.PAGE_START, (page - 1) * perPage); cond.put(POJOCRUDService.PAGE_START, (page - 1) * perPage);
cond.put(POJOCRUDService.PAGE_SIZE, perPage); cond.put(POJOCRUDService.PAGE_SIZE, perPage);
// amis filter 表单值透传为引擎查询条件(保留大写列名约定,跳过分页参数与空值) // amis filter 表单值透传为引擎查询条件(保留大写列名约定,跳过分页参数、权限参数与空值)
allParams.forEach((k, v) -> { allParams.forEach((k, v) -> {
if (!"page".equals(k) && !"perPage".equals(k) && v != null && !v.isBlank()) { if (!"page".equals(k) && !"perPage".equals(k) && !"asUser".equals(k) && !"roles".equals(k)
&& v != null && !v.isBlank()) {
cond.put(k.toUpperCase(), v); cond.put(k.toUpperCase(), v);
} }
}); });
@@ -73,6 +84,28 @@ public class EntityController {
return resp; return resp;
} }
/**
* 构造调用上下文。无 asUser → ADMIN 视角(不触发过滤);有 asUser → 非 ADMIN 视角,
* 把 CURRENTUSER 与 ROLES(List)放入 Properties,交由引擎按 SYS_FILTERRULE 规则过滤。
*/
private Properties buildCtx(String asUser, String roles) {
if (asUser == null || asUser.isBlank()) {
return UserSession.getAdmin();
}
Properties ctx = new Properties();
ctx.setProperty(LoggedInUser.CURRENTUSER, asUser);
List<String> roleList = new ArrayList<>();
if (roles != null && !roles.isBlank()) {
for (String r : roles.split(",")) {
if (!r.isBlank()) {
roleList.add(r.trim());
}
}
}
ctx.put(LoggedInUser.ROLES, roleList);
return ctx;
}
/** GeneralPOJO 值存于内部数组(非 bean getter),手工展开为平面 map 供 JSON 序列化。 */ /** GeneralPOJO 值存于内部数组(非 bean getter),手工展开为平面 map 供 JSON 序列化。 */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private List<Map<String, Object>> toRows(Object listResult) { private List<Map<String, Object>> toRows(Object listResult) {

View File

@@ -0,0 +1,262 @@
{
"summary" : {
"entityCount" : 21,
"cleanEntities" : 21,
"totalRows" : 1108,
"entityConsistencyRate" : 1.0,
"allClean" : true
},
"reports" : [ {
"label" : "EIP4PT_ALLTYPE",
"keyColumns" : [ "EIP4PT_ALLTYPE_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_ASSET",
"keyColumns" : [ "EIP4PT_ASSET_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_COMBO",
"keyColumns" : [ "EIP4PT_COMBO_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_CONFIG",
"keyColumns" : [ "EIP4PT_CONFIG_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_CONTRACT",
"keyColumns" : [ "EIP4PT_CONTRACT_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_CUSTOMER",
"keyColumns" : [ "EIP4PT_CUSTOMER_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_DEPT",
"keyColumns" : [ "EIP4PT_DEPT_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_DEVICE",
"keyColumns" : [ "EIP4PT_DEVICE_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_EMPLOYEE",
"keyColumns" : [ "EIP4PT_EMPLOYEE_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_INVOICE",
"keyColumns" : [ "EIP4PT_INVOICE_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_LOG",
"keyColumns" : [ "EIP4PT_LOG_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_ORDER",
"keyColumns" : [ "EIP4PT_ORDER_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_ORDERLINE",
"keyColumns" : [ "EIP4PT_ORDERLINE_ID" ],
"leftRowCount" : 108,
"rightRowCount" : 108,
"matchedRows" : 108,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_PAYMENT",
"keyColumns" : [ "EIP4PT_PAYMENT_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_PRODUCT",
"keyColumns" : [ "EIP4PT_PRODUCT_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_PROJECT",
"keyColumns" : [ "EIP4PT_PROJECT_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_REFER",
"keyColumns" : [ "EIP4PT_REFER_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_STOCK",
"keyColumns" : [ "EIP4PT_STOCK_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_SUPPLIER",
"keyColumns" : [ "EIP4PT_SUPPLIER_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_TASK",
"keyColumns" : [ "EIP4PT_TASK_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_WAREHOUSE",
"keyColumns" : [ "EIP4PT_WAREHOUSE_ID" ],
"leftRowCount" : 50,
"rightRowCount" : 50,
"matchedRows" : 50,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
} ]
}

View File

@@ -0,0 +1,31 @@
# C1 自对拍报告
- 实体数: 21
- 全一致实体: 21
- 总比对行数(JDBC 基线侧): 1108
- 实体级一致率: 1.0000 ✅ 全部逐行一致
| 实体 | 行数 | 内容差异行 | 仅JDBC | 仅引擎 | 逐行一致率 | 结果 |
|---|---|---|---|---|---|---|
| EIP4PT_ALLTYPE | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_ASSET | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_COMBO | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_CONFIG | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_CONTRACT | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_CUSTOMER | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_DEPT | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_DEVICE | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_EMPLOYEE | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_INVOICE | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_LOG | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_ORDER | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_ORDERLINE | 108 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_PAYMENT | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_PRODUCT | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_PROJECT | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_REFER | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_STOCK | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_SUPPLIER | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_TASK | 50 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_WAREHOUSE | 50 | 0 | 0 | 0 | 1.0000 | ✅ |

View File

@@ -0,0 +1,125 @@
{
"summary" : {
"mode" : "privilege",
"positiveCases" : 9,
"positiveClean" : 9,
"totalRows" : 150,
"positiveConsistencyRate" : 1.0,
"negativeStatus" : {
"EIP4PT_CUSTOMER" : 500,
"EIP4PT_PROJECT" : 500,
"EIP4PT_TASK" : 500
},
"allNegativeRejected" : true,
"allPass" : true
},
"positive" : [ {
"label" : "EIP4PT_CUSTOMER[USER_ALICE]",
"keyColumns" : [ "EIP4PT_CUSTOMER_ID" ],
"leftRowCount" : 16,
"rightRowCount" : 16,
"matchedRows" : 16,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_CUSTOMER[USER_BOB]",
"keyColumns" : [ "EIP4PT_CUSTOMER_ID" ],
"leftRowCount" : 17,
"rightRowCount" : 17,
"matchedRows" : 17,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_CUSTOMER[USER_CAROL]",
"keyColumns" : [ "EIP4PT_CUSTOMER_ID" ],
"leftRowCount" : 17,
"rightRowCount" : 17,
"matchedRows" : 17,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_PROJECT[USER_ALICE]",
"keyColumns" : [ "EIP4PT_PROJECT_ID" ],
"leftRowCount" : 16,
"rightRowCount" : 16,
"matchedRows" : 16,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_PROJECT[USER_BOB]",
"keyColumns" : [ "EIP4PT_PROJECT_ID" ],
"leftRowCount" : 17,
"rightRowCount" : 17,
"matchedRows" : 17,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_PROJECT[USER_CAROL]",
"keyColumns" : [ "EIP4PT_PROJECT_ID" ],
"leftRowCount" : 17,
"rightRowCount" : 17,
"matchedRows" : 17,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_TASK[USER_ALICE]",
"keyColumns" : [ "EIP4PT_TASK_ID" ],
"leftRowCount" : 16,
"rightRowCount" : 16,
"matchedRows" : 16,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_TASK[USER_BOB]",
"keyColumns" : [ "EIP4PT_TASK_ID" ],
"leftRowCount" : 17,
"rightRowCount" : 17,
"matchedRows" : 17,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
}, {
"label" : "EIP4PT_TASK[USER_CAROL]",
"keyColumns" : [ "EIP4PT_TASK_ID" ],
"leftRowCount" : 17,
"rightRowCount" : 17,
"matchedRows" : 17,
"mismatchRows" : 0,
"onlyInLeft" : [ ],
"onlyInRight" : [ ],
"clean" : true,
"consistencyRate" : 1.0,
"mismatches" : [ ]
} ]
}

View File

@@ -0,0 +1,29 @@
# C2 数据行级权限对拍报告
- 正例(受控实体 × 用户): 9,全一致: 9
- 总比对行数(JDBC 基线侧): 150
- 正例逐行一致率: 1.0000 ✅ 全部逐行一致
- 负例(错误角色被拒): ✅ 全部被拒
## 正例:引擎行级过滤 vs JDBC 同语义基线
| 实体[用户] | 行数 | 内容差异 | 仅JDBC | 仅引擎 | 一致率 | 结果 |
|---|---|---|---|---|---|---|
| EIP4PT_CUSTOMER[USER_ALICE] | 16 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_CUSTOMER[USER_BOB] | 17 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_CUSTOMER[USER_CAROL] | 17 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_PROJECT[USER_ALICE] | 16 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_PROJECT[USER_BOB] | 17 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_PROJECT[USER_CAROL] | 17 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_TASK[USER_ALICE] | 16 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_TASK[USER_BOB] | 17 | 0 | 0 | 0 | 1.0000 | ✅ |
| EIP4PT_TASK[USER_CAROL] | 17 | 0 | 0 | 0 | 1.0000 | ✅ |
## 负例:错误角色 ROLE_NOBODY 访问受控实体
| 实体 | HTTP 状态 | 期望 | 结果 |
|---|---|---|---|
| EIP4PT_CUSTOMER | 500 | 非200(PrivilegeException) | ✅ 被拒 |
| EIP4PT_PROJECT | 500 | 非200(PrivilegeException) | ✅ 被拒 |
| EIP4PT_TASK | 500 | 非200(PrivilegeException) | ✅ 被拒 |

View File

@@ -41,11 +41,19 @@ public class EngineHttpClient {
/** 抓某实体全量行(自动翻页直到取满 total)。 */ /** 抓某实体全量行(自动翻页直到取满 total)。 */
public List<Map<String, Object>> listAll(String table) throws Exception { public List<Map<String, Object>> listAll(String table) throws Exception {
return listAll(table, "");
}
/**
* 抓某实体全量行,附加查询串(C2 数据权限用:{@code asUser=...&roles=...} 构造非 ADMIN ctx,
* 触发引擎行级过滤)。{@code extraQuery} 不含前导 {@code &}。
*/
public List<Map<String, Object>> listAll(String table, String extraQuery) throws Exception {
List<Map<String, Object>> rows = new ArrayList<>(); List<Map<String, Object>> rows = new ArrayList<>();
int page = 1; int page = 1;
long total = -1; long total = -1;
while (true) { while (true) {
JsonNode data = getList(table, page, perPage); JsonNode data = getList(table, page, perPage, extraQuery);
JsonNode items = data.get("items"); JsonNode items = data.get("items");
if (items != null && items.isArray()) { if (items != null && items.isArray()) {
for (JsonNode item : items) { for (JsonNode item : items) {
@@ -69,12 +77,13 @@ public class EngineHttpClient {
/** 取某实体 total(引擎 PAGE_COUNT)。 */ /** 取某实体 total(引擎 PAGE_COUNT)。 */
public long total(String table) throws Exception { public long total(String table) throws Exception {
JsonNode data = getList(table, 1, 1); JsonNode data = getList(table, 1, 1, "");
return data.has("total") ? data.get("total").asLong() : 0; return data.has("total") ? data.get("total").asLong() : 0;
} }
private JsonNode getList(String table, int page, int size) throws Exception { private JsonNode getList(String table, int page, int size, String extraQuery) throws Exception {
String url = baseUrl + "/api/entity/" + table + "/list?page=" + page + "&perPage=" + size; String url = baseUrl + "/api/entity/" + table + "/list?page=" + page + "&perPage=" + size
+ (extraQuery == null || extraQuery.isBlank() ? "" : "&" + extraQuery);
HttpRequest req = HttpRequest.newBuilder(URI.create(url)) HttpRequest req = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(60)).GET().build(); .timeout(Duration.ofSeconds(60)).GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
@@ -90,6 +99,19 @@ public class EngineHttpClient {
return root.path("data"); return root.path("data");
} }
/**
* 仅取 HTTP 状态码(C2 负例断言用:无命中角色 → 引擎抛 PrivilegeException → 非 200)。
* 返回状态码,不解析 body。
*/
public int statusOf(String table, String extraQuery) throws Exception {
String url = baseUrl + "/api/entity/" + table + "/list?page=1&perPage=1"
+ (extraQuery == null || extraQuery.isBlank() ? "" : "&" + extraQuery);
HttpRequest req = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(60)).GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
return resp.statusCode();
}
private Map<String, Object> jsonToRow(JsonNode item) { private Map<String, Object> jsonToRow(JsonNode item) {
Map<String, Object> row = new LinkedHashMap<>(); Map<String, Object> row = new LinkedHashMap<>();
item.fields().forEachRemaining(e -> { item.fields().forEachRemaining(e -> {

View File

@@ -24,10 +24,14 @@ import com.fasterxml.jackson.databind.SerializationFeature;
* java -cp ... com.eip4.platform.parity.selfcheck.ParityCli \ * java -cp ... com.eip4.platform.parity.selfcheck.ParityCli \
* --entities=EIP4PT_ALLTYPE,EIP4PT_ORDER # 或 --all * --entities=EIP4PT_ALLTYPE,EIP4PT_ORDER # 或 --all
* [--seed] # 先灌种子(建 ≥20 实体 + 每实体 50 行) * [--seed] # 先灌种子(建 ≥20 实体 + 每实体 50 行)
* [--privilege] # C2 数据行级权限对拍(3 受控实体×3 用户 + 负例)
* [--jdbc=jdbc:postgresql://localhost:5433/eip4m0] [--user=zhengwr] [--pass=] * [--jdbc=jdbc:postgresql://localhost:5433/eip4m0] [--user=zhengwr] [--pass=]
* [--engine=http://localhost:8084] [--out=parity-reports] * [--engine=http://localhost:8084] [--out=parity-reports]
* }</pre> * }</pre>
* *
* <p>{@code --privilege} 前置条件:已跑 bootstrap-privilege.sql(建 SYS_FILTERRULE/中间表 +
* 为 EIP4PT_TASK/PROJECT/CUSTOMER 各配 1 条 {@code CREATEBY = {CURRENTUSERID}} 规则)。
*
* <p>对每个实体:直连 JDBC SELECT(基线) vs 引擎 REST list(被测) 逐行逐列 diff, * <p>对每个实体:直连 JDBC SELECT(基线) vs 引擎 REST list(被测) 逐行逐列 diff,
* 报告写 {@code parity-reports/parity-YYYYMMDD-HHmmss.json} + {@code .md}。 * 报告写 {@code parity-reports/parity-YYYYMMDD-HHmmss.json} + {@code .md}。
* 退出码:全一致=0,有差异=2,运行错误=1。 * 退出码:全一致=0,有差异=2,运行错误=1。
@@ -49,6 +53,12 @@ public final class ParityCli {
SimpleDriverDataSource ds = new SimpleDriverDataSource( SimpleDriverDataSource ds = new SimpleDriverDataSource(
new org.postgresql.Driver(), jdbcUrl, user, pass == null ? "" : pass); new org.postgresql.Driver(), jdbcUrl, user, pass == null ? "" : pass);
// C2 数据行级权限对拍模式:--privilege
if (opt.containsKey("privilege")) {
int code = runPrivilege(engine, ds, outDir);
System.exit(code);
}
List<String> entities = new ArrayList<>(); List<String> entities = new ArrayList<>();
if (opt.containsKey("seed")) { if (opt.containsKey("seed")) {
System.out.println("[seed] 建实体 + 灌数据(固定种子 " + ParitySeeder.SEED + ")..."); System.out.println("[seed] 建实体 + 灌数据(固定种子 " + ParitySeeder.SEED + ")...");
@@ -100,6 +110,127 @@ public final class ParityCli {
System.exit(cleanCount == entities.size() ? 0 : 2); System.exit(cleanCount == entities.size() ? 0 : 2);
} }
/**
* C2 数据行级权限对拍:对 3 个受控实体 × 3 个用户跑正例逐行 diff,并断言负例(错误角色被拒)。
* 写 {@code privilege-parity-*.json/.md} 报告。退出码:全一致且负例全部被拒=0,否则=2。
*/
private static int runPrivilege(String engine, javax.sql.DataSource ds, Path outDir) throws Exception {
System.out.println("=== C2 数据行级权限对拍(--privilege)===");
PrivilegeCheckRunner runner = new PrivilegeCheckRunner(engine, ds);
// 正例:引擎过滤 vs JDBC 同语义基线,逐行 diff
List<DiffReport> reports = runner.runAllPositive();
int cleanCount = 0;
long totalRows = 0;
for (DiffReport r : reports) {
totalRows += r.leftRowCount;
boolean clean = r.isClean();
if (clean) {
cleanCount++;
}
System.out.printf(" 正例 %-26s 行=%-4d 一致率=%.4f %s%n",
r.label, r.leftRowCount, r.consistencyRate(), clean ? "OK" : "DIFF");
}
// 负例:错误角色访问每个受控实体 → 期望 HTTP 非 200(PrivilegeException)
List<String> negTables = new ArrayList<>(PrivilegeCheckRunner.CONTROLLED.keySet());
negTables.sort(String::compareTo);
int negPass = 0;
Map<String, Integer> negStatus = new LinkedHashMap<>();
for (String t : negTables) {
int code = runner.checkNegativeStatus(t, "ROLE_NOBODY");
negStatus.put(t, code);
boolean rejected = code != 200;
if (rejected) {
negPass++;
}
System.out.printf(" 负例 %-26s 错误角色 ROLE_NOBODY → HTTP=%d %s%n",
t, code, rejected ? "REJECTED(OK)" : "NOT-REJECTED(FAIL)");
}
boolean allPositiveClean = cleanCount == reports.size();
boolean allNegativeRejected = negPass == negTables.size();
boolean ok = allPositiveClean && allNegativeRejected;
String ts = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
Path json = outDir.resolve("privilege-parity-" + ts + ".json");
Path md = outDir.resolve("privilege-parity-" + ts + ".md");
writePrivilegeJson(json, reports, negStatus, cleanCount, totalRows, allNegativeRejected);
writePrivilegeMarkdown(md, reports, negStatus, cleanCount, totalRows, allNegativeRejected);
System.out.println("\n=== C2 汇总 ===");
System.out.println("受控实体: " + negTables.size() + " (" + negTables + ")");
System.out.println("正例(实体×用户): " + reports.size() + ",全一致: " + cleanCount);
System.out.println("总比对行数(JDBC 基线侧): " + totalRows);
System.out.println("负例(错误角色被拒): " + negPass + "/" + negTables.size());
System.out.println("结果: " + (ok ? "✅ 全部通过" : "⚠️ 存在失败"));
System.out.println("报告: " + json + " / " + md);
return ok ? 0 : 2;
}
private static void writePrivilegeJson(Path path, List<DiffReport> reports,
Map<String, Integer> negStatus, int cleanCount,
long totalRows, boolean allNegativeRejected) throws Exception {
ObjectMapper m = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
Map<String, Object> root = new LinkedHashMap<>();
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("mode", "privilege");
summary.put("positiveCases", reports.size());
summary.put("positiveClean", cleanCount);
summary.put("totalRows", totalRows);
summary.put("positiveConsistencyRate", reports.isEmpty() ? 1.0 : (double) cleanCount / reports.size());
summary.put("negativeStatus", negStatus);
summary.put("allNegativeRejected", allNegativeRejected);
summary.put("allPass", cleanCount == reports.size() && allNegativeRejected);
root.put("summary", summary);
List<Map<String, Object>> rs = new ArrayList<>();
for (DiffReport r : reports) {
rs.add(r.toSummaryMap());
}
root.put("positive", rs);
Files.writeString(path, m.writeValueAsString(root));
}
private static void writePrivilegeMarkdown(Path path, List<DiffReport> reports,
Map<String, Integer> negStatus, int cleanCount,
long totalRows, boolean allNegativeRejected) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("# C2 数据行级权限对拍报告\n\n");
sb.append("- 正例(受控实体 × 用户): ").append(reports.size())
.append(",全一致: ").append(cleanCount).append("\n");
sb.append("- 总比对行数(JDBC 基线侧): ").append(totalRows).append("\n");
sb.append("- 正例逐行一致率: ")
.append(String.format("%.4f", reports.isEmpty() ? 1.0 : (double) cleanCount / reports.size()))
.append(cleanCount == reports.size() ? " ✅ 全部逐行一致" : " ⚠️ 存在差异").append("\n");
sb.append("- 负例(错误角色被拒): ").append(allNegativeRejected ? "✅ 全部被拒" : "⚠️ 存在未拒").append("\n\n");
sb.append("## 正例:引擎行级过滤 vs JDBC 同语义基线\n\n");
sb.append("| 实体[用户] | 行数 | 内容差异 | 仅JDBC | 仅引擎 | 一致率 | 结果 |\n");
sb.append("|---|---|---|---|---|---|---|\n");
for (DiffReport r : reports) {
sb.append("| ").append(r.label).append(" | ").append(r.leftRowCount)
.append(" | ").append(r.mismatches.size())
.append(" | ").append(r.onlyInLeft.size())
.append(" | ").append(r.onlyInRight.size())
.append(" | ").append(String.format("%.4f", r.consistencyRate()))
.append(" | ").append(r.isClean() ? "✅" : "⚠️").append(" |\n");
}
sb.append("\n## 负例:错误角色 ROLE_NOBODY 访问受控实体\n\n");
sb.append("| 实体 | HTTP 状态 | 期望 | 结果 |\n|---|---|---|---|\n");
for (Map.Entry<String, Integer> e : negStatus.entrySet()) {
boolean rejected = e.getValue() != 200;
sb.append("| ").append(e.getKey()).append(" | ").append(e.getValue())
.append(" | 非200(PrivilegeException) | ")
.append(rejected ? "✅ 被拒" : "⚠️ 未拒").append(" |\n");
}
sb.append("\n");
for (DiffReport r : reports) {
if (!r.isClean()) {
sb.append(r.toMarkdown()).append("\n");
}
}
Files.writeString(path, sb.toString());
}
private static List<String> listEip4ptEntities(javax.sql.DataSource ds) { private static List<String> listEip4ptEntities(javax.sql.DataSource ds) {
return new org.springframework.jdbc.core.JdbcTemplate(ds).queryForList( return new org.springframework.jdbc.core.JdbcTemplate(ds).queryForList(
"SELECT tablename FROM sys_entity WHERE tablename LIKE ? AND isactive=1 ORDER BY tablename", "SELECT tablename FROM sys_entity WHERE tablename LIKE ? AND isactive=1 ORDER BY tablename",

View File

@@ -0,0 +1,106 @@
package com.eip4.platform.parity.selfcheck;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import com.eip4.platform.parity.diff.DiffReport;
import com.eip4.platform.parity.diff.RowDiff;
/**
* C2 数据行级权限对拍执行器。
*
* <p>对每个受控实体(已在 bootstrap-privilege.sql 配 {@code CREATEBY = {CURRENTUSERID}} 规则),
* 用每个测试用户(USER_ALICE/USER_BOB/USER_CAROL)分别:
* <ul>
* <li><b>被测侧</b>:{@code GET /api/entity/{t}/list?asUser=U&roles=R} —— 经引擎行级过滤路径
* (POJOCRUDServiceImpl.listSelect → dataPrivilegeService.getWhereClause 拼 WHERE)。</li>
* <li><b>基线侧</b>:直连 JDBC {@code SELECT * FROM t WHERE createby = 'U'} —— 同语义 ground truth。</li>
* </ul>
* 两侧 {@link RowDiff} 逐行逐列比对,一致率 100% 即证明引擎过滤语义与物理事实逐字节对齐。
*
* <p>另含<b>负例</b>:用错误角色访问受控实体 → 引擎应抛 PrivilegeException(HTTP 非 200);
* 断言之以证明"规则存在但无角色命中 → 拒绝"语义。
*/
public class PrivilegeCheckRunner {
/** 受控实体 → 其规则关联的角色(与 bootstrap-privilege.sql 一致)。 */
public static final Map<String, String> CONTROLLED = Map.of(
"EIP4PT_TASK", "ROLE_TASK",
"EIP4PT_PROJECT", "ROLE_PROJECT",
"EIP4PT_CUSTOMER", "ROLE_CUSTOMER");
/** 测试用户(与 bootstrap-privilege.sql 的 CREATEBY 重分区一致)。 */
public static final List<String> USERS = List.of("USER_ALICE", "USER_BOB", "USER_CAROL");
private final EngineHttpClient engine;
private final JdbcResultReader jdbc;
public PrivilegeCheckRunner(String engineBaseUrl, DataSource dataSource) {
this.engine = new EngineHttpClient(engineBaseUrl);
this.jdbc = new JdbcResultReader(dataSource);
}
/** 一个 (实体, 用户) 正例:引擎过滤结果 vs JDBC 同语义基线,逐行 diff。 */
public DiffReport checkPositive(String table, String user) {
String t = table.toUpperCase();
String role = CONTROLLED.get(t);
String label = t + "[" + user + "]";
List<Map<String, Object>> left;
List<Map<String, Object>> right;
try {
// 基线:同语义 WHERE createby = user(PG bpchar 比较忽略尾空格,与引擎 P.CREATEBY='user' 一致)
left = jdbc.query("SELECT * FROM " + t + " WHERE createby = ?", user);
} catch (Exception e) {
return error(label, "JDBC 基线读失败: " + e.getMessage());
}
try {
String q = "asUser=" + user + "&roles=" + role;
right = engine.listAll(t, q);
} catch (Exception e) {
return error(label, "引擎过滤路径失败: " + e.getMessage());
}
String pk = t + "_ID";
List<String> keys = (!left.isEmpty() && left.get(0).containsKey(pk))
? List.of(pk)
: RowDiff.inferKeyColumns(t, left.isEmpty() ? right : left);
return new RowDiff(keys).diff(label, left, right);
}
/**
* 负例断言:用错误角色访问受控实体,引擎应抛 PrivilegeException(HTTP 非 200)。
* @return 实际 HTTP 状态码(期望 != 200)
*/
public int checkNegativeStatus(String table, String wrongRole) {
try {
return engine.statusOf(table.toUpperCase(),
"asUser=USER_ALICE&roles=" + wrongRole);
} catch (Exception e) {
// 网络层异常也视作"被拒绝"
return -1;
}
}
/** 跑全部受控实体 × 全部用户的正例,返回 DiffReport 列表。 */
public List<DiffReport> runAllPositive() {
List<DiffReport> out = new ArrayList<>();
List<String> tables = new ArrayList<>(CONTROLLED.keySet());
tables.sort(String::compareTo);
for (String t : tables) {
for (String u : USERS) {
out.add(checkPositive(t, u));
}
}
return out;
}
private static DiffReport error(String label, String msg) {
DiffReport r = new DiffReport(label);
DiffReport.RowMismatch mm = new DiffReport.RowMismatch("RUNNER_ERROR");
mm.cells.add(new DiffReport.CellDiff("error", null, msg, "VALUE"));
r.mismatches.add(mm);
return r;
}
}

View File

@@ -0,0 +1,190 @@
-- ============================================================================
-- eip4-platform M0 任务 C2 —— 数据行级权限自举 bootstrap-privilege.sql
-- ----------------------------------------------------------------------------
-- 用途:在已跑过 bootstrap-sys.sql + ParitySeeder(21 个 EIP4PT_* 实体)的本地
-- eip4m0 库上,追加「数据行级过滤」所需的平台表 + 自描述元数据 + 过滤规则,
-- 让保真层移植的 DataPrivilegeServiceImpl 能真实走引擎读路径产生行级过滤。
--
-- 口径权威来源(已逐一核对源码):
-- * 触发点 = POJOCRUDServiceImpl.listSelectSpecialCol:仅当 ctx.CURRENTUSER != ADMIN
-- 时调 dataPrivilegeService.getWhereClause(ctx, table),把返回的 " AND (...)" 拼进 WHERE。
-- * 规则装载 = DataPrivilegeServiceImpl.getEntityDataFilterRule:
-- listSelect(SYS_FILTERRULE WHERE ENTITYID=<实体id>) → 逐行 loadPOJO(...,true)
-- → DataFilterHelper.converToDataFilterRule(po):取 po.get_Value("ROLES")(List<String>)
-- 与 po.get_Value("FILTERRULE")(Conditional JSON)。
-- * ROLES 多值落地 = LIST 显示类型 + 中间表(MIDTABLE):
-- ROLES 列 referenceid='LIST',referencevalue 指向一条 SYS_REFERENCEVALUE,
-- 该 referencevalue.ENTITYID→SYS_FILTERRULEROLE(中间表),ENTITYATTRIBUTEID→FILTERRULEID(回引列)。
-- loadPOJO(isHierarchical=true) 的 hierarchicalQuery 对 LIST 列:
-- SELECT * FROM SYS_FILTERRULEROLE WHERE FILTERRULEID=<规则id>
-- 收集"另一列"ROLEID 的全部值 → List<String> 设回 ROLES。
-- (见 POInfo.getReferenceValueTable/ColumnName + POJOServiceImpl.hierarchicalQuery
-- 第 1256-1262 行:中间表恰好 2 列,referenceColumn 之外那列即取值列。)
-- * 过滤 SQL = getFilterSql:CURRENTUSER 类型 → "P.<列> <sign> 'currentUserValue'"
-- (StringUtil.TO_STRING 自动加单引号);本脚本用 CREATEBY = {CURRENTUSERID} 等值过滤。
--
-- 纪律:可重复执行(DROP IF EXISTS + DELETE 幂等);表名/列名小写。规则 ENTITYID 动态
-- SELECT 自 sys_entity(EIP4PT_* 实体 id 由 ParitySeeder 随机生成,不可硬编码)。
-- ============================================================================
-- ---------------------------------------------------------------------------
-- 0. 清理(逆序)
-- 规则/中间表行随物理表 DROP CASCADE 一并清除,无需单独 DELETE
-- (首次执行表尚不存在,DELETE 会报错)。
-- ---------------------------------------------------------------------------
DROP TABLE IF EXISTS sys_filterrulerole CASCADE;
DROP TABLE IF EXISTS sys_filterrule CASCADE;
-- 元数据残留(本脚本固定 id 前缀)
DELETE FROM sys_referencevalue WHERE sys_referencevalue_id LIKE 'd1000000-%';
DELETE FROM sys_reference WHERE sys_reference_id LIKE 'c1000000-%';
DELETE FROM sys_entityattribute WHERE entityid IN
('e1000000-0000-0000-0000-000000000008', 'e1000000-0000-0000-0000-000000000009');
DELETE FROM sys_entity WHERE sys_entity_id IN
('e1000000-0000-0000-0000-000000000008', 'e1000000-0000-0000-0000-000000000009');
-- ===========================================================================
-- 1. 物理表
-- ===========================================================================
-- 1.1 SYS_FILTERRULE —— 行级过滤规则主表
-- ROLES 是 LIST(多值)列,不落物理列(值在中间表 SYS_FILTERRULEROLE);
-- 物理表只含标量列。FILTERRULE 存 Conditional[] 的 JSON 文本(用 text 防超长)。
CREATE TABLE sys_filterrule (
sys_filterrule_id character(36) NOT NULL,
entityid character(36),
filterrule text,
isactive integer DEFAULT 1 NOT NULL,
createtime bigint,
updatetime bigint,
createby character(36),
updateby character(36),
version integer DEFAULT 0 NOT NULL,
PRIMARY KEY (sys_filterrule_id)
);
-- 1.2 SYS_FILTERRULEROLE —— 规则↔角色 中间表(MIDTABLE,恰 2 列:回引列 + 取值列)
-- 引擎 hierarchicalQuery 对 ROLES(LIST)列查此表,收集 ROLEID 列得 List<String>。
CREATE TABLE sys_filterrulerole (
filterruleid character(36) NOT NULL,
roleid character varying(100) NOT NULL
);
-- ===========================================================================
-- 2. 自描述元数据
-- 固定实体 id:
-- SYS_FILTERRULE = e1000000-0000-0000-0000-000000000008
-- SYS_FILTERRULEROLE = e1000000-0000-0000-0000-000000000009(tabletype=2 中间表)
-- ===========================================================================
INSERT INTO sys_entity
(sys_entity_id, name, description, tablename, entitytype, isview, ischangelog,
accesslevel, tabletype, isactive, createtime, updatetime, createby, updateby, version)
VALUES
('e1000000-0000-0000-0000-000000000008', '数据过滤规则', '行级数据权限过滤规则', 'SYS_FILTERRULE', 'a0000000-0000-0000-0000-0000000000ff', 0, 0, 0, 0, 1, 0, 0, 'ADMIN', 'ADMIN', 0),
('e1000000-0000-0000-0000-000000000009', '过滤规则角色', '规则与角色的中间表', 'SYS_FILTERRULEROLE', 'a0000000-0000-0000-0000-0000000000ff', 0, 0, 0, 2, 1, 0, 0, 'ADMIN', 'ADMIN', 0);
-- --- SYS_FILTERRULE 的自描述属性 ---
-- ROLES 列:referenceid='LIST' 使 displayType=LIST/ColumnClass=List.class;
-- referencevalue 指向下方 SYS_REFERENCEVALUE(d1000000-...-0001),
-- 解析到中间表 SYS_FILTERRULEROLE + 回引列 FILTERRULEID。
INSERT INTO sys_entityattribute
(sys_entityattribute_id, entityid, columnname, displayname, referenceid, referencevalue,
ismandatory, isreadonly, iskey, isidentifier, iscombidentifier, isentitydisplay,
entitydisplayseq, fieldlength, isactive, createby, updateby, version)
VALUES
('a1000000-0000-0000-0000-000000000801', 'e1000000-0000-0000-0000-000000000008', 'SYS_FILTERRULE_ID', '主键', 'CHAR', NULL, 1, 1, 1, 0, 0, 0, 1, 36, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000802', 'e1000000-0000-0000-0000-000000000008', 'ENTITYID', '实体ID', 'CHAR', NULL, 1, 0, 0, 0, 0, 1, 2, 36, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000803', 'e1000000-0000-0000-0000-000000000008', 'FILTERRULE', '过滤条件', 'NVARCHAR', NULL, 0, 0, 0, 0, 0, 0, 3, 4000, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000804', 'e1000000-0000-0000-0000-000000000008', 'ROLES', '角色', 'LIST', 'd1000000-0000-0000-0000-000000000001', 0, 0, 0, 0, 0, 0, 4, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000805', 'e1000000-0000-0000-0000-000000000008', 'ISACTIVE', '是否有效', 'BOOLEAN', NULL, 0, 0, 0, 0, 0, 0, 5, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000806', 'e1000000-0000-0000-0000-000000000008', 'VERSION', '版本', 'INTEGER', NULL, 0, 0, 0, 0, 0, 0, 6, 0, 1, 'ADMIN', 'ADMIN', 0);
-- --- SYS_FILTERRULEROLE 的自描述属性(恰 2 列;seq 决定 getColumnName(0/1) 次序) ---
-- 第 0 列 = FILTERRULEID(回引 SYS_FILTERRULE),第 1 列 = ROLEID(取值列)。
INSERT INTO sys_entityattribute
(sys_entityattribute_id, entityid, columnname, displayname, referenceid, referencevalue,
ismandatory, isreadonly, iskey, isidentifier, iscombidentifier, isentitydisplay,
entitydisplayseq, fieldlength, isactive, createby, updateby, version)
VALUES
('a1000000-0000-0000-0000-000000000901', 'e1000000-0000-0000-0000-000000000009', 'FILTERRULEID', '规则ID', 'CHAR', NULL, 1, 0, 0, 0, 0, 0, 1, 36, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000902', 'e1000000-0000-0000-0000-000000000009', 'ROLEID', '角色', 'NVARCHAR', NULL, 1, 0, 0, 0, 0, 1, 2, 100, 1, 'ADMIN', 'ADMIN', 0);
-- ===========================================================================
-- 3. ROLES(LIST)列的引用值映射
-- SYS_REFERENCEVALUE.ENTITYID → SYS_FILTERRULEROLE 实体(得中间表表名)
-- SYS_REFERENCEVALUE.ENTITYATTRIBUTEID → FILTERRULEID 属性(得回引列名)
-- (引擎 DataDicServiceImpl.getEntityTableNameByReferenceValue /
-- getColumnNameByReferenceValue 两条 JOIN 解析。)
-- 另需一条 SYS_REFERENCE(entityid=中间表实体)以满足通用引用约束。
-- ===========================================================================
INSERT INTO sys_reference
(sys_reference_id, entityid, name, description, isactive, createtime, updatetime, createby, updateby, version)
VALUES
('c1000000-0000-0000-0000-000000000001', 'e1000000-0000-0000-0000-000000000009', 'ROLES->SYS_FILTERRULEROLE', 'C2 行级权限角色引用', 1, 0, 0, 'ADMIN', 'ADMIN', 0);
INSERT INTO sys_referencevalue
(sys_referencevalue_id, entityid, entityattributeid, name, isactive, createtime, updatetime, createby, updateby, version)
VALUES
('d1000000-0000-0000-0000-000000000001', 'e1000000-0000-0000-0000-000000000009', 'a1000000-0000-0000-0000-000000000901', 'ROLES 中间表映射', 1, 0, 0, 'ADMIN', 'ADMIN', 0);
-- ===========================================================================
-- 4. 受控实体的 CREATEBY 重分区 —— 让 "CREATEBY = {CURRENTUSERID}" 过滤可判别
-- ParitySeeder 把 50 行 CREATEBY 全置 'ADMIN';这里按 BIZNO 后缀的数字奇偶/三分,
-- 把 CREATEBY 改成 USER_ALICE / USER_BOB / USER_CAROL,使不同用户视角看到不同子集。
-- 确定性:对每实体的 50 行,按 ctid 行序号 % 3 分配,可重复执行(结果幂等)。
-- ===========================================================================
-- EIP4PT_TASK
WITH ranked AS (
SELECT eip4pt_task_id, row_number() OVER (ORDER BY eip4pt_task_id) AS rn FROM eip4pt_task
)
UPDATE eip4pt_task t SET createby = CASE (r.rn % 3)
WHEN 0 THEN 'USER_ALICE' WHEN 1 THEN 'USER_BOB' ELSE 'USER_CAROL' END
FROM ranked r WHERE t.eip4pt_task_id = r.eip4pt_task_id;
-- EIP4PT_PROJECT
WITH ranked AS (
SELECT eip4pt_project_id, row_number() OVER (ORDER BY eip4pt_project_id) AS rn FROM eip4pt_project
)
UPDATE eip4pt_project t SET createby = CASE (r.rn % 3)
WHEN 0 THEN 'USER_ALICE' WHEN 1 THEN 'USER_BOB' ELSE 'USER_CAROL' END
FROM ranked r WHERE t.eip4pt_project_id = r.eip4pt_project_id;
-- EIP4PT_CUSTOMER
WITH ranked AS (
SELECT eip4pt_customer_id, row_number() OVER (ORDER BY eip4pt_customer_id) AS rn FROM eip4pt_customer
)
UPDATE eip4pt_customer t SET createby = CASE (r.rn % 3)
WHEN 0 THEN 'USER_ALICE' WHEN 1 THEN 'USER_BOB' ELSE 'USER_CAROL' END
FROM ranked r WHERE t.eip4pt_customer_id = r.eip4pt_customer_id;
-- ===========================================================================
-- 5. 过滤规则种子 —— 为 3 个 EIP4PT_* 实体各配 1 条行级过滤规则
-- 规则语义:CREATEBY = {CURRENTUSERID}(只看自己创建的行)。
-- 规则 ENTITYID 动态取自 sys_entity(实体 id 不可硬编码)。
-- FILTERRULE = Conditional[] 的 JSON:type=CURRENTUSERID 触发 getFilterSql
-- 的 "P.CREATEBY ='<currentUser>'" 分支。
-- 每条规则关联 1 个角色(ROLE_TASK / ROLE_PROJECT / ROLE_CUSTOMER),经中间表落地。
-- ===========================================================================
-- 规则固定 id 前缀 f1000000-,便于幂等清理
INSERT INTO sys_filterrule (sys_filterrule_id, entityid, filterrule, isactive, createtime, updatetime, createby, updateby, version)
SELECT 'f1000000-0000-0000-0000-000000000001', sys_entity_id,
'[{"preConditional":"CREATEBY","sign":"=","backConditional":"{CURRENTUSERID}","type":"CURRENTUSERID","op":null}]',
1, 0, 0, 'ADMIN', 'ADMIN', 0
FROM sys_entity WHERE tablename = 'EIP4PT_TASK';
INSERT INTO sys_filterrule (sys_filterrule_id, entityid, filterrule, isactive, createtime, updatetime, createby, updateby, version)
SELECT 'f1000000-0000-0000-0000-000000000002', sys_entity_id,
'[{"preConditional":"CREATEBY","sign":"=","backConditional":"{CURRENTUSERID}","type":"CURRENTUSERID","op":null}]',
1, 0, 0, 'ADMIN', 'ADMIN', 0
FROM sys_entity WHERE tablename = 'EIP4PT_PROJECT';
INSERT INTO sys_filterrule (sys_filterrule_id, entityid, filterrule, isactive, createtime, updatetime, createby, updateby, version)
SELECT 'f1000000-0000-0000-0000-000000000003', sys_entity_id,
'[{"preConditional":"CREATEBY","sign":"=","backConditional":"{CURRENTUSERID}","type":"CURRENTUSERID","op":null}]',
1, 0, 0, 'ADMIN', 'ADMIN', 0
FROM sys_entity WHERE tablename = 'EIP4PT_CUSTOMER';
-- 规则↔角色(中间表):每条规则 1 个角色
INSERT INTO sys_filterrulerole (filterruleid, roleid) VALUES
('f1000000-0000-0000-0000-000000000001', 'ROLE_TASK'),
('f1000000-0000-0000-0000-000000000002', 'ROLE_PROJECT'),
('f1000000-0000-0000-0000-000000000003', 'ROLE_CUSTOMER');