From fc867dc1107249ae12bdca975edcd3967355856d Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 11 Jun 2026 00:10:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20C2=20=E6=95=B0=E6=8D=AE=E6=9D=83?= =?UTF-8?q?=E9=99=90=E6=9C=80=E5=B0=8F=E7=9C=9F=E5=AE=9E=E7=8E=B0=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E6=A1=A9(=E4=BF=9D=E7=9C=9F=E5=B1=82=E5=8E=9F?= =?UTF-8?q?=E6=A0=B7=E7=A7=BB=E6=A4=8D)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把 framework 的数据行级权限实现原样移植进保真层 platform-legacy-core (包名 com.dsasp 不动),删除 platform-auth 的不过滤桩,由真实现接管 @Service("dataPrivilegeService"): - DataPrivilegeServiceImpl(226 行):getWhereClause 按 ctx.ROLES 匹配 SYS_FILTERRULE 规则拼 " AND (...)" 行级过滤;无角色命中抛 PrivilegeException。 - DataFilterHelper(110 行):FILTERRULE(Conditional[])JSON 互转,用 Jackson 1.x (org.codehaus.jackson),保真纪律不改写为 Jackson 2;父 pom + legacy-core pom 引入 jackson-mapper-asl:1.9.13。 - MethodSecurityInterceptor 注解(被 Impl 引用,原样拷入)。 - 删除 StubDataPrivilegeService(与新 Bean 重名冲突);platform-auth/README.md 说明 dataPrivilegeService 已由保真层接管、P2 在此做组织/权限整体真实现。 - 单测 9 用例(DataFilterHelper JSON 互转 + getWhereClause 拼接,假 POJOInfo)。 全模块 mvn clean install 通过,ArchUnit 仍绿。 Co-Authored-By: Claude Fable 5 --- platform-auth/README.md | 18 ++ .../auth/stub/StubDataPrivilegeService.java | 33 -- platform-legacy-core/pom.xml | 5 + .../bean/MethodSecurityInterceptor.java | 18 ++ .../privilege/bean/DataFilterHelper.java | 110 +++++++ .../service/DataPrivilegeServiceImpl.java | 226 ++++++++++++++ .../server/privilege/DataPrivilegeTest.java | 202 ++++++++++++ .../dsasp/server/privilege/FakePOInfo.java | 291 ++++++++++++++++++ pom.xml | 7 + 9 files changed, 877 insertions(+), 33 deletions(-) create mode 100644 platform-auth/README.md delete mode 100644 platform-auth/src/main/java/com/eip4/platform/auth/stub/StubDataPrivilegeService.java create mode 100644 platform-legacy-core/src/main/java/com/dsasp/server/common/privilege/bean/MethodSecurityInterceptor.java create mode 100644 platform-legacy-core/src/main/java/com/dsasp/server/privilege/bean/DataFilterHelper.java create mode 100644 platform-legacy-core/src/main/java/com/dsasp/server/privilege/service/DataPrivilegeServiceImpl.java create mode 100644 platform-legacy-core/src/test/java/com/dsasp/server/privilege/DataPrivilegeTest.java create mode 100644 platform-legacy-core/src/test/java/com/dsasp/server/privilege/FakePOInfo.java diff --git a/platform-auth/README.md b/platform-auth/README.md new file mode 100644 index 0000000..22b5948 --- /dev/null +++ b/platform-auth/README.md @@ -0,0 +1,18 @@ +# platform-auth + +P2 模块:组织机构 / 权限 / 数据权限的整体真实现承载处(当前主要为 PoC 桩 + 少量已被保真层接管的能力)。 + +## dataPrivilegeService 已由保真层(platform-legacy-core)真实现接管 + +M0 任务 C2 已删除本模块原先的 `StubDataPrivilegeService`(返回 `null`、不过滤), +改由 platform-legacy-core 中原样移植的 `com.dsasp.server.privilege.service.DataPrivilegeServiceImpl` +(`@Service("dataPrivilegeService")`)提供**行级数据过滤的原版语义**:按 `ctx.ROLES` 匹配 +`SYS_FILTERRULE` 规则,拼接 `AND (...)` 过滤子句注入 `POJOCRUDService.listSelect` 的 WHERE。 +两个同名 `dataPrivilegeService` Bean 会冲突,故本模块不再保留该桩。 + +P2 在本模块做的是**组织/权限整体真实现**:补齐组织机构数据源(部门/机构/用户-角色关系)、 +角色与数据过滤规则的管理 UI 与维护接口。C2 的实现即原版引擎语义本身,P2 在其之上接入真实 +组织数据与管理界面,不改写过滤算法。 + +其余桩(StubFileService / StubSystemLogManager / StubDataOperatorLog / StubProjectSwitchService) +保留,按 P2 节奏逐项真实现替换。 diff --git a/platform-auth/src/main/java/com/eip4/platform/auth/stub/StubDataPrivilegeService.java b/platform-auth/src/main/java/com/eip4/platform/auth/stub/StubDataPrivilegeService.java deleted file mode 100644 index 6a38498..0000000 --- a/platform-auth/src/main/java/com/eip4/platform/auth/stub/StubDataPrivilegeService.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.eip4.platform.auth.stub; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.springframework.stereotype.Service; - -import com.dsasp.server.common.privilege.bean.DataFilterRule; -import com.dsasp.server.common.privilege.service.DataPrivilegeService; - -/** - * WS1 桩:数据行级权限。PoC 阶段不过滤(返回 null 等价于 admin 视角), - * 接口签名原样保留,P2 阶段以 EIP3 真实现替换。 - */ -@Service("dataPrivilegeService") -public class StubDataPrivilegeService implements DataPrivilegeService { - - @Override - public String getWhereClause(Properties ctx, String tableName) { - return null; - } - - @Override - public void saveOrUpdateDataPrivilege(String entityId, List list, Properties ctx) { - // PoC 不持久化权限规则 - } - - @Override - public List getEntityDataFilterRule(String entityId) { - return new ArrayList<>(); - } -} diff --git a/platform-legacy-core/pom.xml b/platform-legacy-core/pom.xml index 5f1ee2e..8a18f25 100644 --- a/platform-legacy-core/pom.xml +++ b/platform-legacy-core/pom.xml @@ -19,6 +19,11 @@ org.apache.groovygroovy-jsr223 joda-timejoda-time org.jsonjson + + org.codehaus.jacksonjackson-mapper-asl jakarta.servletjakarta.servlet-apiprovided + + org.springframework.bootspring-boot-starter-testtest diff --git a/platform-legacy-core/src/main/java/com/dsasp/server/common/privilege/bean/MethodSecurityInterceptor.java b/platform-legacy-core/src/main/java/com/dsasp/server/common/privilege/bean/MethodSecurityInterceptor.java new file mode 100644 index 0000000..da09c59 --- /dev/null +++ b/platform-legacy-core/src/main/java/com/dsasp/server/common/privilege/bean/MethodSecurityInterceptor.java @@ -0,0 +1,18 @@ +package com.dsasp.server.common.privilege.bean; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface MethodSecurityInterceptor { + + String name(); + String tableName(); + boolean isControl(); + +} diff --git a/platform-legacy-core/src/main/java/com/dsasp/server/privilege/bean/DataFilterHelper.java b/platform-legacy-core/src/main/java/com/dsasp/server/privilege/bean/DataFilterHelper.java new file mode 100644 index 0000000..3eac8c0 --- /dev/null +++ b/platform-legacy-core/src/main/java/com/dsasp/server/privilege/bean/DataFilterHelper.java @@ -0,0 +1,110 @@ +package com.dsasp.server.privilege.bean; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.node.ArrayNode; + +import com.dsasp.server.common.dataDic.bean.GeneralPOJO; +import com.dsasp.server.common.exception.ValidationException; +import com.dsasp.server.common.privilege.bean.Conditional; +import com.dsasp.server.common.privilege.bean.DataFilterRule; +import com.dsasp.server.common.util.StringUtil; + +public class DataFilterHelper { + + /** + * + * @param po + * entity rule + * @param info + * entity info + * @return + */ + public static DataFilterRule converToDataFilterRule(GeneralPOJO po) { + if (po != null && "SYS_FILTERRULE".equals(po.get_TableName())) { + DataFilterRule rule = new DataFilterRule(); + rule.setId(po.get_ID()); + List roles = (List) po.get_Value("ROLES"); + //无效设置,忽略 + if(roles == null || roles.size() == 0){ + return null; + } + rule.setRoles(roles); + rule.setConditionalList(convertJsonToConditional((String) po + .get_Value("FILTERRULE"))); + return rule; + } + return null; + } + + public static List convertJsonToConditional(String json) { + ObjectMapper objectMapper = new ObjectMapper(); + List list = new ArrayList(); + try { + if (!StringUtil.isEmpty(json) && !"null".equals(json)) { + JsonNode rules = objectMapper.readTree(json); + ArrayNode nodes = (ArrayNode) rules; + if (nodes != null && nodes.size() > 0) { + for (JsonNode node : nodes) { + Conditional c = objectMapper.readValue(node, + Conditional.class); + list.add(c); + } + } + } + } catch (Exception ex) { + throw new ValidationException("规则解析异常"); + } + return list; + } + + public static Map convertDataRuleToMap(DataFilterRule rule, + String entityId) { + Map map = new HashMap(); + map.put("SYS_FILTERRULE_ID", rule.getId()); + map.put("ENTITYID", entityId); + map.put("ROLES", rule.getRoles()); + map.put("FILTERRULE", + convertConditionalToJson(rule.getConditionalList())); + return map; + } + + private static String convertConditionalToJson(List list) { + ObjectMapper objectMapper = new ObjectMapper(); + StringWriter w = new StringWriter(); + try { + objectMapper.writeValue(w, list); + return w.getBuffer().toString(); + } catch (Exception ex) { + throw new ValidationException("条件转换json格式异常"); + } + } + + // public static void main(String[] args) { + // ObjectMapper objectMapper = new ObjectMapper(); + // Conditional c = new Conditional(); + // c.setBackConditional("3"); + // c.setOp("OR"); + // c.setPreConditional("field"); + // c.setSign("="); + // c.setType("NUMBER"); + // try { + // StringBuffer a = new StringBuffer(); + // StringWriter w = new StringWriter(); + // objectMapper.writeValue(w, c); + // objectMapper.writeValue(System.out, c); + // + // Conditional cond = objectMapper.readValue(w.getBuffer().toString(), + // Conditional.class); + // System.out.println(cond); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // } +} diff --git a/platform-legacy-core/src/main/java/com/dsasp/server/privilege/service/DataPrivilegeServiceImpl.java b/platform-legacy-core/src/main/java/com/dsasp/server/privilege/service/DataPrivilegeServiceImpl.java new file mode 100644 index 0000000..bbed6bb --- /dev/null +++ b/platform-legacy-core/src/main/java/com/dsasp/server/privilege/service/DataPrivilegeServiceImpl.java @@ -0,0 +1,226 @@ +package com.dsasp.server.privilege.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.dsasp.server.common.core.service.SpringBeanOsgiServices; +import com.dsasp.server.common.dataDic.bean.AbstractPOJOInfo; +import com.dsasp.server.common.dataDic.bean.GeneralPOJO; +import com.dsasp.server.common.dataDic.bean.POJOInfo; +import com.dsasp.server.common.dataDic.bean.SysConfig; +import com.dsasp.server.common.dataDic.service.POJOCRUDService; +import com.dsasp.server.common.exception.PrivilegeException; +import com.dsasp.server.common.exception.ValidationException; +import com.dsasp.server.common.privilege.bean.Conditional; +import com.dsasp.server.common.privilege.bean.DataFilterRule; +import com.dsasp.server.common.privilege.bean.MethodSecurityInterceptor; +import com.dsasp.server.common.privilege.service.DataPrivilegeService; +import com.dsasp.server.common.user.service.LoggedInUser; +import com.dsasp.server.common.util.StringUtil; +import com.dsasp.server.common.util.UserSession; +import com.dsasp.server.privilege.bean.DataFilterHelper; + +@Service(value = "dataPrivilegeService") +@Transactional +public class DataPrivilegeServiceImpl implements DataPrivilegeService { + + + @Override + public String getWhereClause(Properties ctx, String tableName) { + if (!tableName.startsWith("SYS_FILTERRULE")) { + POJOInfo info = AbstractPOJOInfo.getPOInfo(tableName); + List list = info.getDataFilterRules(); + if (list != null && list.size() > 0) { + StringBuffer filterBuffer = new StringBuffer(); + String tableDisplayName = info.getTableDisplayName(); + filterBuffer.append(" AND ( "); + boolean first = true; + for (DataFilterRule rule : list) { + if (isContainsRole((List) ctx.get("ROLES"), + rule.getRoles(), tableDisplayName)) { + if(first){ + first = false; + }else{ + filterBuffer.append(" OR "); + } + List condition = rule.getConditionalList(); + getFilterSql(filterBuffer, condition, info, ctx); + } + } + filterBuffer.append(" )"); + if (first) { + throw new PrivilegeException("没有" + tableDisplayName + + "数据访问权限"); + } else { + return filterBuffer.toString(); + } + } + } + return null; + } + + private void getFilterSql(StringBuffer filterBuffer, List list, POJOInfo info, Properties ctx){ + if(list == null || list.size() == 0){ + filterBuffer.append(" ( 1=1 ) "); + return ; + } + filterBuffer.append(" ("); + for(Conditional cond : list){ + if(StringUtil.isEmpty(cond.getPreConditional()) + || StringUtil.isEmpty(cond.getSign()) + || StringUtil.isEmpty(cond.getType()) + || StringUtil.isEmpty(cond.getBackConditional())){ + filterBuffer.append(" 1=1 ").append(GeneralPOJO.AND); + continue; + } + filterBuffer.append(" P.").append(cond.getPreConditional()).append(" "); + String currentUser = StringUtil.TO_STRING((String)ctx.get(LoggedInUser.CURRENTUSER), 0); + String currentDepart = StringUtil.TO_STRING((String)ctx.get(LoggedInUser.CURRENTDEPART), 0); + String currentOrg = StringUtil.TO_STRING((String)ctx.get(LoggedInUser.CURRENTORG), 0); + if(Conditional.CURRENTUSER.equals(cond.getType())){ + filterBuffer.append(cond.getSign()).append(currentUser); + }else if(Conditional.CURRENTUSERDEPART.equals(cond.getType())){ + filterBuffer.append(cond.getSign()).append(currentDepart); + }else if(Conditional.CURRENTUSERORG.equals(cond.getType())){ + filterBuffer.append(cond.getSign()).append(currentOrg); + }else if(Conditional.SPECIALDEPART.equals(cond.getType()) || Conditional.SPECAILORG.equals(cond.getType())){ + filterBuffer.append(Conditional.SIGN_CONTAIN).append("(").append(StringUtil.convertSplitStrToSql(cond.getBackConditional())).append(") "); + }else{ + String ownProjectWhere = " (" + SysConfig.getConfigValue("com.dsasp.server.privilege.OwnProjectWhere") + ") "; + ownProjectWhere = ownProjectWhere.replaceAll("\\{" + Conditional.CURRENTUSER + "\\}", currentUser); + if(Conditional.OWNNERPROJECT.equals(cond.getType())){ + filterBuffer.append(Conditional.SIGN_CONTAIN).append(ownProjectWhere); + } else { + filterBuffer + .append(cond.getSign()) + .append(cond + .getBackConditional() + .replaceAll( + "\\{" + Conditional.CURRENTUSER + "\\}", + currentUser) + .replaceAll( + "\\{" + Conditional.CURRENTUSERDEPART + + "\\}", currentDepart) + .replaceAll( + "\\{" + Conditional.CURRENTUSERORG + + "\\}", currentOrg).replaceAll("\\{" + Conditional.OWNNERPROJECT + "\\}", ownProjectWhere)); + } + } + if(!StringUtil.isEmpty(cond.getOp())){ + filterBuffer.append(" ").append(cond.getOp()); + } + + } + String str = filterBuffer.toString(); + if(str.endsWith(GeneralPOJO.AND)){ + filterBuffer.delete(str.length() - 4, str.length()); + }else if(str.endsWith(GeneralPOJO.OR)){ + filterBuffer.delete(str.length() - 3, str.length()); + } + filterBuffer.append(")"); + } + + private boolean isContainsRole(List currentUserRoles, List ruleRoles, String tableDisplayName){ + if(ruleRoles != null){ + for(String role : ruleRoles){ + if(currentUserRoles.contains(role)){ + return true; + } + } + }else{ + throw new PrivilegeException(tableDisplayName + "权限配置错误"); + } + return false; + } + + + /** + * update the entity all rules + * @param entityId + * @param list + * @param ctx + */ + @Override + @MethodSecurityInterceptor(name="数据过滤保存", tableName="SYS_FILTERRULE", isControl = true) + public void saveOrUpdateDataPrivilege(String entityId, + List list, Properties ctx) { + POJOCRUDService service = (POJOCRUDService) SpringBeanOsgiServices + .getInstance().getBeanByName("pojoCRUDService"); + List oldList = getEntityDataFilterRule(entityId); + if (list != null && list.size() > 0) { + for (DataFilterRule rule : list) { + boolean isExist = removeContain(oldList, rule); + Map map = DataFilterHelper + .convertDataRuleToMap(rule, entityId); + List roles = rule.getRoles(); + if(roles == null || roles.size() == 0){ + throw new ValidationException("角色不能为空"); + } + if (isExist) { + service.update(map, "SYS_FILTERRULE", ctx); + } else { + service.save(map, "SYS_FILTERRULE", ctx); + } + } + } + if (oldList != null && oldList.size() > 0) { + for (DataFilterRule rule : oldList) { + service.delete(rule.getId(), "SYS_FILTERRULE", ctx); + } + } + AbstractPOJOInfo.setChangePOInfo(entityId); + } + + /** + * does old list contain the rule , if contains is true and remove it from old list , or is false + * @param oldList + * @param rule + * @return + */ + private boolean removeContain(List oldList, + DataFilterRule rule) { + if (oldList != null && oldList.size() > 0 && rule != null + && !StringUtil.isEmpty(rule.getId())) { + for (DataFilterRule oldRule : oldList) { + if (rule.getId().equals(oldRule.getId())) { + oldList.remove(oldRule); + return true; + } + } + } + return false; + } + + /** + * get entity all the rule + * @param entityId + * @return + */ + @Override + public List getEntityDataFilterRule(String entityId){ + List rules = new ArrayList(); + POJOCRUDService service = (POJOCRUDService)SpringBeanOsgiServices.getInstance().getBeanByName("pojoCRUDService"); + Map map = new HashMap(); + map.put("ENTITYID", entityId); + List list = (List)service.listSelect(map, "SYS_FILTERRULE", UserSession.getAdmin()).get(POJOCRUDService.LIST_RESULT); + if(list != null && list.size() > 0){ + GeneralPOJO entity = service.loadPOJO(entityId, "SYS_ENTITY", null, false); + for (GeneralPOJO po : list) { + po = service + .loadPOJO(po.get_ID(), "SYS_FILTERRULE", UserSession.get(), true); + DataFilterRule rule = DataFilterHelper.converToDataFilterRule(po); + if(rule != null){ + rules.add(rule); + } + } + } + return rules; + } + +} diff --git a/platform-legacy-core/src/test/java/com/dsasp/server/privilege/DataPrivilegeTest.java b/platform-legacy-core/src/test/java/com/dsasp/server/privilege/DataPrivilegeTest.java new file mode 100644 index 0000000..66020c7 --- /dev/null +++ b/platform-legacy-core/src/test/java/com/dsasp/server/privilege/DataPrivilegeTest.java @@ -0,0 +1,202 @@ +package com.dsasp.server.privilege; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +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.exception.PrivilegeException; +import com.dsasp.server.common.privilege.bean.Conditional; +import com.dsasp.server.common.privilege.bean.DataFilterRule; +import com.dsasp.server.common.user.service.LoggedInUser; +import com.dsasp.server.privilege.bean.DataFilterHelper; +import com.dsasp.server.privilege.service.DataPrivilegeServiceImpl; + +/** + * C2 数据权限单测:覆盖 DataFilterHelper 的 FILTERRULE JSON 互转, + * 以及 DataPrivilegeServiceImpl.getWhereClause 的行级过滤 SQL 拼接(用假 POJOInfo, + * 经反射注入 AbstractPOJOInfo 的静态缓存,绕开 DB 与 Spring 上下文)。 + * + *

过滤条件仅用 CURRENTUSER / CURRENTUSERDEPART 类型(等值),不触达 SysConfig/OWNNERPROJECT, + * 以保证纯逻辑可单测。语义与 framework 原版一致。 + */ +class DataPrivilegeTest { + + private final DataPrivilegeServiceImpl service = new DataPrivilegeServiceImpl(); + + @BeforeEach + @SuppressWarnings("unchecked") + void clearCache() throws Exception { + Field f = AbstractPOJOInfo.class.getDeclaredField("s_cache"); + f.setAccessible(true); + ((Map) f.get(null)).clear(); + } + + @SuppressWarnings("unchecked") + private void putPoInfo(String table, FakePOInfo info) throws Exception { + Field f = AbstractPOJOInfo.class.getDeclaredField("s_cache"); + f.setAccessible(true); + ((Map) f.get(null)).put(table, info); + } + + private static Conditional cond(String col, String sign, String type, String back, String op) { + Conditional c = new Conditional(); + c.setPreConditional(col); + c.setSign(sign); + c.setType(type); + c.setBackConditional(back); + c.setOp(op); + return c; + } + + private static DataFilterRule rule(List roles, Conditional... conds) { + DataFilterRule r = new DataFilterRule(); + r.setId("rule-" + roles); + r.setRoles(roles); + r.setConditionalList(Arrays.asList(conds)); + return r; + } + + private static Properties ctx(String user, String depart, String... roles) { + Properties p = new Properties(); + p.setProperty(LoggedInUser.CURRENTUSER, user); + if (depart != null) { + p.setProperty(LoggedInUser.CURRENTDEPART, depart); + } + List roleList = new ArrayList<>(Arrays.asList(roles)); + p.put("ROLES", roleList); + return p; + } + + // ---- DataFilterHelper JSON 互转 ---- + + @Test + void json_roundtrip_singleConditional() { + List in = List.of(cond("OWNER", "=", Conditional.CURRENTUSER, "{CURRENTUSERID}", "AND")); + DataFilterRule r = new DataFilterRule(); + r.setId("r1"); + r.setRoles(List.of("ROLE_A")); + r.setConditionalList(in); + + Map map = DataFilterHelper.convertDataRuleToMap(r, "entity-1"); + String json = (String) map.get("FILTERRULE"); + assertNotNull(json); + + List out = DataFilterHelper.convertJsonToConditional(json); + assertEquals(1, out.size()); + assertEquals("OWNER", out.get(0).getPreConditional()); + assertEquals("=", out.get(0).getSign()); + assertEquals(Conditional.CURRENTUSER, out.get(0).getType()); + assertEquals("{CURRENTUSERID}", out.get(0).getBackConditional()); + assertEquals("AND", out.get(0).getOp()); + } + + @Test + void json_roundtrip_multipleConditionals() { + List in = List.of( + cond("OWNER", "=", Conditional.CURRENTUSER, "{CURRENTUSERID}", "OR"), + cond("DEPT", "=", Conditional.CURRENTUSERDEPART, "{CURRENTUSERDEPARTID}", null)); + DataFilterRule r = new DataFilterRule(); + r.setId("r2"); + r.setRoles(List.of("ROLE_A", "ROLE_B")); + r.setConditionalList(in); + + Map map = DataFilterHelper.convertDataRuleToMap(r, "entity-2"); + assertEquals("entity-2", map.get("ENTITYID")); + assertEquals("r2", map.get("SYS_FILTERRULE_ID")); + assertEquals(List.of("ROLE_A", "ROLE_B"), map.get("ROLES")); + + List out = DataFilterHelper.convertJsonToConditional((String) map.get("FILTERRULE")); + assertEquals(2, out.size()); + assertEquals("DEPT", out.get(1).getPreConditional()); + assertEquals(Conditional.CURRENTUSERDEPART, out.get(1).getType()); + } + + @Test + void json_emptyAndNull_returnEmptyList() { + assertTrue(DataFilterHelper.convertJsonToConditional(null).isEmpty()); + assertTrue(DataFilterHelper.convertJsonToConditional("").isEmpty()); + assertTrue(DataFilterHelper.convertJsonToConditional("null").isEmpty()); + assertTrue(DataFilterHelper.convertJsonToConditional("[]").isEmpty()); + } + + @Test + void json_invalid_throwsValidationException() { + assertThrows(RuntimeException.class, + () -> DataFilterHelper.convertJsonToConditional("{ not json")); + } + + // ---- getWhereClause 拼接 ---- + + @Test + void whereClause_singleRoleMatch_currentUser() throws Exception { + FakePOInfo info = new FakePOInfo("EIP4PT_TASK", "任务", + List.of(rule(List.of("ROLE_TASK"), + cond("OWNER", "=", Conditional.CURRENTUSER, "{CURRENTUSERID}", null)))); + putPoInfo("EIP4PT_TASK", info); + + String where = service.getWhereClause(ctx("USER_ALICE", null, "ROLE_TASK"), "EIP4PT_TASK"); + assertNotNull(where); + assertTrue(where.startsWith(" AND ("), where); + assertTrue(where.contains("P.OWNER"), where); + assertTrue(where.contains("='USER_ALICE'"), where); + } + + @Test + void whereClause_multipleRulesMatched_orJoined() throws Exception { + FakePOInfo info = new FakePOInfo("EIP4PT_PROJECT", "项目", + List.of( + rule(List.of("ROLE_X"), + cond("OWNER", "=", Conditional.CURRENTUSER, "{CURRENTUSERID}", null)), + rule(List.of("ROLE_Y"), + cond("DEPTCODE", "=", Conditional.CURRENTUSERDEPART, "{CURRENTUSERDEPARTID}", null)))); + putPoInfo("EIP4PT_PROJECT", info); + + // 两条规则的角色都命中 → OR 连接两个子句 + String where = service.getWhereClause( + ctx("USER_BOB", "DEPT_10", "ROLE_X", "ROLE_Y"), "EIP4PT_PROJECT"); + assertNotNull(where); + assertTrue(where.contains("P.OWNER"), where); + assertTrue(where.contains("='USER_BOB'"), where); + assertTrue(where.contains(" OR "), where); + assertTrue(where.contains("P.DEPTCODE"), where); + assertTrue(where.contains("='DEPT_10'"), where); + } + + @Test + void whereClause_noRoleMatch_throwsPrivilegeException() throws Exception { + FakePOInfo info = new FakePOInfo("EIP4PT_CUSTOMER", "客户", + List.of(rule(List.of("ROLE_ONLY"), + cond("OWNER", "=", Conditional.CURRENTUSER, "{CURRENTUSERID}", null)))); + putPoInfo("EIP4PT_CUSTOMER", info); + + PrivilegeException ex = assertThrows(PrivilegeException.class, + () -> service.getWhereClause(ctx("USER_X", null, "ROLE_OTHER"), "EIP4PT_CUSTOMER")); + assertTrue(ex.getMessage().contains("客户"), ex.getMessage()); + } + + @Test + void whereClause_filterRuleTable_returnsNull() throws Exception { + // SYS_FILTERRULE 自身不被过滤(避免递归) + assertNull(service.getWhereClause(ctx("ADMIN", null, "ANY"), "SYS_FILTERRULE")); + } + + @Test + void whereClause_noRulesEntity_returnsNull() throws Exception { + FakePOInfo info = new FakePOInfo("EIP4PT_ORDER", "订单", List.of()); + putPoInfo("EIP4PT_ORDER", info); + assertNull(service.getWhereClause(ctx("USER_X", null, "ROLE_A"), "EIP4PT_ORDER")); + } +} diff --git a/platform-legacy-core/src/test/java/com/dsasp/server/privilege/FakePOInfo.java b/platform-legacy-core/src/test/java/com/dsasp/server/privilege/FakePOInfo.java new file mode 100644 index 0000000..1d90f1a --- /dev/null +++ b/platform-legacy-core/src/test/java/com/dsasp/server/privilege/FakePOInfo.java @@ -0,0 +1,291 @@ +package com.dsasp.server.privilege; + +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; + +/** + * C2 单测用的最小 POJOInfo 假实现:只承载 getDataFilterRules / getTableDisplayName / + * getTableName,其余方法不在 getWhereClause 路径上,抛 UnsupportedOperationException 即可。 + * 经反射注入 AbstractPOJOInfo 的静态缓存后,getWhereClause 即可在无 DB/Spring 时运行。 + */ +class FakePOInfo implements POJOInfo { + + private final String tableName; + private final String displayName; + private final List rules; + + FakePOInfo(String tableName, String displayName, List rules) { + this.tableName = tableName; + this.displayName = displayName; + this.rules = rules; + } + + @Override + public List getDataFilterRules() { + return rules; + } + + @Override + public String getTableDisplayName() { + return displayName; + } + + @Override + public String getTableName() { + return tableName; + } + + // ---- 以下方法不在 getWhereClause 路径上 ---- + + private static UnsupportedOperationException nope() { + return new UnsupportedOperationException("FakePOInfo: 不应被 getWhereClause 路径调用"); + } + + @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 getColumnCount() { + 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 getColumnName(int index) { + 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 cols) { + throw nope(); + } + + @Override + public StringBuffer buildSelect(List 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 getRules() { + throw nope(); + } + + @Override + public int getTableType() { + throw nope(); + } + + @Override + public String getKeyColumnName() { + throw nope(); + } + + @Override + public List 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(); + } +} diff --git a/pom.xml b/pom.xml index d20d564..3c052f4 100644 --- a/pom.xml +++ b/pom.xml @@ -102,6 +102,13 @@ json 20240303 + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.13 + org.springdoc