package com.dms.service; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.InetAddress; import org.junit.jupiter.api.Test; /** * 登录 IP 匹配单测(契约1.28,对齐 _ip_matches): * 精确IP / CIDR / 起止范围三分支与脏数据安全降级(非法字面量不触发 DNS)。 */ class LoginIpServiceMatchesTest { private static boolean matches(String sourceIp, String value) throws Exception { return LoginIpService.matchesValue(InetAddress.getByName(sourceIp), value); } @Test void 精确IP匹配() throws Exception { assertTrue(matches("10.10.10.10", "10.10.10.10")); assertFalse(matches("10.10.10.11", "10.10.10.10")); } @Test void CIDR网段匹配() throws Exception { assertTrue(matches("192.168.10.55", "192.168.10.0/24")); assertFalse(matches("192.168.11.55", "192.168.10.0/24")); } @Test void 范围匹配含两端边界() throws Exception { assertTrue(matches("172.16.20.10", "172.16.20.10-172.16.20.99")); assertTrue(matches("172.16.20.55", "172.16.20.10-172.16.20.99")); assertTrue(matches("172.16.20.99", "172.16.20.10-172.16.20.99")); assertFalse(matches("172.16.20.100", "172.16.20.10-172.16.20.99")); assertFalse(matches("172.16.20.9", "172.16.20.10-172.16.20.99")); } @Test void 范围版本不一致时拒绝() throws Exception { assertFalse(matches("::1", "172.16.20.10-172.16.20.99")); } @Test void 脏数据按不匹配处理() throws Exception { // 均为非法字面量,InetAddress 直接抛 UnknownHostException,不触发 DNS 查询 assertFalse(matches("10.10.10.10", "1.2.3.4.5")); assertFalse(matches("10.10.10.10", "1.1.1.1-2.2.2.2-3.3.3.3")); assertFalse(matches("10.10.10.10", "1.1.1.1-")); assertFalse(matches("10.10.10.10", "10.0.0.0/xx")); } @Test void 豁免仅限内置admin用户名() { // 登录IP豁免语义:仅内置 admin 用户名豁免,管理员类别(roleCode=ADMIN)不再整体豁免 com.dms.model.UserEntity builtIn = new com.dms.model.UserEntity(); builtIn.setUsername("admin"); builtIn.setRoleCode("ADMIN"); assertTrue(AdminPermission.isSuperAdmin(builtIn)); com.dms.model.UserEntity orgAdmin = new com.dms.model.UserEntity(); orgAdmin.setUsername("org_admin"); orgAdmin.setRoleCode("ADMIN"); assertFalse(AdminPermission.isSuperAdmin(orgAdmin)); } }