Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2############################################################################## 

3## gjb 

4## 06/23/20 

5## https://smiledirectclub.atlassian.net/browse/DE-691 

6## SDC Endpoint Credentials 

7## Retrieves credentials in schema endpoints 

8## 

9# -------------------------------------------------------------------------- 

10############################################################################## 

11""" 

12 

13import base64 

14import importlib 

15import logging 

16import os 

17 

18from sdc_etl_libs.sdc_credentials.secrets_enum import SecretManagers 

19from sdc_etl_libs.sdc_data_schema.schema_exceptions import InvalidSchemaCredentialsType 

20 

21secrets_class = lambda lib_path: importlib.import_module(name=lib_path) 

22 

23 

24class SDCEndpointCredentials: 

25 # Set logger up 

26 logging.basicConfig(format='%(levelname)s: %(asctime)s: ' '%(funcName)s: %(message)s') 

27 logger = logging.getLogger(__name__) 

28 logger.setLevel(logging.INFO) 

29 

30 @staticmethod 

31 def get_credentials(credentials_schema_: dict): 

32 """ 

33 Gets credentials based on schema. 

34 :param credentials_schema_ : Dict. Credentials section of endpoint schema. 

35 :return: Dictionary with credentials. 

36 :raise InvalidSchemaCredentialsType, EnvironmentError, Exception: 

37 """ 

38 credentials = {} 

39 credentials_type = credentials_schema_["type"].lower() 

40 try: 

41 if credentials_type == "aws_secrets": 

42 secret_manager = SecretManagers.__dict__[credentials_type].value 

43 secrets = getattr(secrets_class(secret_manager['lib_path']), secret_manager['class'])() 

44 credentials = secrets.get_secrets(credentials_schema_["opts"]["name"], decode_=False) 

45 elif credentials_type == "vault": 

46 secret_manager = SecretManagers.__dict__[credentials_type].value 

47 secrets = getattr(secrets_class(secret_manager['lib_path']), secret_manager['class']) 

48 vault = secrets() 

49 credentials = vault.get_secrets( 

50 secrets_engine_=credentials_schema_["opts"].get("secrets_engine"), 

51 domain_=credentials_schema_["opts"].get("domain"), 

52 secret_path_=credentials_schema_["opts"].get("secret_path")) 

53 elif credentials_type == "environment_variables": 

54 for key, value in credentials_schema_["opts"]["variables"].items(): 

55 try: 

56 environ_value = os.environ[value] 

57 credentials[key] = environ_value 

58 except KeyError as e: 

59 logging.info("No Environment Variable found for : %s", e) 

60 else: 

61 raise InvalidSchemaCredentialsType(credentials_type) 

62 

63 # Decode Base64 private keys in credentials 

64 credentials = SDCEndpointCredentials.get_decoded_credentials(credentials) 

65 

66 logging.info('%s', "Endpoint Credentials processing complete") 

67 

68 except Exception as e: 

69 logging.exception("Error in get_credentials function") 

70 raise e 

71 

72 return credentials 

73 

74 @staticmethod 

75 def encode_base64(binary_key_: str): 

76 """ 

77 Encodes a binary private key using Base64. 

78 :param str binary_key_: Binary RSA, SSH, or other private key. 

79 :return str base64_key: Base64-encoded RSA or SSH private key. 

80 """ 

81 base64_key = base64.b64encode(binary_key_.encode('utf-8')) 

82 return base64_key 

83 

84 @staticmethod 

85 def decode_base64(base64_key_: str): 

86 """ 

87 Decodes a Base64-encoded private key to binary. 

88 :param str base64_key_: Base64-encoded RSA, SSH, or other private key. 

89 :return str binary_key: Binary RSA or SSH private key. 

90 """ 

91 binary_key = base64.b64decode(base64_key_).decode('utf-8') 

92 return binary_key 

93 

94 @staticmethod 

95 def get_decoded_credentials(credentials_): 

96 """ 

97 Convert credentials containing Base64 private keys to credentials containing binary private keys. 

98 : param dict credentials_: Credentials dictionary containing Base64 private keys (RSA and/or SSH). 

99 :return dict decoded_credentials: Credentials dictionary containing binary private keys (RSA and/or SSH). 

100 """ 

101 decoded_credentials = credentials_.copy() 

102 

103 try: 

104 for private_key in ("rsa_key", "ssh_key"): 

105 if private_key in credentials_: 

106 decoded_credentials[private_key] = SDCEndpointCredentials.decode_base64( 

107 decoded_credentials[private_key]) 

108 except base64.binascii.Error: 

109 raise Exception(f'"{private_key}" secret is not encoded using Base64, but should be.') 

110 

111 return decoded_credentials