Debian Codegraph @

ansible_collections/community/hashi_vault/plugins/module_utils/_connection_options.py

raw
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 from ansible.module_utils.common.text.converters import to_text
20
21 from ansible.module_utils.common.validation import (
22 check_type_dict,
23 check_type_str,
24 check_type_bool,
25 check_type_int,
26 )
27
28 from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common import HashiVaultOptionGroupBase
29
30 # we implement retries via the urllib3 Retry class
31 # https://github.com/ansible-collections/community.hashi_vault/issues/58
32 HAS_RETRIES = False
33 try:
34 from requests import Session
35 from requests.adapters import HTTPAdapter
36 try:
37 # try for a standalone urllib3
38 import urllib3
39 HAS_RETRIES = True
40 except ImportError:
41 try:
42 # failing that try for a vendored version within requests
43 from requests.packages import urllib3
44 HAS_RETRIES = True
45 except ImportError:
46 pass
47 except ImportError:
48 pass
49
50
51 class HashiVaultConnectionOptions(HashiVaultOptionGroupBase):
52 '''HashiVault option group class for connection options'''
53
54 OPTIONS = ['url', 'proxies', 'ca_cert', 'validate_certs', 'namespace', 'timeout', 'retries', 'retry_action']
55
56 ARGSPEC = dict(
57 url=dict(type='str', default=None),
58 proxies=dict(type='raw'),
59 ca_cert=dict(type='str', aliases=['cacert'], default=None),
60 validate_certs=dict(type='bool'),
61 namespace=dict(type='str', default=None),
62 timeout=dict(type='int'),
63 retries=dict(type='raw'),
64 retry_action=dict(type='str', choices=['ignore', 'warn'], default='warn'),
65 )
66
67 _LATE_BINDING_ENV_VAR_OPTIONS = {
68 'url': dict(env=['VAULT_ADDR'], required=True),
69 'ca_cert': dict(env=['VAULT_CACERT']),
70 'namespace': dict(env=['VAULT_NAMESPACE']),
71 }
72
73 _RETRIES_DEFAULT_PARAMS = {
74 'status_forcelist': [
75 # https://www.vaultproject.io/api#http-status-codes
76 # 429 is usually a "too many requests" status, but in Vault it's the default health status response for standby nodes.
77 412, # Precondition failed. Returned on Enterprise when a request can't be processed yet due to some missing eventually consistent data.
78 # Should be retried, perhaps with a little backoff.
79 500, # Internal server error. An internal error has occurred, try again later. If the error persists, report a bug.
80 502, # A request to Vault required Vault making a request to a third party; the third party responded with an error of some kind.
81 503, # Vault is down for maintenance or is currently sealed. Try again later.
82 ],
83 (
84 # this field name changed in 1.26.0, and in the interest of supporting a wider range of urllib3 versions
85 # we'll use the new name whenever possible, but fall back seamlessly when needed.
86 # See also:
87 # - https://github.com/urllib3/urllib3/issues/2092
88 # - https://github.com/urllib3/urllib3/blob/main/CHANGES.rst#1260-2020-11-10
89 "allowed_methods" if HAS_RETRIES and hasattr(urllib3.util.Retry.DEFAULT, "allowed_methods") else "method_whitelist"
90 ): None, # None allows retries on all methods, including those which may not be considered idempotent, like POST
91 'backoff_factor': 0.3,
92 }
93
94 def __init__(self, option_adapter, retry_callback_generator=None):
95 super(HashiVaultConnectionOptions, self).__init__(option_adapter)
96 self._retry_callback_generator = retry_callback_generator
97
98 def get_hvac_connection_options(self):
99 '''returns kwargs to be used for constructing an hvac.Client'''
100
101 # validate_certs is only used to optionally change the value of ca_cert
102 def _filter(k, v):
103 return v is not None and k not in ('validate_certs', 'ca_cert')
104
105 # our transformed ca_cert value will become the verify parameter for the hvac client
106 hvopts = self._options.get_filtered_options(_filter, *self.OPTIONS)
107 hvopts['verify'] = self._conopt_verify
108
109 retry_action = hvopts.pop('retry_action')
110 if 'retries' in hvopts:
111 hvopts['session'] = self._get_custom_requests_session(new_callback=self._retry_callback_generator(retry_action), **hvopts.pop('retries'))
112 hvopts['session'].verify = self._conopt_verify
113
114 return hvopts
115
116 def process_connection_options(self):
117 '''executes special processing required for certain options'''
118 self.process_late_binding_env_vars(self._LATE_BINDING_ENV_VAR_OPTIONS)
119
120 self._boolean_or_cacert()
121 self._process_option_proxies()
122 self._process_option_retries()
123
124 def _get_custom_requests_session(self, **retry_kwargs):
125 '''returns a requests.Session to pass to hvac (or None)'''
126
127 if not HAS_RETRIES:
128 # because hvac requires requests which requires urllib3 it's unlikely we'll ever reach this condition.
129 raise NotImplementedError("Retries are unavailable. This may indicate very old versions of one or more of the following: hvac, requests, urllib3.")
130
131 # This is defined here because Retry may not be defined if its import failed.
132 # As mentioned above, that's very unlikely, but it'll fail sanity tests nonetheless if defined with other classes.
133 class CallbackRetry(urllib3.util.Retry):
134 def __init__(self, *args, **kwargs):
135 self._newcb = kwargs.pop('new_callback')
136 super(CallbackRetry, self).__init__(*args, **kwargs)
137
138 def new(self, **kwargs):
139 if self._newcb is not None:
140 self._newcb(self)
141
142 kwargs['new_callback'] = self._newcb
143 return super(CallbackRetry, self).new(**kwargs)
144
145 # We don't want the Retry class raising its own exceptions because that will prevent
146 # hvac from raising its own on various response codes.
147 # We set this here, rather than in the defaults, because if the caller sets their own
148 # dict for retries, we use it directly, but we don't want them to have to remember to always
149 # set raise_on_status=False themselves to get proper error handling.
150 # On the off chance someone does set it, we leave it alone, even though it's probably a mistake.
151 # That will be mentioned in the parameter docs.
152 if 'raise_on_status' not in retry_kwargs:
153 retry_kwargs['raise_on_status'] = False
154 # needs urllib 1.15+ https://github.com/urllib3/urllib3/blob/main/CHANGES.rst#115-2016-04-06
155 # but we should always have newer ones via requests, via hvac
156
157 retry = CallbackRetry(**retry_kwargs)
158
159 adapter = HTTPAdapter(max_retries=retry)
160 sess = Session()
161 sess.mount("https://", adapter)
162 sess.mount("http://", adapter)
163
164 return sess
165
166 def _process_option_retries(self):
167 '''check if retries option is int or dict and interpret it appropriately'''
168 # this method focuses on validating the option, and setting a valid Retry object construction dict
169 # it intentionally does not build the Session object, which will be done elsewhere
170
171 retries_opt = self._options.get_option('retries')
172
173 if retries_opt is None:
174 return
175
176 # we'll start with a copy of our defaults
177 retries = self._RETRIES_DEFAULT_PARAMS.copy()
178
179 try:
180 # try int
181 # on int, retry the specified number of times, and use the defaults for everything else
182 # on zero, disable retries
183 retries_int = check_type_int(retries_opt)
184
185 if retries_int < 0:
186 raise ValueError("Number of retries must be >= 0 (got %i)" % retries_int)
187 elif retries_int == 0:
188 retries = None
189 else:
190 retries['total'] = retries_int
191
192 except TypeError:
193 try:
194 # try dict
195 # on dict, use the value directly (will be used as the kwargs to initialize the Retry instance)
196 retries = check_type_dict(retries_opt)
197 except TypeError:
198 raise TypeError("retries option must be interpretable as int or dict. Got: %r" % retries_opt)
199
200 self._options.set_option('retries', retries)
201
202 def _process_option_proxies(self):
203 '''check if 'proxies' option is dict or str and set it appropriately'''
204
205 proxies_opt = self._options.get_option('proxies')
206
207 if proxies_opt is None:
208 return
209
210 try:
211 # if it can be interpreted as dict
212 # do it
213 proxies = check_type_dict(proxies_opt)
214 except TypeError:
215 # if it can't be interpreted as dict
216 proxy = check_type_str(proxies_opt)
217 # but can be interpreted as str
218 # use this str as http and https proxy
219 proxies = {
220 'http': proxy,
221 'https': proxy,
222 }
223
224 # record the new/interpreted value for 'proxies' option
225 self._options.set_option('proxies', proxies)
226
227 def _boolean_or_cacert(self):
228 # This is needed because of this (https://hvac.readthedocs.io/en/stable/source/hvac_v1.html):
229 #
230 # # verify (Union[bool,str]) - Either a boolean to indicate whether TLS verification should
231 # # be performed when sending requests to Vault, or a string pointing at the CA bundle to use for verification.
232 #
233 '''return a bool or cacert'''
234 ca_cert = self._options.get_option('ca_cert')
235
236 validate_certs = self._options.get_option('validate_certs')
237
238 if validate_certs is None:
239 # Validate certs option was not explicitly set
240
241 # Check if VAULT_SKIP_VERIFY is set
242 vault_skip_verify = os.environ.get('VAULT_SKIP_VERIFY')
243
244 if vault_skip_verify is not None:
245 # VAULT_SKIP_VERIFY is set
246 try:
247 # Check that we have a boolean value
248 vault_skip_verify = check_type_bool(vault_skip_verify)
249 except TypeError:
250 # Not a boolean value fallback to default value (True)
251 validate_certs = True
252 else:
253 # Use the inverse of VAULT_SKIP_VERIFY
254 validate_certs = not vault_skip_verify
255 else:
256 validate_certs = True
257
258 if not (validate_certs and ca_cert):
259 self._conopt_verify = validate_certs
260 else:
261 self._conopt_verify = to_text(ca_cert, errors='surrogate_or_strict')