-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.py
More file actions
73 lines (56 loc) · 1.84 KB
/
api.py
File metadata and controls
73 lines (56 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from urllib.parse import urlparse
from urllib.request import urlopen as unsafe_urlopen
from requests import get as unsafe_get
from requests import post as unsafe_post
from security.exceptions import SecurityException
from .host_validators import DefaultHostValidator
DEFAULT_PROTOCOLS = frozenset(("http", "https"))
class UrlParser:
def __init__(self, url):
self.url = url
self.parsed_url = urlparse(url)
@property
def protocol(self):
return self.parsed_url.scheme
@property
def host(self):
return self.parsed_url.netloc
def check(self, allowed_protocols, host_validator):
self._check_protocol(allowed_protocols)
self._check_host(host_validator)
def _check_protocol(self, allowed_protocols):
if self.protocol not in allowed_protocols:
raise SecurityException("Disallowed protocol: %s", self.protocol)
def _check_host(self, host_validator):
if not host_validator(self.host).is_allowed:
raise SecurityException("Disallowed host: %s", self.host)
def urlopen(
url,
data=None,
timeout=None,
*args,
allowed_protocols=DEFAULT_PROTOCOLS,
host_validator=DefaultHostValidator,
**kwargs,
):
UrlParser(url).check(allowed_protocols, host_validator)
return unsafe_urlopen(url, data, timeout, *args, **kwargs)
def get(
url,
params=None,
allowed_protocols=DEFAULT_PROTOCOLS,
host_validator=DefaultHostValidator,
**kwargs,
):
UrlParser(url).check(allowed_protocols, host_validator)
return unsafe_get(url, params=params, **kwargs)
def post(
url,
data=None,
json=None,
allowed_protocols=DEFAULT_PROTOCOLS,
host_validator=DefaultHostValidator,
**kwargs,
):
UrlParser(url).check(allowed_protocols, host_validator)
return unsafe_post(url, data=data, json=json, **kwargs)