From a92441186c76e97a96f53fb8c4f46fa04e6b23b6 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 29 Jun 2020 18:36:21 +0200 Subject: [PATCH] Check for valid IPv6 host in UriComponentsBuilder.fromUriString PR gh-358 introduced a "scheme but no host" check in the fromHttpUrl() method in UriComponentsBuilder, but a similar check was not added to fromUriString() at that time. This commit introduces a "scheme but no host" check in fromUriString() to align with the functionality in fromHttpUrl(). Note, however that the regular expressions used to match against the hostname or IP address are inexact and still permit invalid host names or IP addresses. True validation of the host portion of the URI is out of scope for this commit. Closes gh-25334 --- .../org/springframework/web/util/UriComponentsBuilder.java | 5 ++++- .../springframework/web/util/UriComponentsBuilderTests.java | 6 ++++++ 2 files changed, 10 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 be865004ad..f5c8163713 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 @@ -236,13 +236,16 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable { } builder.scheme(scheme); if (opaque) { - String ssp = uri.substring(scheme.length()).substring(1); + String ssp = uri.substring(scheme.length() + 1); if (StringUtils.hasLength(fragment)) { ssp = ssp.substring(0, ssp.length() - (fragment.length() + 1)); } builder.schemeSpecificPart(ssp); } else { + if (StringUtils.hasLength(scheme) && !StringUtils.hasLength(host)) { + throw new IllegalArgumentException("[" + uri + "] is not a valid URI"); + } builder.userInfo(userInfo); builder.host(host); if (StringUtils.hasLength(port)) { 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 d19c2740a2..34cebf5e0d 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 @@ -219,6 +219,12 @@ class UriComponentsBuilderTests { assertThat(resultIPv4compatible.getHost()).isEqualTo("[::192.168.1.1]"); } + @Test + void fromUriStringInvalidIPv6Host() { + assertThatIllegalArgumentException().isThrownBy(() -> + UriComponentsBuilder.fromUriString("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource")); + } + @Test // SPR-11970 void fromUriStringNoPathWithReservedCharInQuery() { UriComponents result = UriComponentsBuilder.fromUriString("https://example.com?foo=bar@baz").build();