Skip to content

Commit a924411

Browse files
committed
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
1 parent 622ccc5 commit a924411

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,16 @@ public static UriComponentsBuilder fromUriString(String uri) {
236236
}
237237
builder.scheme(scheme);
238238
if (opaque) {
239-
String ssp = uri.substring(scheme.length()).substring(1);
239+
String ssp = uri.substring(scheme.length() + 1);
240240
if (StringUtils.hasLength(fragment)) {
241241
ssp = ssp.substring(0, ssp.length() - (fragment.length() + 1));
242242
}
243243
builder.schemeSpecificPart(ssp);
244244
}
245245
else {
246+
if (StringUtils.hasLength(scheme) && !StringUtils.hasLength(host)) {
247+
throw new IllegalArgumentException("[" + uri + "] is not a valid URI");
248+
}
246249
builder.userInfo(userInfo);
247250
builder.host(host);
248251
if (StringUtils.hasLength(port)) {

spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java

+6
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,12 @@ void fromUriStringIPv6Host() {
219219
assertThat(resultIPv4compatible.getHost()).isEqualTo("[::192.168.1.1]");
220220
}
221221

222+
@Test
223+
void fromUriStringInvalidIPv6Host() {
224+
assertThatIllegalArgumentException().isThrownBy(() ->
225+
UriComponentsBuilder.fromUriString("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource"));
226+
}
227+
222228
@Test // SPR-11970
223229
void fromUriStringNoPathWithReservedCharInQuery() {
224230
UriComponents result = UriComponentsBuilder.fromUriString("https://example.com?foo=bar@baz").build();

0 commit comments

Comments
 (0)