views: Update utility for checking URL safety

Django has updated the is_safe_url() method that we based our implementation on.
It is now called url_has_allowed_host_and_scheme(). Our implementation remains
simple as we don't allow any hostname or scheme to be set.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa 2021-09-20 08:43:36 -07:00 committed by James Valleroy
parent 53539c7454
commit 07e62a213b
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
2 changed files with 17 additions and 9 deletions

View File

@ -18,14 +18,19 @@ def test_is_safe_url_valid_url(url):
assert is_safe_url(url)
@pytest.mark.parametrize('url', [
'',
None,
'\\plinth',
'///plinth',
'https://example.com/plinth/login/',
'https:///plinth/login',
])
@pytest.mark.parametrize(
'url',
[
'',
None,
'\\plinth',
'///plinth',
'https://example.com/plinth/login/',
'https:///example.com',
'https:///plinth/login',
'ftp://example.com',
'https://[aabb::ccdd', # Invalid IPv6
])
def test_is_safe_url_invalid_url(url):
"""Test invalid URLs for safe URL checks."""
assert not is_safe_url(url)

View File

@ -44,7 +44,10 @@ def is_safe_url(url):
if '\\' in url or url.startswith('///'):
return False
result = urllib.parse.urlparse(url)
try:
result = urllib.parse.urlparse(url)
except ValueError:
return False
# Only accept URLs to the same site and scheme.
if result.scheme or result.netloc: