From de105a15743642389735600e69855328fb822354 Mon Sep 17 00:00:00 2001 From: sgibb Date: Tue, 12 Mar 2024 01:44:03 -0400 Subject: [PATCH] Validate URI has host unless scheme is `forward` Fixes gh-2919 --- .../cloud/gateway/route/Route.java | 4 ++++ .../cloud/gateway/route/RouteTests.java | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/route/Route.java b/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/route/Route.java index b4a30a5ec5..9193e0e3a7 100644 --- a/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/route/Route.java +++ b/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/route/Route.java @@ -187,6 +187,10 @@ public B uri(URI uri) { this.uri = uri; String scheme = this.uri.getScheme(); Assert.hasText(scheme, "The parameter [" + this.uri + "] format is incorrect, scheme can not be empty"); + if (!scheme.equalsIgnoreCase("forward")) { + Assert.hasText(this.uri.getHost(), + "The parameter [" + this.uri + "] format is incorrect, host can not be empty"); + } if (this.uri.getPort() < 0 && scheme.startsWith("http")) { // default known http ports int port = this.uri.getScheme().equals("https") ? 443 : 80; diff --git a/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/route/RouteTests.java b/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/route/RouteTests.java index 5d3f882564..b43800d8de 100644 --- a/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/route/RouteTests.java +++ b/spring-cloud-gateway-server/src/test/java/org/springframework/cloud/gateway/route/RouteTests.java @@ -54,6 +54,26 @@ public void nullScheme() { .isInstanceOf(IllegalArgumentException.class); } + @Test + public void emptyHostFails() { + assertThatThrownBy(() -> Route.async().id("1").predicate(exchange -> true).uri("localhost:8080")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void noOpWorks() { + Route route = Route.async().id("1").predicate(exchange -> true).uri("no://op").build(); + + assertThat(route.getUri()).hasScheme("no").hasHost("op"); + } + + @Test + public void forwardWorks() { + Route route = Route.async().id("1").predicate(exchange -> true).uri("forward:/some/path").build(); + + assertThat(route.getUri()).hasScheme("forward").hasPath("/some/path"); + } + @Test public void defaultMetadataToEmpty() { Route route = Route.async().id("1").predicate(exchange -> true).uri("http://acme.com:8080").build();