diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java index a235b59dd99..d6e0d369f61 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java @@ -130,4 +130,25 @@ private InetAddress parseAddress(String address) { } } + /** + * Returns the IP address this Matcher is matching for without mask bits. + * @return a string representation of the IP address + */ + public String getHostAddress() { + return this.requiredAddress.getHostAddress(); + } + + /** + * Returns the mask bits of the IP address this Matcher is matching for + * @return a string representation of the mask bits + */ + public String getMaskBits() { + return String.valueOf(this.nMaskBits); + } + + @Override + public String toString() { + return "IpAddressMatcher[" + getHostAddress() + "/" + getMaskBits() + "]"; + } + } diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java index ce702bfbebb..83841ccd180 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java @@ -21,9 +21,7 @@ import org.springframework.mock.web.MockHttpServletRequest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatException; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.*; /** * @author Luke Taylor @@ -153,4 +151,32 @@ public void constructorWhenRequiredAddressIsEmptyThenThrowsIllegalArgumentExcept .withMessage("ipAddress cannot be empty"); } + // gh-16693 + @Test + public void getHostAddressReturnsCorrectIPv4String() { + IpAddressMatcher matcher = new IpAddressMatcher("192.168.1.0/24"); + assertThat(matcher.getHostAddress()).isEqualTo("192.168.1.0"); + } + + // gh-16693 + @Test + public void getMaskBitsIp4ReturnsCorrectString() { + IpAddressMatcher matcher = new IpAddressMatcher("192.168.1.0/24"); + assertThat(matcher.getMaskBits()).isEqualTo("24"); + } + + // gh-16693 + @Test + public void getHostAddressReturnsCorrectIPv6String() { + IpAddressMatcher matcher = new IpAddressMatcher("fe80::21f:5bff:fe33:bd68"); + assertThat(matcher.getHostAddress()).isEqualTo("fe80:0:0:0:21f:5bff:fe33:bd68"); + } + + // gh-16693 + @Test + public void getMaskBitsIp6ReturnsCorrectString() { + IpAddressMatcher matcher = new IpAddressMatcher("2001:DB8::/48"); + assertThat(matcher.getMaskBits()).isEqualTo("48"); + } + }