|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# Copyright (C) Grimoirelab Contributors |
| 4 | +# |
| 5 | +# This program is free software; you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation; either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | +# |
| 18 | + |
| 19 | +import logging |
| 20 | + |
| 21 | +import hvac |
| 22 | +import hvac.exceptions |
| 23 | + |
| 24 | +from .exceptions import HashicorpVaultError, CredentialNotFoundError |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +class HashicorpManager: |
| 30 | + """Retrieve credentials from HashiCorp Vault. |
| 31 | +
|
| 32 | + This class defines functions to initialize a client and retrieve |
| 33 | + secrets from HashiCorp Vault. The workflow is: |
| 34 | +
|
| 35 | + manager = HashicorpManager(vault_url, token, certificate) |
| 36 | + manager.get_secret("github") |
| 37 | + manager.get_secret("elasticsearch") |
| 38 | +
|
| 39 | + The manager initializes the client using the vault_url, token, |
| 40 | + and certificate given as arguments when creating the instance, |
| 41 | + so the object is reusable along the program. |
| 42 | +
|
| 43 | + The get_secret function returns the whole item object, with metadata |
| 44 | + included, so the user can choose to store it and retrieve desired data. |
| 45 | + """ |
| 46 | + |
| 47 | + def __init__(self, vault_url: str, token: str, certificate: str | bool = None): |
| 48 | + """ |
| 49 | + Creates HashicorpManager object using token authentication |
| 50 | +
|
| 51 | + :param str vault_url: The URL of the vault |
| 52 | + :param str token: The access token for authentication |
| 53 | + :param Union[str, bool, None] certificate: TLS verification setting. Either a boolean to indicate whether TLS |
| 54 | + verification should be performed, a string pointing at the CA bundle to use for |
| 55 | + verification |
| 56 | +
|
| 57 | + :raises ConnectionError: If connection issues occur |
| 58 | + """ |
| 59 | + try: |
| 60 | + logger.debug("Creating Vault client") |
| 61 | + # Initialize client with URL, token, and certificate verification setting |
| 62 | + self.client = hvac.Client(url=vault_url, token=token, verify=certificate) |
| 63 | + logger.debug("Vault client initialized successfully") |
| 64 | + except Exception as e: |
| 65 | + logger.error("An error occurred initializing the client: %s", str(e)) |
| 66 | + raise e |
| 67 | + |
| 68 | + def get_secret(self, item_name: str) -> dict: |
| 69 | + """Retrieve an item from the HashiCorp Vault. |
| 70 | +
|
| 71 | + Retrieves all the fields stored for an item with the name |
| 72 | + provided as an argument and returns them as a dictionary. |
| 73 | +
|
| 74 | + The returned dictionary includes fields such as: |
| 75 | + - data: The actual secret data and metadata |
| 76 | + - request_id, lease_id, renewable, lease_duration |
| 77 | + - Other vault metadata |
| 78 | +
|
| 79 | + :param str item_name: The name of the item to retrieve |
| 80 | +
|
| 81 | + :returns: Dictionary containing the secret data and metadata |
| 82 | + :rtype: dict |
| 83 | +
|
| 84 | + :raises CredentialNotFoundError: If the secret path is not found |
| 85 | + :raises HashicorpVaultError: If Vault operations fail |
| 86 | + """ |
| 87 | + try: |
| 88 | + logger.info("Retrieving credentials from vault: %s", item_name) |
| 89 | + # Read secret from KV secrets engine |
| 90 | + secret = self.client.secrets.kv.read_secret(path=item_name) |
| 91 | + return secret |
| 92 | + except hvac.exceptions.InvalidPath: |
| 93 | + logger.error("The path %s does not exist in the vault", item_name) |
| 94 | + raise CredentialNotFoundError( |
| 95 | + f"Secret path '{item_name}' not found in Vault" |
| 96 | + ) |
| 97 | + except Exception as e: |
| 98 | + logger.error("Error retrieving the secret: %s", str(e)) |
| 99 | + raise HashicorpVaultError(f"Vault operation failed: {e}") |
0 commit comments