From e35fe33b72b2865ce22f1b6ab00b7fb821239c7c Mon Sep 17 00:00:00 2001 From: Brian Clozel Date: Tue, 8 Jun 2021 15:26:13 +0200 Subject: [PATCH] Revisit fix for gh-26905 in UriComponentsBuilder This commit revisits the recently updated `PORT_PATTERN` in `UriComponentsBuilder`. The fix introduced in gh-26905 fails with ambiguous URL patterns, especially when the port and path parts of the pattern are hard to differentiate, for example "https://localhost:{port}{path}". This commit reinstates the previous behavior without undoing the actual fix. The only limitation introduced here is the fact that only a single pattern variable is allowed for the port pattern part. Fixes gh-27039 --- .../springframework/web/util/UriComponentsBuilder.java | 2 +- .../web/util/UriComponentsBuilderTests.java | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java index 39d689be6724..f814955fe2b3 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java @@ -85,7 +85,7 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable { private static final String HOST_PATTERN = "(" + HOST_IPV6_PATTERN + "|" + HOST_IPV4_PATTERN + ")"; - private static final String PORT_PATTERN = "([^/?#]*)"; + private static final String PORT_PATTERN = "(\\{[^}]+}?|[^/?#]*)"; private static final String PATH_PATTERN = "([^?#]*)"; diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 2da0fc9b2857..3b8a5168cfb2 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -1297,4 +1297,14 @@ void verifyInvalidPort() { .isInstanceOf(NumberFormatException.class); } + @Test // gh-27039 + void expandPortAndPathWithoutSeparator() { + URI uri = UriComponentsBuilder + .fromUriString("ws://localhost:{port}{path}") + .buildAndExpand(7777, "/test") + .toUri(); + assertThat(uri.toString()).isEqualTo("ws://localhost:7777/test"); + } + + }