| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright (c) 2021 Brian Scholer (@briantist) |
| 3 |
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 4 |
# SPDX-License-Identifier: BSD-2-Clause |
| 5 |
|
| 6 |
'''Python versions supported: >=3.8''' |
| 7 |
|
| 8 |
# FOR INTERNAL COLLECTION USE ONLY |
| 9 |
# The interfaces in this file are meant for use within the community.hashi_vault collection |
| 10 |
# and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release. |
| 11 |
# See also: https://github.com/ansible/community/issues/539#issuecomment-780839686 |
| 12 |
# Please open an issue if you have questions about this. |
| 13 |
|
| 14 |
from __future__ import absolute_import, division, print_function |
| 15 |
__metaclass__ = type |
| 16 |
|
| 17 |
import os |
| 18 |
|
| 19 |
|
| 20 |
class HashiVaultValueError(ValueError): |
| 21 |
'''Use in common code to raise an Exception that can be turned into AnsibleError or used to fail_json()''' |
| 22 |
|
| 23 |
|
| 24 |
class HashiVaultHVACError(ImportError): |
| 25 |
'''Use in common code to signal HVAC is missing.''' |
| 26 |
def __init__(self, error, msg): |
| 27 |
super().__init__(error) |
| 28 |
self.msg = msg |
| 29 |
self.error = error |
| 30 |
|
| 31 |
|
| 32 |
class HashiVaultHelper(): |
| 33 |
def __init__(self): |
| 34 |
try: |
| 35 |
import hvac |
| 36 |
self.hvac = hvac |
| 37 |
except ImportError as e: |
| 38 |
from ansible.module_utils.basic import missing_required_lib |
| 39 |
raise HashiVaultHVACError(error=str(e), msg=missing_required_lib('hvac')) |
| 40 |
|
| 41 |
def get_hvac(self): |
| 42 |
return self.hvac |
| 43 |
|
| 44 |
def get_vault_client( |
| 45 |
self, |
| 46 |
hashi_vault_logout_inferred_token=True, hashi_vault_revoke_on_logout=False, |
| 47 |
**kwargs |
| 48 |
): |
| 49 |
''' |
| 50 |
creates a Vault client with the given kwargs |
| 51 |
|
| 52 |
:param hashi_vault_logout_inferred_token: if True performs "logout" after creation to remove any token that |
| 53 |
the hvac library itself may have read in. Only used if "token" is not included in kwargs. |
| 54 |
:type hashi_vault_logout_implied_token: bool |
| 55 |
|
| 56 |
:param hashi_vault_revoke_on_logout: if True revokes any current token on logout. Only used if a logout is performed. Not recommended. |
| 57 |
:type hashi_vault_revoke_on_logout: bool |
| 58 |
''' |
| 59 |
|
| 60 |
client = self.hvac.Client(**kwargs) |
| 61 |
|
| 62 |
# logout to prevent accidental use of inferred tokens |
| 63 |
# https://github.com/ansible-collections/community.hashi_vault/issues/13 |
| 64 |
if hashi_vault_logout_inferred_token and 'token' not in kwargs: |
| 65 |
client.logout(revoke_token=hashi_vault_revoke_on_logout) |
| 66 |
|
| 67 |
return client |
| 68 |
|
| 69 |
|
| 70 |
class HashiVaultOptionAdapter(object): |
| 71 |
''' |
| 72 |
The purpose of this class is to provide a standard interface for option getting/setting |
| 73 |
within module_utils code, since the processes are so different in plugins and modules. |
| 74 |
|
| 75 |
Attention is paid to ensuring that in plugins we use the methods provided by Config Manager, |
| 76 |
but to allow flexibility to create an adapter to work with other sources, hence the design |
| 77 |
of defining specific methods exposed, and having them call provided function references. |
| 78 |
''' |
| 79 |
# More context on the need to call Config Manager methods: |
| 80 |
# |
| 81 |
# Some issues raised around deprecations in plugins not being processed led to comments |
| 82 |
# from core maintainers around the need to use Config Manager and also to ensure any |
| 83 |
# option needed is always retrieved using AnsiblePlugin.get_option(). At the time of this |
| 84 |
# writing, based on the way Config Manager is implemented, that's not actually necessary, |
| 85 |
# and calling AnsiblePlugin.set_options() to initialize them is enough. But that's not |
| 86 |
# guaranteed to stay that way, if get_option() is used to "trigger" internal events. |
| 87 |
# |
| 88 |
# More reading: |
| 89 |
# - https://github.com/ansible-collections/community.hashi_vault/issues/35 |
| 90 |
# - https://github.com/ansible/ansible/issues/73051 |
| 91 |
# - https://github.com/ansible/ansible/pull/73058 |
| 92 |
# - https://github.com/ansible/ansible/pull/73239 |
| 93 |
# - https://github.com/ansible/ansible/pull/73240 |
| 94 |
|
| 95 |
@classmethod |
| 96 |
def from_dict(cls, dict): |
| 97 |
return cls( |
| 98 |
getter=dict.__getitem__, |
| 99 |
setter=dict.__setitem__, |
| 100 |
haver=lambda key: key in dict, |
| 101 |
updater=dict.update, |
| 102 |
defaultsetter=dict.setdefault, |
| 103 |
defaultgetter=dict.get, |
| 104 |
) |
| 105 |
|
| 106 |
@classmethod |
| 107 |
def from_ansible_plugin(cls, plugin): |
| 108 |
return cls( |
| 109 |
getter=plugin.get_option, |
| 110 |
setter=plugin.set_option, |
| 111 |
haver=plugin.has_option if hasattr(plugin, 'has_option') else None, |
| 112 |
# AnsiblePlugin.has_option was added in 2.10, see https://github.com/ansible/ansible/pull/61078 |
| 113 |
) |
| 114 |
|
| 115 |
@classmethod |
| 116 |
def from_ansible_module(cls, module): |
| 117 |
return cls.from_dict(module.params) |
| 118 |
|
| 119 |
def __init__( |
| 120 |
self, |
| 121 |
getter, setter, |
| 122 |
haver=None, updater=None, getitems=None, getfiltereditems=None, getfilleditems=None, defaultsetter=None, defaultgetter=None): |
| 123 |
|
| 124 |
def _default_default_setter(key, default=None): |
| 125 |
try: |
| 126 |
value = self.get_option(key) |
| 127 |
return value |
| 128 |
except KeyError: |
| 129 |
self.set_option(key, default) |
| 130 |
return default |
| 131 |
|
| 132 |
def _default_updater(**kwargs): |
| 133 |
for key, value in kwargs.items(): |
| 134 |
self.set_option(key, value) |
| 135 |
|
| 136 |
def _default_haver(key): |
| 137 |
try: |
| 138 |
self.get_option(key) |
| 139 |
return True |
| 140 |
except KeyError: |
| 141 |
return False |
| 142 |
|
| 143 |
def _default_getitems(*args): |
| 144 |
return dict((key, self.get_option(key)) for key in args) |
| 145 |
|
| 146 |
def _default_getfiltereditems(filter, *args): |
| 147 |
return dict((key, value) for key, value in self.get_options(*args).items() if filter(key, value)) |
| 148 |
|
| 149 |
def _default_getfilleditems(*args): |
| 150 |
return self.get_filtered_options(lambda k, v: v is not None, *args) |
| 151 |
|
| 152 |
def _default_default_getter(key, default): |
| 153 |
try: |
| 154 |
return self.get_option(key) |
| 155 |
except KeyError: |
| 156 |
return default |
| 157 |
|
| 158 |
self._getter = getter |
| 159 |
self._setter = setter |
| 160 |
|
| 161 |
self._haver = haver or _default_haver |
| 162 |
self._updater = updater or _default_updater |
| 163 |
self._getitems = getitems or _default_getitems |
| 164 |
self._getfiltereditems = getfiltereditems or _default_getfiltereditems |
| 165 |
self._getfilleditems = getfilleditems or _default_getfilleditems |
| 166 |
self._defaultsetter = defaultsetter or _default_default_setter |
| 167 |
self._defaultgetter = defaultgetter or _default_default_getter |
| 168 |
|
| 169 |
def get_option(self, key): |
| 170 |
return self._getter(key) |
| 171 |
|
| 172 |
def get_option_default(self, key, default=None): |
| 173 |
return self._defaultgetter(key, default) |
| 174 |
|
| 175 |
def set_option(self, key, value): |
| 176 |
return self._setter(key, value) |
| 177 |
|
| 178 |
def set_option_default(self, key, default=None): |
| 179 |
return self._defaultsetter(key, default) |
| 180 |
|
| 181 |
def has_option(self, key): |
| 182 |
return self._haver(key) |
| 183 |
|
| 184 |
def set_options(self, **kwargs): |
| 185 |
return self._updater(**kwargs) |
| 186 |
|
| 187 |
def get_options(self, *args): |
| 188 |
return self._getitems(*args) |
| 189 |
|
| 190 |
def get_filtered_options(self, filter, *args): |
| 191 |
return self._getfiltereditems(filter, *args) |
| 192 |
|
| 193 |
def get_filled_options(self, *args): |
| 194 |
return self._getfilleditems(*args) |
| 195 |
|
| 196 |
|
| 197 |
class HashiVaultOptionGroupBase: |
| 198 |
'''A base class for class option group classes''' |
| 199 |
|
| 200 |
def __init__(self, option_adapter): |
| 201 |
self._options = option_adapter |
| 202 |
|
| 203 |
def process_late_binding_env_vars(self, option_vars): |
| 204 |
'''looks through a set of options, and if empty/None, looks for a value in specified env vars, or sets an optional default''' |
| 205 |
# see https://github.com/ansible-collections/community.hashi_vault/issues/10 |
| 206 |
# |
| 207 |
# Options which seek to use environment vars that are not Ansible-specific |
| 208 |
# should load those as values of last resort, so that INI values can override them. |
| 209 |
# For default processing, list such options and vars here. |
| 210 |
# Alternatively, process them in another appropriate place like an auth method's |
| 211 |
# validate_ method. |
| 212 |
# |
| 213 |
# key = option_name |
| 214 |
# value = dict with "env" key which is a list of env vars (in order of those checked first; process stops when value is found), |
| 215 |
# and an optional "default" key whose value will be set if none of the env vars are found. |
| 216 |
# An optional boolean "required" key can be used to specify that a value is required, so raise if one is not found. |
| 217 |
|
| 218 |
for opt, config in option_vars.items(): |
| 219 |
for env in config['env']: |
| 220 |
# we use has_option + get_option rather than get_option_default |
| 221 |
# because we will only override if the option exists and |
| 222 |
# is None, not if it's missing. For plugins, that is the usual, |
| 223 |
# but for modules, they may have to set the default to None |
| 224 |
# in the argspec if it has late binding env vars. |
| 225 |
if self._options.has_option(opt) and self._options.get_option(opt) is None: |
| 226 |
self._options.set_option(opt, os.environ.get(env)) |
| 227 |
|
| 228 |
if 'default' in config and self._options.has_option(opt) and self._options.get_option(opt) is None: |
| 229 |
self._options.set_option(opt, config['default']) |
| 230 |
|
| 231 |
if 'required' in config and self._options.get_option_default(opt) is None: |
| 232 |
raise HashiVaultValueError("Required option %s was not set." % opt) |
| 233 |
|
| 234 |
|
| 235 |
class HashiVaultAuthMethodBase(HashiVaultOptionGroupBase): |
| 236 |
'''Base class for individual auth method implementations''' |
| 237 |
|
| 238 |
def __init__(self, option_adapter, warning_callback, deprecate_callback): |
| 239 |
super(HashiVaultAuthMethodBase, self).__init__(option_adapter) |
| 240 |
self._warner = warning_callback |
| 241 |
self._deprecator = deprecate_callback |
| 242 |
|
| 243 |
def validate(self): |
| 244 |
'''Validates the given auth method as much as possible without calling Vault.''' |
| 245 |
raise NotImplementedError('validate must be implemented') |
| 246 |
|
| 247 |
def authenticate(self, client, use_token=True): |
| 248 |
'''Authenticates against Vault, returns a token.''' |
| 249 |
raise NotImplementedError('authenticate must be implemented') |
| 250 |
|
| 251 |
def validate_by_required_fields(self, *field_names): |
| 252 |
missing = [field for field in field_names if self._options.get_option_default(field) is None] |
| 253 |
|
| 254 |
if missing: |
| 255 |
raise HashiVaultValueError("Authentication method %s requires options %r to be set, but these are missing: %r" % (self.NAME, field_names, missing)) |
| 256 |
|
| 257 |
def warn(self, message): |
| 258 |
self._warner(message) |
| 259 |
|
| 260 |
def deprecate(self, message, version=None, date=None, collection_name=None): |
| 261 |
self._deprecator(message, version=version, date=date, collection_name=collection_name) |