518f47f79cf7e6f675bc3c6f9f87b89c88390a85
[osm/NBI.git] / osm_nbi / authconn_keystone.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018 Whitestack, LLC
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16 #
17 # For those usages not covered by the Apache License, Version 2.0 please
18 # contact: esousa@whitestack.com or glavado@whitestack.com
19 ##
20
21 """
22 AuthconnKeystone implements implements the connector for
23 Openstack Keystone and leverages the RBAC model, to bring
24 it for OSM.
25 """
26 import time
27
28 __author__ = "Eduardo Sousa <esousa@whitestack.com>"
29 __date__ = "$27-jul-2018 23:59:59$"
30
31 from authconn import Authconn, AuthException, AuthconnOperationException
32
33 import logging
34 import requests
35 from keystoneauth1 import session
36 from keystoneauth1.identity import v3
37 from keystoneauth1.exceptions.base import ClientException
38 from keystoneauth1.exceptions.http import Conflict
39 from keystoneclient.v3 import client
40 from http import HTTPStatus
41
42
43 class AuthconnKeystone(Authconn):
44 def __init__(self, config):
45 Authconn.__init__(self, config)
46
47 self.logger = logging.getLogger("nbi.authenticator.keystone")
48
49 self.auth_url = "http://{0}:{1}/v3".format(config.get("auth_url", "keystone"), config.get("auth_port", "5000"))
50 self.user_domain_name = config.get("user_domain_name", "default")
51 self.admin_project = config.get("service_project", "service")
52 self.admin_username = config.get("service_username", "nbi")
53 self.admin_password = config.get("service_password", "nbi")
54 self.project_domain_name = config.get("project_domain_name", "default")
55
56 # Waiting for Keystone to be up
57 available = None
58 counter = 300
59 while available is None:
60 time.sleep(1)
61 try:
62 result = requests.get(self.auth_url)
63 available = True if result.status_code == 200 else None
64 except Exception:
65 counter -= 1
66 if counter == 0:
67 raise AuthException("Keystone not available after 300s timeout")
68
69 self.auth = v3.Password(user_domain_name=self.user_domain_name,
70 username=self.admin_username,
71 password=self.admin_password,
72 project_domain_name=self.project_domain_name,
73 project_name=self.admin_project,
74 auth_url=self.auth_url)
75 self.sess = session.Session(auth=self.auth)
76 self.keystone = client.Client(session=self.sess)
77
78 def authenticate_with_user_password(self, user, password):
79 """
80 Authenticate a user using username and password.
81
82 :param user: username
83 :param password: password
84 :return: an unscoped token that grants access to project list
85 """
86 try:
87 user_id = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0].id
88 project_names = [project.name for project in self.keystone.projects.list(user=user_id)]
89
90 token = self.keystone.get_raw_token_from_identity_service(
91 auth_url=self.auth_url,
92 username=user,
93 password=password,
94 user_domain_name=self.user_domain_name,
95 project_domain_name=self.project_domain_name)
96
97 return token["auth_token"], project_names
98 except ClientException:
99 self.logger.exception("Error during user authentication using keystone. Method: basic")
100 raise AuthException("Error during user authentication using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
101
102 def authenticate_with_token(self, token, project=None):
103 """
104 Authenticate a user using a token. Can be used to revalidate the token
105 or to get a scoped token.
106
107 :param token: a valid token.
108 :param project: (optional) project for a scoped token.
109 :return: return a revalidated token, scoped if a project was passed or
110 the previous token was already scoped.
111 """
112 try:
113 token_info = self.keystone.tokens.validate(token=token)
114 projects = self.keystone.projects.list(user=token_info["user"]["id"])
115 project_names = [project.name for project in projects]
116
117 new_token = self.keystone.get_raw_token_from_identity_service(
118 auth_url=self.auth_url,
119 token=token,
120 project_name=project,
121 user_domain_name=self.user_domain_name,
122 project_domain_name=self.project_domain_name)
123
124 return new_token["auth_token"], project_names
125 except ClientException:
126 self.logger.exception("Error during user authentication using keystone. Method: bearer")
127 raise AuthException("Error during user authentication using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
128
129 def validate_token(self, token):
130 """
131 Check if the token is valid.
132
133 :param token: token to validate
134 :return: dictionary with information associated with the token. If the
135 token is not valid, returns None.
136 """
137 if not token:
138 return
139
140 try:
141 token_info = self.keystone.tokens.validate(token=token)
142
143 return token_info
144 except ClientException:
145 self.logger.exception("Error during token validation using keystone")
146 raise AuthException("Error during token validation using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
147
148 def revoke_token(self, token):
149 """
150 Invalidate a token.
151
152 :param token: token to be revoked
153 """
154 try:
155 self.logger.info("Revoking token: " + token)
156 self.keystone.tokens.revoke_token(token=token)
157
158 return True
159 except ClientException:
160 self.logger.exception("Error during token revocation using keystone")
161 raise AuthException("Error during token revocation using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
162
163 def get_project_list(self, token):
164 """
165 Get all the projects associated with a user.
166
167 :param token: valid token
168 :return: list of projects
169 """
170 try:
171 token_info = self.keystone.tokens.validate(token=token)
172 projects = self.keystone.projects.list(user=token_info["user"]["id"])
173 project_names = [project.name for project in projects]
174
175 return project_names
176 except ClientException:
177 self.logger.exception("Error during user project listing using keystone")
178 raise AuthException("Error during user project listing using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
179
180 def get_role_list(self, token):
181 """
182 Get role list for a scoped project.
183
184 :param token: scoped token.
185 :return: returns the list of roles for the user in that project. If
186 the token is unscoped it returns None.
187 """
188 try:
189 token_info = self.keystone.tokens.validate(token=token)
190 roles_info = self.keystone.roles.list(user=token_info["user"]["id"], project=token_info["project"]["id"])
191
192 roles = [role.name for role in roles_info]
193
194 return roles
195 except ClientException:
196 self.logger.exception("Error during user role listing using keystone")
197 raise AuthException("Error during user role listing using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
198
199 def create_user(self, user, password):
200 """
201 Create a user.
202
203 :param user: username.
204 :param password: password.
205 :raises AuthconnOperationException: if user creation failed.
206 """
207 try:
208 self.keystone.users.create(user, password=password, domain=self.user_domain_name)
209 except ClientException:
210 self.logger.exception("Error during user creation using keystone")
211 raise AuthconnOperationException("Error during user creation using Keystone")
212
213 def change_password(self, user, new_password):
214 """
215 Change the user password.
216
217 :param user: username.
218 :param new_password: new password.
219 :raises AuthconnOperationException: if user password change failed.
220 """
221 try:
222 user_obj = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0]
223 self.keystone.users.update(user_obj, password=new_password)
224 except ClientException:
225 self.logger.exception("Error during user password update using keystone")
226 raise AuthconnOperationException("Error during user password update using Keystone")
227
228 def delete_user(self, user):
229 """
230 Delete user.
231
232 :param user: username.
233 :raises AuthconnOperationException: if user deletion failed.
234 """
235 try:
236 user_obj = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0]
237 self.keystone.users.delete(user_obj)
238 except ClientException:
239 self.logger.exception("Error during user deletion using keystone")
240 raise AuthconnOperationException("Error during user deletion using Keystone")
241
242 def create_role(self, role):
243 """
244 Create a role.
245
246 :param role: role name.
247 :raises AuthconnOperationException: if role creation failed.
248 """
249 try:
250 self.keystone.roles.create(role)
251 except Conflict as ex:
252 self.logger.info("Duplicate entry: %s", str(ex))
253 except ClientException:
254 self.logger.exception("Error during role creation using keystone")
255 raise AuthconnOperationException("Error during role creation using Keystone")
256
257 def delete_role(self, role):
258 """
259 Delete a role.
260
261 :param role: role name.
262 :raises AuthconnOperationException: if role deletion failed.
263 """
264 try:
265 role_obj = list(filter(lambda x: x.name == role, self.keystone.roles.list()))[0]
266 self.keystone.roles.delete(role_obj)
267 except ClientException:
268 self.logger.exception("Error during role deletion using keystone")
269 raise AuthconnOperationException("Error during role deletion using Keystone")
270
271 def create_project(self, project):
272 """
273 Create a project.
274
275 :param project: project name.
276 :raises AuthconnOperationException: if project creation failed.
277 """
278 try:
279 self.keystone.project.create(project, self.project_domain_name)
280 except ClientException:
281 self.logger.exception("Error during project creation using keystone")
282 raise AuthconnOperationException("Error during project creation using Keystone")
283
284 def delete_project(self, project):
285 """
286 Delete a project.
287
288 :param project: project name.
289 :raises AuthconnOperationException: if project deletion failed.
290 """
291 try:
292 project_obj = list(filter(lambda x: x.name == project, self.keystone.projects.list()))[0]
293 self.keystone.project.delete(project_obj)
294 except ClientException:
295 self.logger.exception("Error during project deletion using keystone")
296 raise AuthconnOperationException("Error during project deletion using Keystone")
297
298 def assign_role_to_user(self, user, project, role):
299 """
300 Assigning a role to a user in a project.
301
302 :param user: username.
303 :param project: project name.
304 :param role: role name.
305 :raises AuthconnOperationException: if role assignment failed.
306 """
307 try:
308 user_obj = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0]
309 project_obj = list(filter(lambda x: x.name == project, self.keystone.projects.list()))[0]
310 role_obj = list(filter(lambda x: x.name == role, self.keystone.roles.list()))[0]
311
312 self.keystone.roles.grant(role_obj, user=user_obj, project=project_obj)
313 except ClientException:
314 self.logger.exception("Error during user role assignment using keystone")
315 raise AuthconnOperationException("Error during user role assignment using Keystone")
316
317 def remove_role_from_user(self, user, project, role):
318 """
319 Remove a role from a user in a project.
320
321 :param user: username.
322 :param project: project name.
323 :param role: role name.
324 :raises AuthconnOperationException: if role assignment revocation failed.
325 """
326 try:
327 user_obj = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0]
328 project_obj = list(filter(lambda x: x.name == project, self.keystone.projects.list()))[0]
329 role_obj = list(filter(lambda x: x.name == role, self.keystone.roles.list()))[0]
330
331 self.keystone.roles.revoke(role_obj, user=user_obj, project=project_obj)
332 except ClientException:
333 self.logger.exception("Error during user role revocation using keystone")
334 raise AuthconnOperationException("Error during user role revocation using Keystone")