Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion url/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2025,7 +2025,17 @@ impl Url {
let scheme_type = SchemeType::from(self.scheme());

if let Some(host) = host {
if host.is_empty() && scheme_type.is_special() && !scheme_type.is_file() {
// An empty host is only valid for a non-special scheme that has no
// credentials and no port. Setting it otherwise would produce a
// serialization (e.g. `foo://user@/` or `foo://:1/`) that the parser
// itself rejects with `EmptyHost`, breaking the parse/serialize
// roundtrip. Mirror the parser here.
if host.is_empty()
&& ((scheme_type.is_special() && !scheme_type.is_file())
|| !self.username().is_empty()
|| self.password().is_some()
|| self.port().is_some())
{
return Err(ParseError::EmptyHost);
}
let mut host_substr = host;
Expand Down
28 changes: 28 additions & 0 deletions url/tests/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,34 @@ fn test_set_empty_host() {
assert_eq!(base.as_str(), "file://foo/share/foo/bar");
}

#[test]
/// https://github.com/servo/rust-url/issues/1144
fn test_set_empty_host_non_special() {
// A non-special URL that has credentials or a port must reject an empty
// host: the resulting serialization (`foo://user@/`, `foo://:1/`) is one
// that `Url::parse` rejects with `EmptyHost`, so allowing it here would
// break the parse/serialize roundtrip. The URL must be left unchanged.
let cases = ["foo://user@host/", "foo://host:1/", "foo://user:pass@host/"];
for input in cases.iter() {
let mut url = Url::parse(input).unwrap();
let before = url.as_str().to_owned();
assert_eq!(
url.set_host(Some("")),
Err(url::ParseError::EmptyHost),
"{}",
input
);
assert_eq!(url.as_str(), before, "{}", input);
}

// Without credentials or a port, an empty host stays legal for a
// non-special scheme, and the result must roundtrip through the parser.
let mut url = Url::parse("foo://host/path").unwrap();
url.set_host(Some("")).unwrap();
assert_eq!(url.as_str(), "foo:///path");
assert_eq!(Url::parse(url.as_str()).unwrap(), url);
}

#[test]
fn test_set_empty_username_and_password() {
let mut base: Url = "moz://foo:bar@servo/baz".parse().unwrap();
Expand Down