Debian Codegraph @

mistralclient/auth/keystone.py

raw symbols SCIP
1 # Copyright 2016 - Nokia Networks
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import logging
16
17 import keystoneauth1.access.service_catalog as sc
18 import keystoneauth1.identity.generic as auth_plugin
19 from keystoneauth1 import session as ks_session
20 import mistralclient.api.httpclient as api
21 from mistralclient import auth as mistral_auth
22 from oslo_serialization import jsonutils
23
24
25 LOG = logging.getLogger(__name__)
26
27
28 class KeystoneAuthHandler(mistral_auth.AuthHandler):
29
30 def authenticate(self, req, session=None):
31 """Perform authentication via Keystone.
32
33 :param req: Request dict containing the parameters required
34 for Keystone authentication.
35 """
36 reqs = self._separate_target_reqs(req)
37 try:
38 result = self._authenticate(reqs, session)
39 except Exception as e:
40 if "Cannot use v2 authentication with domain scope" in str(e):
41 LOG.warning("Client tried to use v2 authentication with "
42 "domain scope. Domain parameters are assumed "
43 "to be erroneously set. Retrying "
44 "authentication without them. "
45 "Request parameters: %s" % str(reqs))
46 domainless_reqs = [reqs[0],
47 self._remove_domain(reqs[1])]
48 result = self._authenticate(domainless_reqs, session)
49 else:
50 raise
51 return result
52
53 @staticmethod
54 def _separate_target_reqs(req):
55 """Separates parameters into target and non-target ones.
56
57 target_* parameters are rekeyed by removing the prefix.
58
59 :param req: Request dict containing the parameters for Keystone
60 authentication.
61 :return: list of [non-target, target] request parameters
62 """
63 r = {}
64 target_r = {}
65 target_prefix = "target_"
66 for key in req:
67 if key.startswith(target_prefix):
68 target_r[key[len(target_prefix):]] = req[key]
69 else:
70 r[key] = req[key]
71
72 return [r, target_r]
73
74 @staticmethod
75 def _remove_domain(req):
76 """Remove all domain parameters from req.
77
78 Keystoneauth with V2 does not accept domain parameters. This
79 is an incompatible change from Keystoneclient but it would
80 unnecessarily break clients of Mistral. It is safe to remove
81 domain parameters if V2 auth is targeted.
82
83 :param req: Request dict containing list of parameters required
84 :return: Request dict without domains
85 """
86 r = {}
87 for key in req:
88 if "domain" not in key:
89 r[key] = req[key]
90 return r
91
92 @staticmethod
93 def _get_auth(api_key=None, auth_token=None, auth_url=None,
94 project_domain_id=None, project_domain_name=None,
95 project_id=None, project_name=None, user_domain_id=None,
96 user_domain_name=None, user_id=None, username=None,
97 **kwargs):
98
99 if project_name and project_id:
100 project_name = None
101 LOG.warning(
102 "Only one of project_name or project_id should be set,"
103 "project_name will be ignored"
104 )
105
106 if username and user_id:
107 username = None
108 LOG.warning(
109 "Only one of username or user_id should be set,"
110 "username will be ignored"
111 )
112
113 auth = {}
114
115 if auth_token:
116 auth = auth_plugin.Token(
117 auth_url=auth_url,
118 project_domain_id=project_domain_id,
119 project_domain_name=project_domain_name,
120 project_id=project_id,
121 project_name=project_name,
122 token=auth_token
123 )
124 elif api_key and (username or user_id):
125 auth = auth_plugin.Password(
126 auth_url=auth_url,
127 password=api_key,
128 project_domain_id=project_domain_id,
129 project_domain_name=project_domain_name,
130 project_id=project_id,
131 project_name=project_name,
132 user_domain_id=user_domain_id,
133 user_domain_name=user_domain_name,
134 user_id=user_id,
135 username=username
136 )
137
138 return auth
139
140 def _authenticate(self, reqs, session=None):
141 """Performs authentication via Keystone.
142
143 :param reqs: Request dict containing list of parameters required
144 for Keystone authentication.
145 :return: Auth response dict
146 """
147 if not isinstance(reqs[0], dict):
148 raise TypeError('The input "req" is not typeof dict.')
149 if not isinstance(reqs[1], dict):
150 raise TypeError('The input "req" is not typeof dict.')
151
152 auth_response = {}
153 req = reqs[0]
154 cacert = req.get('cacert')
155 endpoint_type = req.get('endpoint_type', 'publicURL')
156 insecure = req.get('insecure')
157 mistral_url = req.get('mistral_url')
158 region_name = req.get('region_name')
159 service_type = req.get('service_type', 'workflowv2')
160
161 verify = self._verification_needed(cacert, insecure)
162
163 if not session:
164 auth = self._get_auth(**req)
165
166 if auth:
167 session = ks_session.Session(auth=auth, verify=verify)
168
169 if session:
170 if not mistral_url:
171 try:
172 mistral_url = session.get_endpoint(
173 service_type=service_type,
174 interface=endpoint_type,
175 region_name=region_name
176 )
177 except Exception:
178 mistral_url = None
179
180 auth_response['mistral_url'] = mistral_url
181 auth_response['session'] = session
182
183 target_req = reqs[1]
184
185 if "auth_url" in target_req:
186 target_auth = self._get_auth(**target_req)
187
188 if target_auth:
189
190 # target cacert and insecure
191 cacert = target_req.get('cacert')
192 insecure = target_req.get('insecure')
193
194 verify = self._verification_needed(cacert, insecure)
195
196 target_session = ks_session.Session(
197 auth=target_auth,
198 verify=verify
199 )
200
201 target_auth_headers = target_session.get_auth_headers() or {}
202
203 target_auth_token = target_auth_headers.get('X-Auth-Token')
204
205 auth_response.update({
206 api.TARGET_AUTH_TOKEN: target_auth_token,
207 api.TARGET_PROJECT_ID: target_session.get_project_id(),
208 api.TARGET_USER_ID: target_session.get_user_id(),
209 api.TARGET_AUTH_URI: target_auth._plugin.auth_url,
210 })
211
212 access = target_auth.get_access(target_session)
213 service_catalog = access.service_catalog
214
215 if self._is_service_catalog_v2(service_catalog):
216 access_data = access._data["access"]
217 if not len(access_data['serviceCatalog']):
218 LOG.warning(
219 "Service Catalog empty, some authentication"
220 "credentials may be missing. This can cause"
221 "malfunction in the Mistral action executions.")
222 sc_json = jsonutils.dumps(access_data)
223 auth_response[api.TARGET_SERVICE_CATALOG] = sc_json
224
225 if not auth_response:
226 LOG.debug("No valid token or password + user provided. "
227 "Continuing without authentication")
228 return {}
229
230 return auth_response
231
232 @staticmethod
233 def _verification_needed(cacert, insecure):
234 """Return the verify parameter.
235
236 The value of verify can be either True/False or a cacert.
237
238 :param cacert None or path to CA cert file
239 :param insecure truthy value to switch on SSL verification
240 """
241 if insecure is False or insecure is None:
242 verify = cacert or True
243 else:
244 verify = False
245 return verify
246
247 @staticmethod
248 def _is_service_catalog_v2(catalog):
249 """Check if the service catalog is of type ServiceCatalogV2
250
251 :param catalog: the service catalog
252 :return: True if V2, False otherwise
253 """
254 return type(catalog) is sc.ServiceCatalogV2