|
| 1 | +# coding=utf-8 |
| 2 | +""" |
| 3 | +HTTP Client Library Adapters |
| 4 | +
|
| 5 | +""" |
| 6 | +import logging |
| 7 | + |
| 8 | +import requests |
| 9 | +import requests.exceptions |
| 10 | + |
| 11 | +from hvac import utils |
| 12 | +from abc import ABCMeta, abstractmethod |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class Adapter(object): |
| 18 | + """Abstract base class used when constructing adapters for use with the Client class.""" |
| 19 | + __metaclass__ = ABCMeta |
| 20 | + |
| 21 | + @staticmethod |
| 22 | + def urljoin(*args): |
| 23 | + """Joins given arguments into a url. Trailing and leading slashes are stripped for each argument. |
| 24 | +
|
| 25 | + :param args: Multiple parts of a URL to be combined into one string. |
| 26 | + :type args: str |
| 27 | + :return: Full URL combining all provided arguments |
| 28 | + :rtype: str |
| 29 | + """ |
| 30 | + |
| 31 | + return '/'.join(map(lambda x: str(x).strip('/'), args)) |
| 32 | + |
| 33 | + @abstractmethod |
| 34 | + def close(self): |
| 35 | + raise NotImplemented |
| 36 | + |
| 37 | + @abstractmethod |
| 38 | + def get(self, url, **kwargs): |
| 39 | + raise NotImplemented |
| 40 | + |
| 41 | + @abstractmethod |
| 42 | + def post(self, url, **kwargs): |
| 43 | + raise NotImplemented |
| 44 | + |
| 45 | + @abstractmethod |
| 46 | + def put(self, url, **kwargs): |
| 47 | + raise NotImplemented |
| 48 | + |
| 49 | + @abstractmethod |
| 50 | + def delete(self, url, **kwargs): |
| 51 | + raise NotImplemented |
| 52 | + |
| 53 | + @abstractmethod |
| 54 | + def request(self, method, url, headers=None, **kwargs): |
| 55 | + raise NotImplemented |
| 56 | + |
| 57 | + |
| 58 | +class Request(Adapter): |
| 59 | + """The Request adapter class""" |
| 60 | + |
| 61 | + def __init__(self, base_uri='http://localhost:8200', token=None, cert=None, verify=True, timeout=30, proxies=None, |
| 62 | + allow_redirects=True, session=None): |
| 63 | + """Create a new request adapter instance. |
| 64 | +
|
| 65 | + :param base_uri: Base URL for the Vault instance being addressed. |
| 66 | + :type base_uri: str |
| 67 | + :param token: Authentication token to include in requests sent to Vault. |
| 68 | + :type token: str |
| 69 | + :param cert: Certificates for use in requests sent to the Vault instance. This should be a tuple with the |
| 70 | + certificate and then key. |
| 71 | + :type cert: tuple |
| 72 | + :param verify: Flag to indicate whether TLS verification should be performed when sending requests to Vault. |
| 73 | + :type verify: bool |
| 74 | + :param timeout: The timeout value for requests sent to Vault. |
| 75 | + :type timeout: int |
| 76 | + :param proxies: Proxies to use when preforming requests. |
| 77 | + See: http://docs.python-requests.org/en/master/user/advanced/#proxies |
| 78 | + :type proxies: dict |
| 79 | + :param allow_redirects: Whether to follow redirects when sending requests to Vault. |
| 80 | + :type allow_redirects: bool |
| 81 | + :param session: Optional session object to use when performing request. |
| 82 | + :type session: request.Session |
| 83 | + """ |
| 84 | + if not session: |
| 85 | + session = requests.Session() |
| 86 | + |
| 87 | + self.base_uri = base_uri |
| 88 | + self.token = token |
| 89 | + self.session = session |
| 90 | + self.allow_redirects = allow_redirects |
| 91 | + |
| 92 | + self._kwargs = { |
| 93 | + 'cert': cert, |
| 94 | + 'verify': verify, |
| 95 | + 'timeout': timeout, |
| 96 | + 'proxies': proxies, |
| 97 | + } |
| 98 | + |
| 99 | + def close(self): |
| 100 | + """Close the underlying Requests session. |
| 101 | + """ |
| 102 | + self.session.close() |
| 103 | + |
| 104 | + def get(self, url, **kwargs): |
| 105 | + """Performs a GET request. |
| 106 | +
|
| 107 | + :param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri |
| 108 | + attribute. |
| 109 | + :type url: str |
| 110 | + :param kwargs: Additional keyword arguments to include in the requests call. |
| 111 | + :type kwargs: dict |
| 112 | + :return: The response of the request. |
| 113 | + :rtype: requests.Response |
| 114 | + """ |
| 115 | + return self.request('get', url, **kwargs) |
| 116 | + |
| 117 | + def post(self, url, **kwargs): |
| 118 | + """Performs a POST request. |
| 119 | +
|
| 120 | + :param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri |
| 121 | + attribute. |
| 122 | + :type url: str |
| 123 | + :param kwargs: Additional keyword arguments to include in the requests call. |
| 124 | + :type kwargs: dict |
| 125 | + :return: The response of the request. |
| 126 | + :rtype: requests.Response |
| 127 | + """ |
| 128 | + return self.request('post', url, **kwargs) |
| 129 | + |
| 130 | + def put(self, url, **kwargs): |
| 131 | + """Performs a PUT request. |
| 132 | +
|
| 133 | + :param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri |
| 134 | + attribute. |
| 135 | + :type url: str |
| 136 | + :param kwargs: Additional keyword arguments to include in the requests call. |
| 137 | + :type kwargs: dict |
| 138 | + :return: The response of the request. |
| 139 | + :rtype: requests.Response |
| 140 | + """ |
| 141 | + return self.request('put', url, **kwargs) |
| 142 | + |
| 143 | + def delete(self, url, **kwargs): |
| 144 | + """Performs a DELETE request. |
| 145 | +
|
| 146 | + :param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri |
| 147 | + attribute. |
| 148 | + :type url: str |
| 149 | + :param kwargs: Additional keyword arguments to include in the requests call. |
| 150 | + :type kwargs: dict |
| 151 | + :return: The response of the request. |
| 152 | + :rtype: requests.Response |
| 153 | + """ |
| 154 | + return self.request('delete', url, **kwargs) |
| 155 | + |
| 156 | + def request(self, method, url, headers=None, **kwargs): |
| 157 | + """ |
| 158 | +
|
| 159 | + :param method: HTTP method to use with the request. E.g., GET, POST, etc. |
| 160 | + :type method: str |
| 161 | + :param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri |
| 162 | + attribute. |
| 163 | + :type url: str |
| 164 | + :param headers: Additional headers to include with the request. |
| 165 | + :type headers: dict |
| 166 | + :param kwargs: Additional keyword arguments to include in the requests call. |
| 167 | + :type kwargs: dict |
| 168 | + :return: The response of the request. |
| 169 | + :rtype: requests.Response |
| 170 | + """ |
| 171 | + url = self.urljoin(self.base_uri, url) |
| 172 | + |
| 173 | + if not headers: |
| 174 | + headers = {} |
| 175 | + |
| 176 | + if self.token: |
| 177 | + headers['X-Vault-Token'] = self.token |
| 178 | + |
| 179 | + wrap_ttl = kwargs.pop('wrap_ttl', None) |
| 180 | + if wrap_ttl: |
| 181 | + headers['X-Vault-Wrap-TTL'] = str(wrap_ttl) |
| 182 | + |
| 183 | + _kwargs = self._kwargs.copy() |
| 184 | + _kwargs.update(kwargs) |
| 185 | + |
| 186 | + response = self.session.request(method, url, headers=headers, |
| 187 | + allow_redirects=False, **_kwargs) |
| 188 | + |
| 189 | + # NOTE(ianunruh): workaround for https://github.com/ianunruh/hvac/issues/51 |
| 190 | + while response.is_redirect and self.allow_redirects: |
| 191 | + url = self.urljoin(self.base_uri, response.headers['Location']) |
| 192 | + response = self.session.request(method, url, headers=headers, |
| 193 | + allow_redirects=False, **_kwargs) |
| 194 | + |
| 195 | + if response.status_code >= 400 and response.status_code < 600: |
| 196 | + text = errors = None |
| 197 | + if response.headers.get('Content-Type') == 'application/json': |
| 198 | + errors = response.json().get('errors') |
| 199 | + if errors is None: |
| 200 | + text = response.text |
| 201 | + utils.raise_for_error(response.status_code, text, errors=errors) |
| 202 | + |
| 203 | + return response |
0 commit comments