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

1from .exceptions import ApiKeyIncludedException 

2 

3 

4class ValidateApiKey(object): 

5 """Validates content to ensure SendGrid API key is not present""" 

6 

7 regexes = None 

8 

9 def __init__(self, regex_strings=None, use_default=True): 

10 """Create an API key validator 

11 

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 """ 

17 

18 import re 

19 self.regexes = set() 

20 

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)) 

25 

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)) 

29 

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. 

33 

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 """ 

40 

41 # Handle string in edge-case 

42 if isinstance(request_body, str): 

43 self.validate_message_text(request_body) 

44 

45 # Default param 

46 elif isinstance(request_body, dict): 

47 

48 contents = request_body.get("content", list()) 

49 

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) 

56 

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 

60 

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()