Manager for securely accessing and managing service credentials. Supports loading credentials from environment variables, credential files, and AWS Secrets Manager.
| 66 | |
| 67 | |
| 68 | class CredentialManager: |
| 69 | """ |
| 70 | Manager for securely accessing and managing service credentials. |
| 71 | |
| 72 | Supports loading credentials from environment variables, credential files, |
| 73 | and AWS Secrets Manager. |
| 74 | """ |
| 75 | |
| 76 | def __init__( |
| 77 | self, |
| 78 | credentials_file: Optional[str] = None, |
| 79 | use_env_vars: bool = True, |
| 80 | use_aws_secrets: bool = False, |
| 81 | aws_region: Optional[str] = None |
| 82 | ): |
| 83 | """ |
| 84 | Initialize the credential manager. |
| 85 | |
| 86 | Args: |
| 87 | credentials_file: Path to credentials file |
| 88 | use_env_vars: Whether to load credentials from environment variables |
| 89 | use_aws_secrets: Whether to load credentials from AWS Secrets Manager |
| 90 | aws_region: AWS region for Secrets Manager |
| 91 | """ |
| 92 | self.credentials_file = credentials_file |
| 93 | self.use_env_vars = use_env_vars |
| 94 | self.use_aws_secrets = use_aws_secrets |
| 95 | self.aws_region = aws_region |
| 96 | |
| 97 | # Load credentials from file if provided |
| 98 | self.credentials: Dict[str, Any] = {} |
| 99 | if credentials_file: |
| 100 | self._load_credentials_file() |
| 101 | |
| 102 | def _load_credentials_file(self) -> None: |
| 103 | """ |
| 104 | Load credentials from file. |
| 105 | |
| 106 | Raises: |
| 107 | FileNotFoundError: If credentials file doesn't exist |
| 108 | json.JSONDecodeError: If credentials file is not valid JSON |
| 109 | """ |
| 110 | try: |
| 111 | creds_path = Path(self.credentials_file).expanduser() |
| 112 | if creds_path.exists(): |
| 113 | with open(creds_path, 'r') as f: |
| 114 | self.credentials = json.load(f) |
| 115 | logger.info(f"Loaded credentials from {self.credentials_file}") |
| 116 | else: |
| 117 | logger.warning(f"Credentials file {self.credentials_file} not found") |
| 118 | except (json.JSONDecodeError, IOError) as e: |
| 119 | logger.error(f"Failed to load credentials file: {e}") |
| 120 | raise |
| 121 | |
| 122 | def _get_from_env(self, prefix: str, keys: Dict[str, str]) -> Dict[str, str]: |
| 123 | """ |
| 124 | Get credentials from environment variables. |
| 125 |
no outgoing calls