Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
32 changes: 30 additions & 2 deletions src/url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::sync::OnceLock;

use idna::punycode::decode_to_string;
use jiter::{PartialMode, StringCacheMode};
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use percent_encoding::{percent_encode, AsciiSet, CONTROLS};
use pyo3::exceptions::PyValueError;
use pyo3::pyclass::CompareOp;
use pyo3::sync::OnceLockExt;
Expand Down Expand Up @@ -602,8 +602,36 @@ fn is_punnycode_domain(lib_url: &Url, domain: &str) -> bool {
scheme_is_special(lib_url.scheme()) && domain.split('.').any(|part| part.starts_with(PUNYCODE_PREFIX))
}

/// See <https://url.spec.whatwg.org/#userinfo-percent-encode-set>
///
/// Note that this doesn't actually include % itself - see the note in
/// https://url.spec.whatwg.org/#string-percent-encode-after-encoding
Copy link
Member

@Viicos Viicos Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RFC 3986 says:

Because the percent ("%") character serves as the indicator for
percent-encoded octets, it must be percent-encoded as "%25" for that
octet to be used as data within a URI.

And the note in the WHATWG spec isn't clear to me:

The other values for the percentEncodeSet argument — which happen to be used by the URL parser — leave U+0025 (%) untouched and as such it needs to be percent-encoded first in order to be properly represented.

As I understand it, it says that some encoding sets don't encode %, and as such % need special-casing and must be percent-encoded?

Before #1829, it seems that % wasn't encoded:

import pydantic as py

scheme = "mysql+pymysql"
host = "my_host"
port = 3306
path = "my_db"
username = "my_user"
password = "my_passwor%d"

url_1 = py.AnyUrl(f"{scheme}://{username}:{password}@{host}:{port}/{path}")
print(url_1)
#> mysql+pymysql://my_user:my_passwor%d@my_host:3306/my_db

But following what I said previously this should be a bug.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const USERINFO_ENCODE_SET: &AsciiSet = &CONTROLS
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to self: ~ is no included in the set. RFC 1738 used to consider it an unsafe character, but RFC 3986 doesn't.

// query percent-encodes is controls plus the below
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'<')
.add(b'>')
// path percent-encodes is query percent-encodes plus the below
.add(b'?')
.add(b'^')
.add(b'`')
.add(b'{')
.add(b'}')
// userinfo percent-encodes is path percent-encodes plus the below
.add(b'/')
.add(b':')
.add(b';')
.add(b'=')
.add(b'@')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'|');

fn encode_userinfo_component(value: &str) -> Cow<'_, str> {
let encoded = percent_encode(value.as_bytes(), NON_ALPHANUMERIC).to_string();
let encoded = percent_encode(value.as_bytes(), USERINFO_ENCODE_SET).to_string();
if encoded == value {
Cow::Borrowed(value)
} else {
Expand Down
33 changes: 20 additions & 13 deletions tests/validators/test_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -1318,31 +1318,38 @@ def test_multi_url_build() -> None:
assert str(url) == 'postgresql://testuser:[email protected]:5432/database?sslmode=require#test'


def test_multi_url_build_encodes_credentials() -> None:
url = MultiHostUrl.build(
@pytest.mark.parametrize('url_type', [Url, MultiHostUrl])
def test_url_build_encodes_credentials(url_type: type[Union[Url, MultiHostUrl]]) -> None:
url = url_type.build(
scheme='postgresql',
username='user name',
password='p@ss/word?#',
password='p@ss/word?#__',
host='example.com',
port=5432,
)
assert url == MultiHostUrl('postgresql://user%20name:p%40ss%2Fword%3F%[email protected]:5432')
assert str(url) == 'postgresql://user%20name:p%40ss%2Fword%3F%[email protected]:5432'
assert url.hosts() == [
{'username': 'user%20name', 'password': 'p%40ss%2Fword%3F%23', 'host': 'example.com', 'port': 5432}
]
assert url == url_type('postgresql://user%20name:p%40ss%2Fword%3F%[email protected]:5432')
assert str(url) == 'postgresql://user%20name:p%40ss%2Fword%3F%[email protected]:5432'
if url_type is Url:
assert url.username == 'user%20name'
assert url.password == 'p%40ss%2Fword%3F%23__'
else:
assert url.hosts() == [
{'username': 'user%20name', 'password': 'p%40ss%2Fword%3F%23__', 'host': 'example.com', 'port': 5432}
]


def test_multi_url_build_hosts_encodes_credentials() -> None:
hosts = [
{'host': 'example.com', 'password': 'p@ss/word?#', 'username': 'user name', 'port': 5431},
{'host': 'example.org', 'password': 'pa%ss', 'username': 'other', 'port': 5432},
{'host': 'example.com', 'password': 'p@ss/word?#__', 'username': 'user name', 'port': 5431},
{'host': 'example.org', 'password': 'p@%ss__', 'username': 'other', 'port': 5432},
]
url = MultiHostUrl.build(scheme='postgresql', hosts=hosts)
assert str(url) == 'postgresql://user%20name:p%40ss%2Fword%3F%[email protected]:5431,other:pa%[email protected]:5432'
assert (
str(url) == 'postgresql://user%20name:p%40ss%2Fword%3F%[email protected]:5431,other:p%40%[email protected]:5432'
)
assert url.hosts() == [
{'username': 'user%20name', 'password': 'p%40ss%2Fword%3F%23', 'host': 'example.com', 'port': 5431},
{'username': 'other', 'password': 'pa%25ss', 'host': 'example.org', 'port': 5432},
{'username': 'user%20name', 'password': 'p%40ss%2Fword%3F%23__', 'host': 'example.com', 'port': 5431},
{'username': 'other', 'password': 'p%40%ss__', 'host': 'example.org', 'port': 5432},
]


Expand Down
Loading