Debian Codegraph @

heatclient/common/http.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import copy
17 import hashlib
18 import logging
19 import os
20 import socket
21
22 from keystoneauth1 import adapter
23 from oslo_serialization import jsonutils
24 from oslo_utils import encodeutils
25 from oslo_utils import importutils
26 import requests
27 from urllib import parse
28
29 from heatclient._i18n import _
30 from heatclient.common import utils
31 from heatclient import exc
32
33 LOG = logging.getLogger(__name__)
34 USER_AGENT = 'python-heatclient'
35 CHUNKSIZE = 1024 * 64 # 64kB
36 SENSITIVE_HEADERS = ('X-Auth-Token',)
37 osprofiler_web = importutils.try_import("osprofiler.web")
38
39
40 def authenticated_fetcher(hc):
41 """A wrapper around the heat client object to fetch a template."""
42
43 def _do(*args, **kwargs):
44 if isinstance(hc.http_client, SessionClient):
45 method, url = args
46 return hc.http_client.request(url, method, **kwargs).content
47 else:
48 return hc.http_client.raw_request(*args, **kwargs).content
49
50 return _do
51
52
53 def get_system_ca_file():
54 """Return path to system default CA file."""
55 # Standard CA file locations for Debian/Ubuntu, RedHat/Fedora,
56 # Suse, FreeBSD/OpenBSD, MacOSX, and the bundled ca
57 ca_path = ['/etc/ssl/certs/ca-certificates.crt',
58 '/etc/pki/tls/certs/ca-bundle.crt',
59 '/etc/ssl/ca-bundle.pem',
60 '/etc/ssl/cert.pem',
61 '/System/Library/OpenSSL/certs/cacert.pem',
62 requests.certs.where()]
63 for ca in ca_path:
64 LOG.debug("Looking for ca file %s", ca)
65 if os.path.exists(ca):
66 LOG.debug("Using ca file %s", ca)
67 return ca
68 LOG.warning("System ca file could not be found.")
69
70
71 class HTTPClient:
72
73 def __init__(self, endpoint, **kwargs):
74 self.endpoint = endpoint
75 self.auth_url = kwargs.get('auth_url')
76 self.auth_token = kwargs.get('token')
77 self.username = kwargs.get('username')
78 self.password = kwargs.get('password')
79 self.region_name = kwargs.get('region_name')
80 self.include_pass = kwargs.get('include_pass')
81 self.endpoint_url = endpoint
82
83 self.cert_file = kwargs.get('cert_file')
84 self.key_file = kwargs.get('key_file')
85 self.timeout = kwargs.get('timeout')
86
87 self.ssl_connection_params = {
88 'ca_file': kwargs.get('ca_file'),
89 'cert_file': kwargs.get('cert_file'),
90 'key_file': kwargs.get('key_file'),
91 'insecure': kwargs.get('insecure'),
92 }
93
94 self.verify_cert = None
95 if parse.urlparse(endpoint).scheme == "https":
96 if kwargs.get('insecure'):
97 self.verify_cert = False
98 else:
99 self.verify_cert = kwargs.get('ca_file', get_system_ca_file())
100
101 # FIXME(shardy): We need this for compatibility with the oslo apiclient
102 # we should move to inheriting this class from the oslo HTTPClient
103 self.last_request_id = None
104
105 def safe_header(self, name, value):
106 if name in SENSITIVE_HEADERS:
107 # because in python3 byte string handling is ... ug
108 v = value.encode('utf-8')
109 h = hashlib.sha1(v)
110 d = h.hexdigest()
111 return encodeutils.safe_decode(name), "{SHA1}%s" % d
112 else:
113 return (encodeutils.safe_decode(name),
114 encodeutils.safe_decode(value))
115
116 def log_curl_request(self, method, url, kwargs):
117 curl = ['curl -g -i -X %s' % method]
118
119 for (key, value) in kwargs['headers'].items():
120 header = '-H \'%s: %s\'' % self.safe_header(key, value)
121 curl.append(header)
122
123 conn_params_fmt = [
124 ('key_file', '--key %s'),
125 ('cert_file', '--cert %s'),
126 ('ca_file', '--cacert %s'),
127 ]
128 for (key, fmt) in conn_params_fmt:
129 value = self.ssl_connection_params.get(key)
130 if value:
131 curl.append(fmt % value)
132
133 if self.ssl_connection_params.get('insecure'):
134 curl.append('-k')
135
136 if 'data' in kwargs:
137 curl.append('-d \'%s\'' % kwargs['data'])
138
139 if not parse.urlparse(url).netloc:
140 url = self.endpoint + url
141
142 curl.append(url)
143 LOG.debug(' '.join(curl))
144
145 @staticmethod
146 def log_http_response(resp):
147 status = (resp.raw.version / 10.0, resp.status_code, resp.reason)
148 dump = ['\nHTTP/%.1f %s %s' % status]
149 dump.extend([f'{k}: {v}' for k, v in resp.headers.items()])
150 dump.append('')
151 if resp.content:
152 content = resp.content
153 if isinstance(content, bytes):
154 content = content.decode()
155 dump.extend([content, ''])
156 LOG.debug('\n'.join(dump))
157
158 def _http_request(self, url, method, **kwargs):
159 """Send an http request with the specified characteristics.
160
161 Wrapper around requests.request to handle tasks such as
162 setting headers and error handling.
163 """
164 # Copy the kwargs so we can reuse the original in case of redirects
165 kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
166 kwargs['headers'].setdefault('User-Agent', USER_AGENT)
167 if self.auth_token:
168 kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)
169 else:
170 kwargs['headers'].update(self.credentials_headers())
171 if self.auth_url:
172 kwargs['headers'].setdefault('X-Auth-Url', self.auth_url)
173 if self.region_name:
174 kwargs['headers'].setdefault('X-Region-Name', self.region_name)
175 if self.include_pass and 'X-Auth-Key' not in kwargs['headers']:
176 kwargs['headers'].update(self.credentials_headers())
177 if osprofiler_web:
178 kwargs['headers'].update(osprofiler_web.get_trace_id_headers())
179
180 self.log_curl_request(method, url, kwargs)
181
182 if self.cert_file and self.key_file:
183 kwargs['cert'] = (self.cert_file, self.key_file)
184
185 if self.verify_cert is not None:
186 kwargs['verify'] = self.verify_cert
187
188 if self.timeout is not None:
189 kwargs['timeout'] = float(self.timeout)
190
191 # Allow caller to specify not to follow redirects, in which case we
192 # just return the redirect response. Useful for using stacks:lookup.
193 redirect = kwargs.pop('redirect', True)
194
195 # Since requests does not follow the RFC when doing redirection to sent
196 # back the same method on a redirect we are simply bypassing it. For
197 # example if we do a DELETE/POST/PUT on a URL and we get a 302 RFC says
198 # that we should follow that URL with the same method as before,
199 # requests doesn't follow that and send a GET instead for the method.
200 # Hopefully this could be fixed as they say in a comment in a future
201 # point version i.e.: 3.x
202 # See issue: https://github.com/kennethreitz/requests/issues/1704
203 allow_redirects = False
204
205 # Use fully qualified URL from response header for redirects
206 if not parse.urlparse(url).netloc:
207 url = self.endpoint_url + url
208
209 try:
210 resp = requests.request(
211 method,
212 url,
213 allow_redirects=allow_redirects,
214 **kwargs)
215 except socket.gaierror as e:
216 message = (_("Error finding address for %(url)s: %(e)s") %
217 {'url': self.endpoint_url + url, 'e': e})
218 raise exc.InvalidEndpoint(message=message)
219 except (OSError, TimeoutError) as e:
220 endpoint = self.endpoint
221 message = (_("Error communicating with %(endpoint)s %(e)s") %
222 {'endpoint': endpoint, 'e': e})
223 raise exc.CommunicationError(message=message)
224
225 self.log_http_response(resp)
226 txt_content = encodeutils.safe_decode(resp.content, 'utf-8')
227 if not ('X-Auth-Key' in kwargs['headers']) and (
228 resp.status_code == 401 or
229 (resp.status_code == 500 and "(HTTP 401)" in txt_content)):
230 raise exc.HTTPUnauthorized(_("Authentication failed: %s")
231 % resp.content)
232 elif 400 <= resp.status_code < 600:
233 raise exc.from_response(resp)
234 elif resp.status_code in (301, 302, 305):
235 # Redirected. Reissue the request to the new location,
236 # unless caller specified redirect=False
237 if redirect:
238 location = resp.headers.get('location')
239 if not location:
240 message = _("Location not returned with redirect")
241 raise exc.InvalidEndpoint(message=message)
242 resp = self._http_request(location, method, **kwargs)
243 elif resp.status_code == 300:
244 raise exc.from_response(resp)
245
246 return resp
247
248 def credentials_headers(self):
249 creds = {}
250 # NOTE(dhu): (shardy) When deferred_auth_method=password, Heat
251 # encrypts and stores username/password. For Keystone v3, the
252 # intent is to use trusts since SHARDY is working towards
253 # deferred_auth_method=trusts as the default.
254 # TODO(dhu): Make Keystone v3 work in Heat standalone mode. Maye
255 # require X-Auth-User-Domain.
256 if self.username:
257 creds['X-Auth-User'] = self.username
258 if self.password:
259 creds['X-Auth-Key'] = self.password
260 return creds
261
262 def json_request(self, method, url, **kwargs):
263 kwargs.setdefault('headers', {})
264 kwargs['headers'].setdefault('Content-Type', 'application/json')
265 kwargs['headers'].setdefault('Accept', 'application/json')
266
267 if 'data' in kwargs:
268 kwargs['data'] = jsonutils.dumps(kwargs['data'])
269
270 resp = self._http_request(url, method, **kwargs)
271 body = utils.get_response_body(resp)
272 return resp, body
273
274 def raw_request(self, method, url, **kwargs):
275 kwargs.setdefault('headers', {})
276 kwargs['headers'].setdefault('Content-Type',
277 'application/octet-stream')
278 return self._http_request(url, method, **kwargs)
279
280 def client_request(self, method, url, **kwargs):
281 resp, body = self.json_request(method, url, **kwargs)
282 return resp
283
284 def head(self, url, **kwargs):
285 return self.client_request("HEAD", url, **kwargs)
286
287 def get(self, url, **kwargs):
288 return self.client_request("GET", url, **kwargs)
289
290 def post(self, url, **kwargs):
291 return self.client_request("POST", url, **kwargs)
292
293 def put(self, url, **kwargs):
294 return self.client_request("PUT", url, **kwargs)
295
296 def delete(self, url, **kwargs):
297 return self.raw_request("DELETE", url, **kwargs)
298
299 def patch(self, url, **kwargs):
300 return self.client_request("PATCH", url, **kwargs)
301
302
303 class SessionClient(adapter.LegacyJsonAdapter):
304 """HTTP client based on Keystone client session."""
305
306 def request(self, url, method, **kwargs):
307 redirect = kwargs.get('redirect')
308 kwargs.setdefault('user_agent', USER_AGENT)
309
310 headers = kwargs.setdefault('headers', {})
311 headers.setdefault('Content-Type', 'application/json')
312
313 if 'data' in kwargs:
314 kwargs['data'] = jsonutils.dumps(kwargs['data'])
315
316 resp, body = super().request(
317 url, method,
318 raise_exc=False,
319 **kwargs)
320
321 if 400 <= resp.status_code < 600:
322 raise exc.from_response(resp)
323 elif resp.status_code in (301, 302, 305):
324 if redirect:
325 location = resp.headers.get('location')
326 path = self.strip_endpoint(location)
327 resp = self.request(path, method, **kwargs)
328 elif resp.status_code == 300:
329 raise exc.from_response(resp)
330
331 return resp
332
333 def credentials_headers(self):
334 return {}
335
336 def strip_endpoint(self, location):
337 if location is None:
338 message = _("Location not returned with 302")
339 raise exc.InvalidEndpoint(message=message)
340 if (self.endpoint_override is not None and
341 location.lower().startswith(self.endpoint_override.lower())):
342 return location[len(self.endpoint_override):]
343 else:
344 return location
345
346
347 def _construct_http_client(endpoint=None, username=None, password=None,
348 include_pass=None, endpoint_type=None,
349 auth_url=None, **kwargs):
350 session = kwargs.pop('session', None)
351 auth = kwargs.pop('auth', None)
352
353 if session:
354 if 'endpoint_override' not in kwargs and endpoint:
355 kwargs['endpoint_override'] = endpoint
356
357 if 'service_type' not in kwargs:
358 kwargs['service_type'] = 'orchestration'
359
360 if 'interface' not in kwargs and endpoint_type:
361 kwargs['interface'] = endpoint_type
362
363 if 'region_name' in kwargs:
364 kwargs['additional_headers'] = {
365 'X-Region-Name': kwargs['region_name']}
366
367 return SessionClient(session, auth=auth, **kwargs)
368 else:
369 return HTTPClient(endpoint=endpoint, username=username,
370 password=password, include_pass=include_pass,
371 endpoint_type=endpoint_type, auth_url=auth_url,
372 **kwargs)