Skip to content

Commit 3bdbd01

Browse files
committed
Reject raw ASCII controls and spaces in URI validation
1 parent 6ffd862 commit 3bdbd01

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

‎src/validators/uri.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# https://www.rfc-editor.org/rfc/rfc3986#section-3
55

66
# standard
7+
import re
78
from urllib.parse import urlsplit
89

910
# local
@@ -88,7 +89,7 @@ def uri(value: str, /):
8889
(Literal[True]): If `value` is a valid URI.
8990
(ValidationError): If `value` is an invalid URI.
9091
"""
91-
if not value:
92+
if not value or re.search(r"[\x00-\x20\x7f]", value):
9293
return False
9394

9495
# TODO: work on various validations

‎tests/test_uri.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,35 @@ def test_valid_telnet_uri(value: str):
4141
def test_invalid_telnet_uri(value: str):
4242
"""Test invalid telnet URI."""
4343
assert not uri(value)
44+
45+
46+
@pytest.mark.parametrize(
47+
"value",
48+
[
49+
"file:///tmp/readme.txt",
50+
"ipfs://QmYwAPJzv5CZsnAzt8auVZRnGiUncKEy6PBDoDeZ7hA9Rx/readme.txt",
51+
"magnet:?xt=urn:btih:0123456789012345678901234567890123456789",
52+
"tel:+1234567890",
53+
"data:text/plain;base64,SGVsbG8=",
54+
"urn:isbn:9780140328721",
55+
"urc:example",
56+
],
57+
)
58+
@pytest.mark.parametrize("invalid_char", ["\x00", "\t", "\n", "\r", " ", "\x7f"])
59+
def test_rejects_raw_ascii_controls_and_spaces_in_uri(value: str, invalid_char: str):
60+
"""Test rejects raw ASCII controls and spaces in URI."""
61+
assert not uri(value + invalid_char)
62+
63+
64+
@pytest.mark.parametrize(
65+
"value",
66+
[
67+
"file:///tmp/readme%20name.txt",
68+
"ipfs://QmYwAPJzv5CZsnAzt8auVZRnGiUncKEy6PBDoDeZ7hA9Rx/readme%0A.txt",
69+
"magnet:?xt=urn:btih:0123456789012345678901234567890123456789&dn=readme%20name",
70+
"data:text/plain,hello%20world",
71+
],
72+
)
73+
def test_accepts_percent_encoded_characters_in_uri(value: str):
74+
"""Test accepts percent encoded characters in URI."""
75+
assert uri(value)

0 commit comments

Comments
 (0)