fix: validation for trusted urls

This commit is contained in:
Seth Falco
2022-07-15 16:04:48 +01:00
parent 67ac0ad973
commit 2578e804b6
4 changed files with 168 additions and 18 deletions

View File

@@ -5,6 +5,7 @@ Simple module providing reusable random_string function
import random
import string
from PIL import Image, ImageDraw
from urllib.parse import urlparse
def random_string(length=10):
@@ -112,3 +113,42 @@ def mm_ng(
)
return image
def is_trusted_url(url, url_filters):
"""
Check if a URL is valid and considered a trusted URL.
If the URL is malformed, returns False.
Based on: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/events/UrlFilter
"""
(scheme, netloc, path, params, query, fragment) = urlparse(url)
for filter in url_filters:
if "schemes" in filter:
schemes = filter["schemes"]
if scheme not in schemes:
continue
if "host_equals" in filter:
host_equals = filter["host_equals"]
if netloc != host_equals:
continue
if "host_suffix" in filter:
host_suffix = filter["host_suffix"]
if not netloc.endswith(host_suffix):
continue
if "path_prefix" in filter:
path_prefix = filter["path_prefix"]
if not path.startswith(path_prefix):
continue
return True
return False