Browse Source

Falls back to unresolved hostname in ForwardedHeadersFilter to prevent NPE.

fixes gh-1601
pull/1613/head
Tobias Gies 5 years ago committed by Spencer Gibb
parent
commit
5f48b1d253
No known key found for this signature in database
GPG Key ID: 7788A47380690861
  1. 5
      spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/headers/ForwardedHeadersFilter.java
  2. 24
      spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/headers/ForwardedHeadersFilterTests.java

5
spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/headers/ForwardedHeadersFilter.java

@ -116,7 +116,10 @@ public class ForwardedHeadersFilter implements HttpHeadersFilter, Ordered { @@ -116,7 +116,10 @@ public class ForwardedHeadersFilter implements HttpHeadersFilter, Ordered {
InetSocketAddress remoteAddress = request.getRemoteAddress();
if (remoteAddress != null) {
String forValue = remoteAddress.getAddress().getHostAddress();
// If remoteAddress is unresolved, calling getHostAddress() would cause a
// NullPointerException.
String forValue = remoteAddress.isUnresolved() ? remoteAddress.getHostName()
: remoteAddress.getAddress().getHostAddress();
int port = remoteAddress.getPort();
if (port >= 0) {
forValue = forValue + ":" + port;

24
spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/headers/ForwardedHeadersFilterTests.java

@ -131,6 +131,30 @@ public class ForwardedHeadersFilterTests { @@ -131,6 +131,30 @@ public class ForwardedHeadersFilterTests {
.containsEntry("for", "\"10.0.0.1:80\"");
}
@Test
public void unresolvedRemoteAddressFallsBackToHostName() throws UnknownHostException {
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
.remoteAddress(
InetSocketAddress.createUnresolved("unresolvable-hostname", 80))
.build();
ForwardedHeadersFilter filter = new ForwardedHeadersFilter();
HttpHeaders headers = filter.filter(request.getHeaders(),
MockServerWebExchange.from(request));
assertThat(headers.get(FORWARDED_HEADER)).hasSize(1);
List<Forwarded> forwardeds = ForwardedHeadersFilter
.parse(headers.get(FORWARDED_HEADER));
assertThat(forwardeds).hasSize(1);
Forwarded forwarded = forwardeds.get(0);
assertThat(forwarded.getValues()).containsEntry("proto", "http")
.containsEntry("for", "\"unresolvable-hostname:80\"");
}
@Test
public void forwardedParsedCorrectly() {
String[] valid = new String[] { "for=\"_gazonk\"",

Loading…
Cancel
Save