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
This commit is contained in:
Sam Brannen 2020-06-29 18:36:21 +02:00
parent 622ccc5767
commit a92441186c
2 changed files with 10 additions and 1 deletions

View File

@ -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)) {

View File

@ -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();