Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/sendgrid/helpers/mail/validators.py: 16%
27 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from .exceptions import ApiKeyIncludedException
4class ValidateApiKey(object):
5 """Validates content to ensure SendGrid API key is not present"""
7 regexes = None
9 def __init__(self, regex_strings=None, use_default=True):
10 """Create an API key validator
12 :param regex_strings: list of regex strings
13 :type regex_strings: list(str)
14 :param use_default: Whether or not to include default regex
15 :type use_default: bool
16 """
18 import re
19 self.regexes = set()
21 # Compile the regex strings into patterns, add them to our set
22 if regex_strings is not None:
23 for regex_string in regex_strings:
24 self.regexes.add(re.compile(regex_string))
26 if use_default:
27 default_regex_string = r'SG\.[0-9a-zA-Z]+\.[0-9a-zA-Z]+'
28 self.regexes.add(re.compile(default_regex_string))
30 def validate_message_dict(self, request_body):
31 """With the JSON dict that will be sent to SendGrid's API,
32 check the content for SendGrid API keys - throw exception if found.
34 :param request_body: The JSON dict that will be sent to SendGrid's
35 API.
36 :type request_body: JSON serializable structure
37 :raise ApiKeyIncludedException: If any content in request_body
38 matches regex
39 """
41 # Handle string in edge-case
42 if isinstance(request_body, str):
43 self.validate_message_text(request_body)
45 # Default param
46 elif isinstance(request_body, dict):
48 contents = request_body.get("content", list())
50 for content in contents:
51 if content is not None:
52 if (content.get("type") == "text/html" or
53 isinstance(content.get("value"), str)):
54 message_text = content.get("value", "")
55 self.validate_message_text(message_text)
57 def validate_message_text(self, message_string):
58 """With a message string, check to see if it contains a SendGrid API Key
59 If a key is found, throw an exception
61 :param message_string: message that will be sent
62 :type message_string: string
63 :raises ApiKeyIncludedException: If message_string matches a regex
64 string
65 """
66 if isinstance(message_string, str):
67 for regex in self.regexes:
68 if regex.match(message_string) is not None:
69 raise ApiKeyIncludedException()