# -*- coding: utf-8 -*-
from setuptools import setup

package_dir = \
{'': 'src'}

packages = \
['pydantic_vault']

package_data = \
{'': ['*']}

install_requires = \
['hvac>=0.10.6,<0.12', 'pydantic>=1.8,<2.0']

setup_kwargs = {
    'name': 'pydantic-vault',
    'version': '0.7.0',
    'description': 'A simple extension to Pydantic BaseSettings that can retrieve secrets from Hashicorp Vault',
    'long_description': '# Pydantic-Vault\n\n[![PyPI](https://img.shields.io/pypi/v/pydantic-vault)](https://pypi.org/project/pydantic-vault/)\n[![Check code](https://github.com/nymous/pydantic-vault/workflows/Check%20code/badge.svg)](https://github.com/nymous/pydantic-vault/actions/workflows/check_code.yml)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\nA simple extension to [Pydantic][pydantic] [BaseSettings][pydantic-basesettings] that can retrieve secrets from a [KV v2 secrets engine][vault-kv-v2] in Hashicorp [Vault][vault]\n\n<!-- toc -->\n\n- [Installation](#installation)\n- [Getting started](#getting-started)\n- [Documentation](#documentation)\n  * [`Field` additional parameters](#field-additional-parameters)\n  * [Configuration](#configuration)\n  * [Authentication](#authentication)\n    + [Approle](#approle)\n    + [Kubernetes](#kubernetes)\n    + [Vault token](#vault-token)\n  * [Order of priority](#order-of-priority)\n- [Logging](#logging)\n- [Examples](#examples)\n  * [Retrieve a secret from a KV v2 secret engine](#retrieve-a-secret-from-a-kv-v2-secret-engine)\n  * [Retrieve a whole secret at once](#retrieve-a-whole-secret-at-once)\n  * [Retrieve a secret from a KV v1 secret engine](#retrieve-a-secret-from-a-kv-v1-secret-engine)\n  * [Retrieve a secret from a database secret engine](#retrieve-a-secret-from-a-database-secret-engine)\n- [Known limitations](#known-limitations)\n- [Inspirations](#inspirations)\n- [License](#license)\n\n<!-- tocstop -->\n\n## Installation\n\n```shell\npip install pydantic-vault\n\n# or if you use Poetry or Pipenv\npoetry add pydantic-vault\npipenv install pydantic-vault\n```\n\n## Getting started\n\nStarting with Pydantic 1.8, [custom settings sources][pydantic-basesettings-customsource] are officially supported.\n\nYou can create a normal `BaseSettings` class, and define the `customise_sources()` method to load secrets from your Vault instance using the `vault_config_settings_source` function:\n\n```python\nimport os\n\nfrom pydantic import BaseSettings, Field, SecretStr\nfrom pydantic_vault import vault_config_settings_source\n\n\nclass Settings(BaseSettings):\n    # The `vault_secret_path` is the full path (with mount point included) to the secret\n    # The `vault_secret_key` is the specific key to extract from a secret\n    username: str = Field(\n        ..., vault_secret_path="secret/data/path/to/secret", vault_secret_key="my_user"\n    )\n    password: SecretStr = Field(\n        ...,\n        vault_secret_path="secret/data/path/to/secret",\n        vault_secret_key="my_password",\n    )\n\n    class Config:\n        vault_url: str = "https://vault.tld"\n        vault_token: SecretStr = os.environ["VAULT_TOKEN"]\n        vault_namespace: str = "your/namespace"  # Optional, pydantic-vault supports Vault namespaces (for Vault Enterprise)\n\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            # This is where you can choose which settings sources to use and their priority\n            return (\n                init_settings,\n                env_settings,\n                vault_config_settings_source,\n                file_secret_settings,\n            )\n\n\nsettings = Settings()\n# These variables will come from the Vault secret you configured\nsettings.username\nsettings.password.get_secret_value()\n\n\n# Now let\'s pretend we have already set the USERNAME in an environment variable\n# (see the Pydantic documentation for more information and to know how to configure it)\n# With the priority order we defined above, its value will override the Vault secret\nos.environ["USERNAME"] = "my user"\n\nsettings = Settings()\nsettings.username  # "my user", defined in the environment variable\nsettings.password.get_secret_value()  # the value set in Vault\n```\n\n## Documentation\n\n### `Field` additional parameters\n\nYou might have noticed that we import `Field` directly from Pydantic. Pydantic-Vault doesn\'t add any custom logic to it, which means you can still use everything you know and love from Pydantic.\n\nThe additional parameters Pydantic-Vault uses are:\n\n| Parameter name              | Required | Description |\n|-----------------------------|----------|-------------|\n| `vault_secret_path`         | **Yes**  | The path to your secret in Vault<br>This needs to be the *full path* to the secret, including its mount point (see [examples](#examples) below) |\n| `vault_secret_key`          | No       | The key to use in the secret<br>If it is not specified the whole secret content will be loaded as a dict (see [examples](#examples) below) |\n\nFor example, if you create a secret `database/prod` with a key `password` and a value of `a secret password` in a KV v2 secret engine mounted at the default `secret/` location, you would access it with\n\n```python\npassword: SecretStr = Field(\n    ..., vault_secret_path="secret/data/database/prod", vault_secret_key="password"\n)\n```\n\n### Configuration\n\nYou can configure the behaviour of Pydantic-vault in your `Settings.Config` class, or using environment variables:\n\n| Settings name              | Required | Environment variable | Description |\n|----------------------------|----------|----------------------|-------------|\n| `customise_sources()`      | **Yes**  | N/A                  | You need to implement this function to use Vault as a settings source, and choose the priority order you want |\n| `vault_url`                | **Yes**  | `VAULT_ADDR`         | Your Vault URL |\n| `vault_namespace`          | No       | `VAULT_NAMESPACE`    | Your Vault namespace (if you use one, requires Vault Enterprise) |\n| `vault_auth_mount_point`   | No       | `VAULT_AUTH_MOUNT_POINT` | The mount point of the authentication method, if different from its default mount point |\n\nYou can also configure everything available in the original Pydantic `BaseSettings` class.\n\n### Authentication\n\nPydantic-Vault supports the following authentication method (in descending order of priority):\n  - [direct token authentication][vault-auth-token]\n  - [kubernetes][vault-auth-kubernetes]\n  - [approle][vault-auth-approle]\n\nPydantic-Vault tries to be transparent and help you work, both during local development and in production. It will try to\nfind the required information for the first authentication method, if it can\'t it goes on to the next method, until it\nhas exhausted all authentication methods. In this case it gives up and logs the failure.\n\nYou only need to know this order of priority if you specify the authentication parameters for multiple methods.\n\nSupport is planned for GKE authentication methods.\n\n#### Approle\n\nTo authenticate using the [Approle auth method][vault-auth-approle], you need to pass a role ID and a secret ID to your Settings class.\n\nPydantic-vault reads this information from the following sources (in descending order of priority):\n  - the `vault_role_id` and `vault_secret_id` configuration fields in your `Settings.Config` class (`vault_secret_id` can be a `str` or a `SecretStr`)\n  - the `VAULT_ROLE_ID` and `VAULT_SECRET_ID` environment variables\n\nYou can also mix-and-match, e.g. write the role ID in your `Settings.Config` class and retrieve the secret ID from the environment at runtime.\n\nExample:\n```python\nfrom pydantic import BaseSettings, Field, SecretStr\nfrom pydantic_vault import vault_config_settings_source\n\n\nclass Settings(BaseSettings):\n    username: str = Field(\n        ..., vault_secret_path="path/to/secret", vault_secret_key="my_user"\n    )\n    password: SecretStr = Field(\n        ..., vault_secret_path="path/to/secret", vault_secret_key="my_password"\n    )\n\n    class Config:\n        vault_url: str = "https://vault.tld"\n        vault_role_id: str = "my-role-id"\n        vault_secret_id: SecretStr = SecretStr("my-secret-id")\n\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            return (\n                init_settings,\n                env_settings,\n                vault_config_settings_source,\n                file_secret_settings,\n            )\n```\n\n#### Kubernetes\n\nTo authenticate using the [Kubernetes auth method][vault-auth-kubernetes], you need to pass a role to your Settings class.\n\nPydantic-vault reads this information from the following sources (in descending order of priority):\n  - the `vault_kubernetes_role` configuration field in your `Settings.Config` class, which must be a `str`\n  - the `VAULT_KUBERNETES_ROLE` environment variable\n\nThe Kubernetes service account token will be read from the file at `/var/run/secrets/kubernetes.io/serviceaccount/token`.\n\nExample:\n```python\nfrom pydantic import BaseSettings, Field, SecretStr\nfrom pydantic_vault import vault_config_settings_source\n\n\nclass Settings(BaseSettings):\n    username: str = Field(\n        ..., vault_secret_path="path/to/secret", vault_secret_key="my_user"\n    )\n    password: SecretStr = Field(\n        ..., vault_secret_path="path/to/secret", vault_secret_key="my_password"\n    )\n\n    class Config:\n        vault_url: str = "https://vault.tld"\n        vault_kubernetes_role: str = "my-role"\n\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            return (\n                init_settings,\n                env_settings,\n                vault_config_settings_source,\n                file_secret_settings,\n            )\n```\n\n#### Vault token\n\nTo authenticate using the [Token auth method][vault-auth-token], you need to pass a Vault token to your `Settings` class.\n\nPydantic-vault reads this token from the following sources (in descending order of priority):\n  - the `vault_token` configuration field in your `Settings.Config` class, which can be a `str` or a `SecretStr`\n  - the `VAULT_TOKEN` environment variable\n  - the `~/.vault-token` file (so you can use the `vault` CLI to login locally, Pydantic-vault will transparently reuse its token)\n\nExample:\n```python\nfrom pydantic import BaseSettings, Field, SecretStr\nfrom pydantic_vault import vault_config_settings_source\n\n\nclass Settings(BaseSettings):\n    username: str = Field(\n        ..., vault_secret_path="path/to/secret", vault_secret_key="my_user"\n    )\n    password: SecretStr = Field(\n        ..., vault_secret_path="path/to/secret", vault_secret_key="my_password"\n    )\n\n    class Config:\n        vault_url: str = "https://vault.tld"\n        vault_token: SecretStr = SecretStr("my-secret-token")\n\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            return (\n                init_settings,\n                env_settings,\n                vault_config_settings_source,\n                file_secret_settings,\n            )\n```\n\n### Order of priority\n\nThanks to the new feature in Pydantic 1.8 that allows you to [customize settings sources][pydantic-basesettings-customsource], you can choose the order of priority you want.\n\nHere are some examples:\n```python\nfrom pydantic import BaseSettings\nfrom pydantic_vault import vault_config_settings_source\n\n\nclass Settings(BaseSettings):\n    """\n    In descending order of priority:\n      - arguments passed to the `Settings` class initializer\n      - environment variables\n      - Vault variables\n      - variables loaded from the secrets directory, such as Docker Secrets\n      - the default field values for the `Settings` model\n    """\n\n    class Config:\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            return (\n                init_settings,\n                env_settings,\n                vault_config_settings_source,\n                file_secret_settings,\n            )\n\n\nclass Settings(BaseSettings):\n    """\n    In descending order of priority:\n      - Vault variables\n      - environment variables\n      - variables loaded from the secrets directory, such as Docker Secrets\n      - the default field values for the `Settings` model\n    Here we chose to remove the "init arguments" source,\n    and move the Vault source up before the environment source\n    """\n\n    class Config:\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            return (vault_config_settings_source, env_settings, file_secret_settings)\n```\n\n## Logging\n\nThe library exports a logger called `pydantic-vault`.\n\nTo help debugging you can change the log level. A simple way to do that if you do not have a custom log setup is:\n```py\n# At the beginning of your main file or entrypoint\nimport logging\n\nlogging.basicConfig()\nlogging.getLogger("pydantic-vault").setLevel(logging.DEBUG)  # Change the log level here\n```\n\n## Examples\n\nAll examples use the following structure, so we will omit the imports and the `Config` inner class:\n```python\nfrom pydantic import BaseSettings, Field, SecretStr\nfrom pydantic_vault import vault_config_settings_source\n\n\nclass Settings(BaseSettings):\n    ###############################################\n    # THIS PART CHANGES IN THE DIFFERENT EXAMPLES #\n    username: str = Field(\n        ..., vault_secret_path="secret/data/path/to/secret", vault_secret_key="my_user"\n    )\n    ###############################################\n\n    class Config:\n        vault_url: str = "https://vault.tld"\n\n        @classmethod\n        def customise_sources(\n            cls,\n            init_settings,\n            env_settings,\n            file_secret_settings,\n        ):\n            return (\n                init_settings,\n                env_settings,\n                vault_config_settings_source,\n                file_secret_settings,\n            )\n```\n\n### Retrieve a secret from a KV v2 secret engine\n\nSuppose your secret is at `my-api/prod` and looks like this:\n```\nKey             Value\n---             -----\nroot_user       root\nroot_password   a_v3ry_s3cur3_p4ssw0rd\n```\n\nYour settings class would be:\n```python\nclass Settings(BaseSettings):\n    # The `vault_secret_path` is the full path (with mount point included) to the secret.\n    # For a KV v2 secret engine, there is always a `data/` sub-path between the mount point and\n    # the secret actual path, eg. if your mount point is `secret/` (the default) and your secret\n    # path is `my-api/prod`, the full path to use is `secret/data/my-api/prod`.\n    # The `vault_secret_key` is the specific key to extract from a secret.\n    username: str = Field(\n        ..., vault_secret_path="secret/data/my-api/prod", vault_secret_key="root_user"\n    )\n    password: SecretStr = Field(\n        ...,\n        vault_secret_path="secret/data/my-api/prod",\n        vault_secret_key="root_password",\n    )\n\n\nsettings = Settings()\n\nsettings.username  # "root"\nsettings.password.get_secret_value()  # "a_v3ry_s3cur3_p4ssw0rd"\n```\n\n### Retrieve a whole secret at once\n\nIf you omit the `vault_secret_key` parameter in your `Field`, Pydantic-Vault will load\nthe whole secret in your class field.\n\nWith the same secret as before, located at `my-api/prod` and with this data:\n```\nKey             Value\n---             -----\nroot_user       root\nroot_password   a_v3ry_s3cur3_p4ssw0rd\n```\n\nYou could use a settings class like this to retrieve everything in the secret:\n```python\nclass Settings(BaseSettings):\n    # The `vault_secret_path` is the full path (with mount point included) to the secret.\n    # For a KV v2 secret engine, there is always a `data/` sub-path between the mount point and\n    # the secret actual path, eg. if your mount point is `secret/` (the default) and your secret\n    # path is `my-api/prod`, the full path to use is `secret/data/my-api/prod`.\n    # We don\'t pass a `vault_secret_key` here so that Pydantic-Vault fetches all fields at once.\n    credentials: dict = Field(..., vault_secret_path="secret/data/my-api/prod")\n\n\nsettings = Settings()\nsettings.credentials  # { "root_user": "root", "root_password": "a_v3ry_s3cur3_p4ssw0rd" }\n```\n\nYou can also use a Pydantic `BaseModel` class to parse and validate the incoming secret:\n```python\nclass Credentials(BaseModel):\n    root_user: str\n    root_password: SecretStr\n\n\nclass Settings(BaseSettings):\n    # The `vault_secret_path` is the full path (with mount point included) to the secret.\n    # For a KV v2 secret engine, there is always a `data/` sub-path between the mount point and\n    # the secret actual path, eg. if your mount point is `secret/` (the default) and your secret\n    # path is `my-api/prod`, the full path to use is `secret/data/my-api/prod`.\n    # We don\'t pass a `vault_secret_key` here so that Pydantic-Vault fetches all fields at once.\n    credentials: Credentials = Field(..., vault_secret_path="secret/data/my-api/prod")\n\n\nsettings = Settings()\nsettings.credentials.root_user  # "root"\nsettings.credentials.root_password.get_secret_value()  # "a_v3ry_s3cur3_p4ssw0rd"\n```\n\n### Retrieve a secret from a KV v1 secret engine\n\nSuppose your secret is at `my-api/prod` and looks like this:\n```\nKey             Value\n---             -----\nroot_user       root\nroot_password   a_v3ry_s3cur3_p4ssw0rd\n```\n\nYour settings class would be:\n```python\nclass Settings(BaseSettings):\n    # The `vault_secret_path` is the full path (with mount point included) to the secret.\n    # For a KV v1 secret engine, the secret path is directly appended to the mount point,\n    # eg. if your mount point is `kv/` (the default) and your secret path is `my-api/prod`,\n    # the full path to use is `kv/my-api/prod` (unlike with KV v2 secret engines).\n    # The `vault_secret_key` is the specific key to extract from a secret.\n    username: str = Field(\n        ..., vault_secret_path="kv/my-api/prod", vault_secret_key="root_user"\n    )\n    password: SecretStr = Field(\n        ..., vault_secret_path="kv/my-api/prod", vault_secret_key="root_password"\n    )\n\n\nsettings = Settings()\n\nsettings.username  # "root"\nsettings.password.get_secret_value()  # "a_v3ry_s3cur3_p4ssw0rd"\n```\n\n⚠ Beware of the [known limitations](#known-limitations) on KV v1 secrets!\n\n### Retrieve a secret from a database secret engine\n\nDatabase secrets can be "dynamic", generated by Vault every time you request access.\nBecause every call to Vault will create a new database account, you cannot store the username\nand password in two different fields in your settings class, or you would get the username of the\n*first* generated account and the password of the *second* account. This means that you must *not*\npass a `vault_secret_key`, so that Pydantic-Vault retrieves the whole secret at once.\n\nYou can store the credentials in a dict or in a custom `BaseModel` class:\n```python\nclass DbCredentials(BaseModel):\n    username: str\n    password: SecretStr\n\n\nclass Settings(BaseSettings):\n    # The `vault_secret_path` is the full path (with mount point included) to the secret.\n    # For a database secret engine, the secret path is `<mount point>/creds/<role name>`.\n    # For example if your mount point is `database/` (the default) and your role name is\n    # `my-db-prod`, the full path to use is `database/creds/my-db-prod`. You will receive\n    # `username` and `password` fields in response.\n    # You must *not* pass a `vault_secret_key` so that Pydantic-Vault fetches both fields at once.\n    db_creds: DbCredentials = Field(..., vault_secret_path="database/creds/my-db-prod")\n    db_creds_in_dict: dict = Field(..., vault_secret_path="database/creds/my-db-prod")\n\n\nsettings = Settings()\n\nsettings.db_creds.username  # "generated-username-1"\nsettings.db_creds.password.get_secret_value()  # "generated-password-for-username-1"\nsettings.db_creds_in_dict["username"]  # "generated-username-2"\nsettings.db_creds_in_dict["password"]  # "generated-password-for-username-2"\n```\n\n## Known limitations\n\n- Pydantic by default takes up ~80 MB, because it is compiled to a native extension and optimized for speed instead of file\n  size. If you don\'t rely much on Pydantic (you only use it for your app configuration with Pydantic-Vault, you parse/serialize\n  a low volume of JSON, your code is generally slow and Pydantic wouldn\'t be the bottleneck) you can use the flag\n  `--no-binary pydantic` when running `pip install` to install the pure-Python version instead of the compiled one (which\n  comes at less than 1 MB). You can also add the flag on its own line in your `requirements.txt`. See this discussion\n  https://github.com/samuelcolvin/pydantic/issues/2276 for more information.\n\n- On KV v1 secret engines, if your secret has a `data` key and you do not specify a `vault_secret_key`\nto load the whole secret at once, Pydantic-vault will only load the content of the `data` key.\n  For example, with a secret `kv/my-secret`\n  ```\n  Key             Value\n  ---             -----\n  user            root\n  password        a_v3ry_s3cur3_p4ssw0rd\n  data            a very important piece of data\n  ```\n  and the settings class\n  ```python\n  class Settings(BaseSettings):\n      my_secret: dict = Field(..., vault_secret_path="kv/my-secret")\n  ```\n  Pydantic-Vault will try to load only the `data` value (`a very important piece of data`) in\n  `my_secret`, which will fail validation from Pydantic because it is not a dict.\n\n  **Workaround:** Rename the `data` key in your secret 😅\n\n  **Workaround:** Migrate to KV v2\n\n## Inspirations\n\n- [Ansible `hashi_vault` lookup plugin][ansible hashi_vault] for the API and some code\n- [Hashicorp\'s Vault GitHub Action][vault-action] for the API\n\n## License\n\nPydantic-Vault is available under the [MIT license](./LICENSE).\n\n[ansible hashi_vault]: https://docs.ansible.com/ansible/latest/collections/community/hashi_vault/hashi_vault_lookup.html\n[pydantic]: https://pydantic-docs.helpmanual.io/\n[pydantic-basesettings]: https://pydantic-docs.helpmanual.io/usage/settings/\n[pydantic-basesettings-customsource]: https://pydantic-docs.helpmanual.io/usage/settings/#customise-settings-sources\n[vault]: https://www.vaultproject.io/\n[vault-action]: https://github.com/hashicorp/vault-action\n[vault-auth-approle]: https://www.vaultproject.io/docs/auth/approle\n[vault-auth-kubernetes]: https://www.vaultproject.io/docs/auth/kubernetes\n[vault-auth-token]: https://www.vaultproject.io/docs/auth/token\n[vault-kv-v2]: https://www.vaultproject.io/docs/secrets/kv/kv-v2/\n',
    'author': 'Thomas Gaudin',
    'author_email': 'thomas.gaudin@centraliens-lille.org',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/nymous/pydantic-vault',
    'package_dir': package_dir,
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.6.2,<4.0.0',
}


setup(**setup_kwargs)
