Retain brackets for IPV6 address in MockHttpServletRequest
According to the Javadoc for ServletRequest's getServerName() method, when the `Host` header is set, the server name is "the value of the part before ':' in the Host header value ...". For a value representing an IPV6 address such as `[::ffff:abcd:abcd]`, the enclosing square brackets should therefore not be stripped from the enclosed IPV6 address. However, the changes made in conjunction with gh-16704 introduced a regression in Spring Framework 4.1 for the getServerName() method in MockHttpServletRequest by stripping the enclosing brackets from the IPV6 address in the `Host` header. Similarly, the changes made in conjunction with gh-20686 introduced a regression in Spring Framework 4.3.13 and 5.0.2 in the getRequestURL() method in MockHttpServletRequest by delegating to the getServerName() method which strips the enclosing brackets. This commit fixes the implementation of getServerName() so that the enclosing brackets are no longer stripped from an IPV6 address in the `Host` header. The implementation of getRequestURL() is therefore also fixed. In addition, in order to avoid a NullPointerException, the implementations of getServerName() and getServerPort() now assert that an IPV6 address present in the `Host` header correctly contains an opening and closing bracket and throw an IllegalStateException if that is not the case. Closes gh-24916
This commit is contained in:
@@ -668,11 +668,14 @@ public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
@Override
|
||||
public String getServerName() {
|
||||
String host = getHeader(HttpHeaders.HOST);
|
||||
String rawHostHeader = getHeader(HttpHeaders.HOST);
|
||||
String host = rawHostHeader;
|
||||
if (host != null) {
|
||||
host = host.trim();
|
||||
if (host.startsWith("[")) {
|
||||
host = host.substring(1, host.indexOf(']'));
|
||||
int indexOfClosingBracket = host.indexOf(']');
|
||||
Assert.state(indexOfClosingBracket > -1, () -> "Invalid Host header: " + rawHostHeader);
|
||||
host = host.substring(0, indexOfClosingBracket + 1);
|
||||
}
|
||||
else if (host.contains(":")) {
|
||||
host = host.substring(0, host.indexOf(':'));
|
||||
@@ -690,12 +693,15 @@ public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
@Override
|
||||
public int getServerPort() {
|
||||
String host = getHeader(HttpHeaders.HOST);
|
||||
String rawHostHeader = getHeader(HttpHeaders.HOST);
|
||||
String host = rawHostHeader;
|
||||
if (host != null) {
|
||||
host = host.trim();
|
||||
int idx;
|
||||
if (host.startsWith("[")) {
|
||||
idx = host.indexOf(':', host.indexOf(']'));
|
||||
int indexOfClosingBracket = host.indexOf(']');
|
||||
Assert.state(indexOfClosingBracket > -1, () -> "Invalid Host header: " + rawHostHeader);
|
||||
idx = host.indexOf(':', indexOfClosingBracket);
|
||||
}
|
||||
else {
|
||||
idx = host.indexOf(':');
|
||||
|
||||
Reference in New Issue
Block a user