LoginIpServiceMatchesTest.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.dms.service;
  2. import static org.junit.jupiter.api.Assertions.assertFalse;
  3. import static org.junit.jupiter.api.Assertions.assertTrue;
  4. import java.net.InetAddress;
  5. import org.junit.jupiter.api.Test;
  6. /**
  7. * 登录 IP 匹配单测(契约1.28,对齐 _ip_matches):
  8. * 精确IP / CIDR / 起止范围三分支与脏数据安全降级(非法字面量不触发 DNS)。
  9. */
  10. class LoginIpServiceMatchesTest {
  11. private static boolean matches(String sourceIp, String value) throws Exception {
  12. return LoginIpService.matchesValue(InetAddress.getByName(sourceIp), value);
  13. }
  14. @Test
  15. void 精确IP匹配() throws Exception {
  16. assertTrue(matches("10.10.10.10", "10.10.10.10"));
  17. assertFalse(matches("10.10.10.11", "10.10.10.10"));
  18. }
  19. @Test
  20. void CIDR网段匹配() throws Exception {
  21. assertTrue(matches("192.168.10.55", "192.168.10.0/24"));
  22. assertFalse(matches("192.168.11.55", "192.168.10.0/24"));
  23. }
  24. @Test
  25. void 范围匹配含两端边界() throws Exception {
  26. assertTrue(matches("172.16.20.10", "172.16.20.10-172.16.20.99"));
  27. assertTrue(matches("172.16.20.55", "172.16.20.10-172.16.20.99"));
  28. assertTrue(matches("172.16.20.99", "172.16.20.10-172.16.20.99"));
  29. assertFalse(matches("172.16.20.100", "172.16.20.10-172.16.20.99"));
  30. assertFalse(matches("172.16.20.9", "172.16.20.10-172.16.20.99"));
  31. }
  32. @Test
  33. void 范围版本不一致时拒绝() throws Exception {
  34. assertFalse(matches("::1", "172.16.20.10-172.16.20.99"));
  35. }
  36. @Test
  37. void 脏数据按不匹配处理() throws Exception {
  38. // 均为非法字面量,InetAddress 直接抛 UnknownHostException,不触发 DNS 查询
  39. assertFalse(matches("10.10.10.10", "1.2.3.4.5"));
  40. assertFalse(matches("10.10.10.10", "1.1.1.1-2.2.2.2-3.3.3.3"));
  41. assertFalse(matches("10.10.10.10", "1.1.1.1-"));
  42. assertFalse(matches("10.10.10.10", "10.0.0.0/xx"));
  43. }
  44. @Test
  45. void 豁免仅限内置admin用户名() {
  46. // 登录IP豁免语义:仅内置 admin 用户名豁免,管理员类别(roleCode=ADMIN)不再整体豁免
  47. com.dms.model.UserEntity builtIn = new com.dms.model.UserEntity();
  48. builtIn.setUsername("admin");
  49. builtIn.setRoleCode("ADMIN");
  50. assertTrue(AdminPermission.isSuperAdmin(builtIn));
  51. com.dms.model.UserEntity orgAdmin = new com.dms.model.UserEntity();
  52. orgAdmin.setUsername("org_admin");
  53. orgAdmin.setRoleCode("ADMIN");
  54. assertFalse(AdminPermission.isSuperAdmin(orgAdmin));
  55. }
  56. }