blob: 5008c601336b5153d747c222b775cefd19a16801 [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# 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
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
17from uuid import uuid4
18from hashlib import sha256
19from http import HTTPStatus
Eduardo Sousa5c01e192019-05-08 02:35:47 +010020from time import time
tierno23acf402019-08-28 13:36:34 +000021from osm_nbi.validation import user_new_schema, user_edit_schema, project_new_schema, project_edit_schema, \
22 vim_account_new_schema, vim_account_edit_schema, sdn_new_schema, sdn_edit_schema, \
23 wim_account_new_schema, wim_account_edit_schema, roles_new_schema, roles_edit_schema, \
24 validate_input, ValidationError, is_valid_uuid # To check that User/Project Names don't look like UUIDs
25from osm_nbi.base_topic import BaseTopic, EngineException
26from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020027from osm_common.dbbase import deep_update_rfc7396
tiernob24258a2018-10-04 18:39:49 +020028
29__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
30
31
32class UserTopic(BaseTopic):
33 topic = "users"
34 topic_msg = "users"
35 schema_new = user_new_schema
36 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010037 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020038
39 def __init__(self, db, fs, msg):
40 BaseTopic.__init__(self, db, fs, msg)
41
42 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010043 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020044 """
45 Generates a filter dictionary for querying database users.
46 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020048 :return:
49 """
50 if session["admin"]: # allows all
51 return {}
52 else:
53 return {"username": session["username"]}
54
tierno65ca36d2019-02-12 19:27:52 +010055 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020056 # check username not exists
57 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
58 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
59 # check projects
tierno65ca36d2019-02-12 19:27:52 +010060 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020061 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020062 # To allow project addressing by Name as well as ID
63 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
64 fail_on_more=False):
65 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
tiernob24258a2018-10-04 18:39:49 +020066
tiernob4844ab2019-05-23 08:42:12 +000067 def check_conflict_on_del(self, session, _id, db_content):
68 """
69 Check if deletion can be done because of dependencies if it is not force. To override
70 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
71 :param _id: internal _id
72 :param db_content: The database content of this item _id
73 :return: None if ok or raises EngineException with the conflict
74 """
tiernob24258a2018-10-04 18:39:49 +020075 if _id == session["username"]:
76 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
77
78 @staticmethod
79 def format_on_new(content, project_id=None, make_public=False):
80 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +020081 # Removed so that the UUID is kept, to allow User Name modification
82 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +020083 salt = uuid4().hex
84 content["_admin"]["salt"] = salt
85 if content.get("password"):
86 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +010087 if content.get("project_role_mappings"):
delacruzramo01b15d32019-07-02 14:37:47 +020088 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
Eduardo Sousa339ed782019-05-28 14:25:00 +010089
90 if content.get("projects"):
91 content["projects"] += projects
92 else:
93 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +020094
95 @staticmethod
96 def format_on_edit(final_content, edit_content):
97 BaseTopic.format_on_edit(final_content, edit_content)
98 if edit_content.get("password"):
99 salt = uuid4().hex
100 final_content["_admin"]["salt"] = salt
101 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
102 salt.encode('utf-8')).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000103 return None
tiernob24258a2018-10-04 18:39:49 +0200104
tierno65ca36d2019-02-12 19:27:52 +0100105 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200106 if not session["admin"]:
107 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200108 # Names that look like UUIDs are not allowed
109 name = (indata if indata else kwargs).get("username")
110 if is_valid_uuid(name):
111 raise EngineException("Usernames that look like UUIDs are not allowed",
112 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100113 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200114
tierno65ca36d2019-02-12 19:27:52 +0100115 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200116 if not session["admin"]:
117 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200118 # Names that look like UUIDs are not allowed
119 name = indata["username"] if indata else kwargs["username"]
120 if is_valid_uuid(name):
121 raise EngineException("Usernames that look like UUIDs are not allowed",
122 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100123 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200124
125
126class ProjectTopic(BaseTopic):
127 topic = "projects"
128 topic_msg = "projects"
129 schema_new = project_new_schema
130 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100131 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200132
133 def __init__(self, db, fs, msg):
134 BaseTopic.__init__(self, db, fs, msg)
135
tierno65ca36d2019-02-12 19:27:52 +0100136 @staticmethod
137 def _get_project_filter(session):
138 """
139 Generates a filter dictionary for querying database users.
140 Current policy is admin can show all, non admin, only its own user.
141 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
142 :return:
143 """
144 if session["admin"]: # allows all
145 return {}
146 else:
147 return {"_id.cont": session["project_id"]}
148
149 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200150 if not indata.get("name"):
151 raise EngineException("missing 'name'")
152 # check name not exists
153 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
154 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
155
156 @staticmethod
157 def format_on_new(content, project_id=None, make_public=False):
158 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200159 # Removed so that the UUID is kept, to allow Project Name modification
160 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200161
tiernob4844ab2019-05-23 08:42:12 +0000162 def check_conflict_on_del(self, session, _id, db_content):
163 """
164 Check if deletion can be done because of dependencies if it is not force. To override
165 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
166 :param _id: internal _id
167 :param db_content: The database content of this item _id
168 :return: None if ok or raises EngineException with the conflict
169 """
tierno65ca36d2019-02-12 19:27:52 +0100170 if _id in session["project_id"]:
tiernob24258a2018-10-04 18:39:49 +0200171 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
tierno65ca36d2019-02-12 19:27:52 +0100172 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200173 return
174 _filter = {"projects": _id}
175 if self.db.get_list("users", _filter):
176 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
177
tierno65ca36d2019-02-12 19:27:52 +0100178 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200179 if not session["admin"]:
180 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200181 # Names that look like UUIDs are not allowed
182 name = (indata if indata else kwargs).get("name")
183 if is_valid_uuid(name):
184 raise EngineException("Project names that look like UUIDs are not allowed",
185 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100186 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200187
tierno65ca36d2019-02-12 19:27:52 +0100188 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200189 if not session["admin"]:
190 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200191 # Names that look like UUIDs are not allowed
192 name = indata["name"] if indata else kwargs["name"]
193 if is_valid_uuid(name):
194 raise EngineException("Project names that look like UUIDs are not allowed",
195 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100196 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200197
198
tiernobdebce92019-07-01 15:36:49 +0000199class CommonVimWimSdn(BaseTopic):
200 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
tierno468aa242019-08-01 16:35:04 +0000201 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
tiernobdebce92019-07-01 15:36:49 +0000202 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200203
tiernobdebce92019-07-01 15:36:49 +0000204 @staticmethod
205 def _create_operation(op_type, params=None):
206 """
207 Creates a dictionary with the information to an operation, similar to ns-lcm-op
208 :param op_type: can be create, edit, delete
209 :param params: operation input parameters
210 :return: new dictionary with
211 """
212 now = time()
213 return {
214 "lcmOperationType": op_type,
215 "operationState": "PROCESSING",
216 "startTime": now,
217 "statusEnteredTime": now,
218 "detailed-status": "",
219 "operationParams": params,
220 }
tiernob24258a2018-10-04 18:39:49 +0200221
tierno65ca36d2019-02-12 19:27:52 +0100222 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000223 """
224 Check that the data to be inserted is valid. It is checked that name is unique
225 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
226 :param indata: data to be inserted
227 :return: None or raises EngineException
228 """
tiernob24258a2018-10-04 18:39:49 +0200229 self.check_unique_name(session, indata["name"], _id=None)
230
tierno65ca36d2019-02-12 19:27:52 +0100231 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000232 """
233 Check that the data to be edited/uploaded is valid. It is checked that name is unique
234 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
235 :param final_content: data once modified. This method may change it.
236 :param edit_content: incremental data that contains the modifications to apply
237 :param _id: internal _id
238 :return: None or raises EngineException
239 """
tierno65ca36d2019-02-12 19:27:52 +0100240 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200241 self.check_unique_name(session, edit_content["name"], _id=_id)
242
tiernobdebce92019-07-01 15:36:49 +0000243 def format_on_edit(self, final_content, edit_content):
244 """
245 Modifies final_content inserting admin information upon edition
246 :param final_content: final content to be stored at database
247 :param edit_content: user requested update content
248 :return: operation id
249 """
250
tierno92c1c7d2018-11-12 15:22:37 +0100251 # encrypt passwords
252 schema_version = final_content.get("schema_version")
253 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000254 if edit_content.get(self.password_to_encrypt):
255 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
256 schema_version=schema_version,
257 salt=final_content["_id"])
tierno468aa242019-08-01 16:35:04 +0000258 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
259 if edit_content.get("config") and config_to_encrypt_keys:
260
261 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100262 if edit_content["config"].get(p):
263 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
tiernobdebce92019-07-01 15:36:49 +0000264 schema_version=schema_version,
265 salt=final_content["_id"])
266
267 # create edit operation
268 final_content["_admin"]["operations"].append(self._create_operation("edit"))
269 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
tierno92c1c7d2018-11-12 15:22:37 +0100270
271 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000272 """
273 Modifies content descriptor to include _admin and insert create operation
274 :param content: descriptor to be modified
275 :param project_id: if included, it add project read/write permissions. Can be None or a list
276 :param make_public: if included it is generated as public for reading.
277 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
278 """
279 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000280 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100281
282 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000283 if content.get(self.password_to_encrypt):
284 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
285 schema_version=schema_version,
286 salt=content["_id"])
tierno468aa242019-08-01 16:35:04 +0000287 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
288 if content.get("config") and config_to_encrypt_keys:
289 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100290 if content["config"].get(p):
tiernobdebce92019-07-01 15:36:49 +0000291 content["config"][p] = self.db.encrypt(content["config"][p],
292 schema_version=schema_version,
tierno92c1c7d2018-11-12 15:22:37 +0100293 salt=content["_id"])
294
tiernob24258a2018-10-04 18:39:49 +0200295 content["_admin"]["operationalState"] = "PROCESSING"
296
tiernobdebce92019-07-01 15:36:49 +0000297 # create operation
298 content["_admin"]["operations"] = [self._create_operation("create")]
299 content["_admin"]["current_operation"] = None
300
301 return "{}:0".format(content["_id"])
302
tierno65ca36d2019-02-12 19:27:52 +0100303 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200304 """
305 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200307 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200308 :param dry_run: make checking but do not delete
tiernobdebce92019-07-01 15:36:49 +0000309 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200310 """
tiernobdebce92019-07-01 15:36:49 +0000311
312 filter_q = self._get_project_filter(session)
313 filter_q["_id"] = _id
314 db_content = self.db.get_one(self.topic, filter_q)
315
316 self.check_conflict_on_del(session, _id, db_content)
317 if dry_run:
318 return None
319
320 # remove reference from project_read. If not last delete
321 if session["project_id"]:
322 for project_id in session["project_id"]:
323 if project_id in db_content["_admin"]["projects_read"]:
324 db_content["_admin"]["projects_read"].remove(project_id)
325 if project_id in db_content["_admin"]["projects_write"]:
326 db_content["_admin"]["projects_write"].remove(project_id)
327 else:
328 db_content["_admin"]["projects_read"].clear()
329 db_content["_admin"]["projects_write"].clear()
330
331 update_dict = {"_admin.projects_read": db_content["_admin"]["projects_read"],
332 "_admin.projects_write": db_content["_admin"]["projects_write"]
333 }
334
335 # check if there are projects referencing it (apart from ANY that means public)....
336 if db_content["_admin"]["projects_read"] and (len(db_content["_admin"]["projects_read"]) > 1 or
337 db_content["_admin"]["projects_read"][0] != "ANY"):
338 self.db.set_one(self.topic, filter_q, update_dict=update_dict) # remove references but not delete
339 return None
340
341 # It must be deleted
342 if session["force"]:
343 self.db.del_one(self.topic, {"_id": _id})
344 op_id = None
345 self._send_msg("deleted", {"_id": _id, "op_id": op_id})
346 else:
347 update_dict["_admin.to_delete"] = True
348 self.db.set_one(self.topic, {"_id": _id},
349 update_dict=update_dict,
350 push={"_admin.operations": self._create_operation("delete")}
351 )
352 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
353 # so the -1 is not needed
354 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
355 self._send_msg("delete", {"_id": _id, "op_id": op_id})
356 return op_id
tiernob24258a2018-10-04 18:39:49 +0200357
358
tiernobdebce92019-07-01 15:36:49 +0000359class VimAccountTopic(CommonVimWimSdn):
360 topic = "vim_accounts"
361 topic_msg = "vim_account"
362 schema_new = vim_account_new_schema
363 schema_edit = vim_account_edit_schema
364 multiproject = True
365 password_to_encrypt = "vim_password"
tierno468aa242019-08-01 16:35:04 +0000366 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
367 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
tiernobdebce92019-07-01 15:36:49 +0000368
369
370class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000371 topic = "wim_accounts"
372 topic_msg = "wim_account"
373 schema_new = wim_account_new_schema
374 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100375 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000376 password_to_encrypt = "wim_password"
tierno468aa242019-08-01 16:35:04 +0000377 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000378
379
tiernobdebce92019-07-01 15:36:49 +0000380class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200381 topic = "sdns"
382 topic_msg = "sdn"
383 schema_new = sdn_new_schema
384 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100385 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000386 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000387 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100388
389
390class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100391 # topic = "users"
392 # topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100393 schema_new = user_new_schema
394 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100395
396 def __init__(self, db, fs, msg, auth):
397 UserTopic.__init__(self, db, fs, msg)
398 self.auth = auth
399
tierno65ca36d2019-02-12 19:27:52 +0100400 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100401 """
402 Check that the data to be inserted is valid
403
tierno65ca36d2019-02-12 19:27:52 +0100404 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100405 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100406 :return: None or raises EngineException
407 """
408 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000409 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200410 raise EngineException("username '{}' cannot have a uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000411 HTTPStatus.UNPROCESSABLE_ENTITY)
412
413 # Check that username is not used, regardless keystone already checks this
414 if self.auth.get_user_list(filter_q={"name": username}):
415 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100416
Eduardo Sousa339ed782019-05-28 14:25:00 +0100417 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000418 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200419 role = self.auth.get_role_list({"name": "project_admin"})
420 if not role:
421 role = self.auth.get_role_list()
422 if not role:
423 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
424 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000425 if not indata.get("project_role_mappings"):
426 indata["project_role_mappings"] = []
427 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200428 pid = self.auth.get_project(project)["_id"]
429 prm = {"project": pid, "role": rid}
430 if prm not in indata["project_role_mappings"]:
431 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000432 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
433 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100434
tierno65ca36d2019-02-12 19:27:52 +0100435 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100436 """
437 Check that the data to be edited/uploaded is valid
438
tierno65ca36d2019-02-12 19:27:52 +0100439 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100440 :param final_content: data once modified
441 :param edit_content: incremental data that contains the modifications to apply
442 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100443 :return: None or raises EngineException
444 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100445
tiernocf042d32019-06-13 09:06:40 +0000446 if "username" in edit_content:
447 username = edit_content.get("username")
448 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200449 raise EngineException("username '{}' cannot have an uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000450 HTTPStatus.UNPROCESSABLE_ENTITY)
451
452 # Check that username is not used, regardless keystone already checks this
453 if self.auth.get_user_list(filter_q={"name": username}):
454 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
455
456 if final_content["username"] == "admin":
457 for mapping in edit_content.get("remove_project_role_mappings", ()):
458 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
459 # TODO make this also available for project id and role id
460 raise EngineException("You cannot remove system_admin role from admin user",
461 http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100462
tiernob4844ab2019-05-23 08:42:12 +0000463 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100464 """
465 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100466 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100467 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000468 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100469 :return: None if ok or raises EngineException with the conflict
470 """
tiernocf042d32019-06-13 09:06:40 +0000471 if db_content["username"] == session["username"]:
472 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200473 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100474
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100475 @staticmethod
476 def format_on_show(content):
477 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100478 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100479 metadata from the role definition.
480 """
481 project_role_mappings = []
482
delacruzramo01b15d32019-07-02 14:37:47 +0200483 if "projects" in content:
484 for project in content["projects"]:
485 for role in project["roles"]:
486 project_role_mappings.append({"project": project["_id"],
487 "project_name": project["name"],
488 "role": role["_id"],
489 "role_name": role["name"]})
490 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100491 content["project_role_mappings"] = project_role_mappings
492
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100493 return content
494
tierno65ca36d2019-02-12 19:27:52 +0100495 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100496 """
497 Creates a new entry into the authentication backend.
498
499 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
500
501 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100502 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100503 :param indata: data to be inserted
504 :param kwargs: used to override the indata descriptor
505 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200506 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100507 """
508 try:
509 content = BaseTopic._remove_envelop(indata)
510
511 # Override descriptor with query string kwargs
512 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100513 content = self._validate_input_new(content, session["force"])
514 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000515 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200516 now = time()
517 content["_admin"] = {"created": now, "modified": now}
518 prms = []
519 for prm in content.get("project_role_mappings", []):
520 proj = self.auth.get_project(prm["project"], not session["force"])
521 role = self.auth.get_role(prm["role"], not session["force"])
522 pid = proj["_id"] if proj else None
523 rid = role["_id"] if role else None
524 prl = {"project": pid, "role": rid}
525 if prl not in prms:
526 prms.append(prl)
527 content["project_role_mappings"] = prms
528 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
529 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100530
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100531 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000532 # del content["password"]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100533 # self._send_msg("create", content)
delacruzramo01b15d32019-07-02 14:37:47 +0200534 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100535 except ValidationError as e:
536 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
537
538 def show(self, session, _id):
539 """
540 Get complete information on an topic
541
tierno65ca36d2019-02-12 19:27:52 +0100542 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100543 :param _id: server internal id
544 :return: dictionary, raise exception if not found.
545 """
tiernocf042d32019-06-13 09:06:40 +0000546 # Allow _id to be a name or uuid
547 filter_q = {self.id_field(self.topic, _id): _id}
548 users = self.auth.get_user_list(filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100549
550 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000551 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100552 elif len(users) > 1:
553 raise EngineException("Too many users found", HTTPStatus.CONFLICT)
554 else:
555 raise EngineException("User not found", HTTPStatus.NOT_FOUND)
556
tierno65ca36d2019-02-12 19:27:52 +0100557 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100558 """
559 Updates an user entry.
560
tierno65ca36d2019-02-12 19:27:52 +0100561 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100562 :param _id:
563 :param indata: data to be inserted
564 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100565 :param content:
566 :return: _id: identity of the inserted data.
567 """
568 indata = self._remove_envelop(indata)
569
570 # Override descriptor with query string kwargs
571 if kwargs:
572 BaseTopic._update_input_with_kwargs(indata, kwargs)
573 try:
tierno65ca36d2019-02-12 19:27:52 +0100574 indata = self._validate_input_edit(indata, force=session["force"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100575
576 if not content:
577 content = self.show(session, _id)
tierno65ca36d2019-02-12 19:27:52 +0100578 self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000579 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100580
delacruzramo01b15d32019-07-02 14:37:47 +0200581 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
582 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
583 indata.get("projects") or indata.get("add_projects")):
tiernocf042d32019-06-13 09:06:40 +0000584 return _id
delacruzramo01b15d32019-07-02 14:37:47 +0200585 if indata.get("project_role_mappings") \
586 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
tiernocf042d32019-06-13 09:06:40 +0000587 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
588 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
Eduardo Sousa44603902019-06-04 08:10:32 +0100589
delacruzramo01b15d32019-07-02 14:37:47 +0200590 if indata.get("projects") or indata.get("add_projects"):
591 role = self.auth.get_role_list({"name": "project_admin"})
592 if not role:
593 role = self.auth.get_role_list()
594 if not role:
595 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
596 .format(content["username"]))
597 rid = role[0]["_id"]
598 if "add_project_role_mappings" not in indata:
599 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +0000600 if "remove_project_role_mappings" not in indata:
601 indata["remove_project_role_mappings"] = []
602 if isinstance(indata.get("projects"), dict):
603 # backward compatible
604 for k, v in indata["projects"].items():
605 if k.startswith("$") and v is None:
606 indata["remove_project_role_mappings"].append({"project": k[1:]})
607 elif k.startswith("$+"):
608 indata["add_project_role_mappings"].append({"project": v, "role": rid})
609 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +0200610 for proj in indata.get("projects", []) + indata.get("add_projects", []):
611 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
612
613 # user = self.show(session, _id) # Already in 'content'
614 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100615
tiernocf042d32019-06-13 09:06:40 +0000616 mappings_to_add = []
617 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +0100618
tiernocf042d32019-06-13 09:06:40 +0000619 # remove
620 for to_remove in indata.get("remove_project_role_mappings", ()):
621 for mapping in original_mapping:
622 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
623 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
624 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +0100625
tiernocf042d32019-06-13 09:06:40 +0000626 # add
627 for to_add in indata.get("add_project_role_mappings", ()):
628 for mapping in original_mapping:
629 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
630 to_add["role"] in (mapping["role"], mapping["role_name"]):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100631
tiernocf042d32019-06-13 09:06:40 +0000632 if mapping in mappings_to_remove: # do not remove
633 mappings_to_remove.remove(mapping)
634 break # do not add, it is already at user
635 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200636 pid = self.auth.get_project(to_add["project"])["_id"]
637 rid = self.auth.get_role(to_add["role"])["_id"]
638 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000639
640 # set
641 if indata.get("project_role_mappings"):
642 for to_set in indata["project_role_mappings"]:
643 for mapping in original_mapping:
644 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
645 to_set["role"] in (mapping["role"], mapping["role_name"]):
tiernocf042d32019-06-13 09:06:40 +0000646 if mapping in mappings_to_remove: # do not remove
647 mappings_to_remove.remove(mapping)
648 break # do not add, it is already at user
649 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200650 pid = self.auth.get_project(to_set["project"])["_id"]
651 rid = self.auth.get_role(to_set["role"])["_id"]
652 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000653 for mapping in original_mapping:
654 for to_set in indata["project_role_mappings"]:
655 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
656 to_set["role"] in (mapping["role"], mapping["role_name"]):
657 break
658 else:
659 # delete
660 if mapping not in mappings_to_remove: # do not remove
661 mappings_to_remove.append(mapping)
662
delacruzramo01b15d32019-07-02 14:37:47 +0200663 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
664 "add_project_role_mappings": mappings_to_add,
665 "remove_project_role_mappings": mappings_to_remove
666 })
tiernocf042d32019-06-13 09:06:40 +0000667
delacruzramo01b15d32019-07-02 14:37:47 +0200668 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100669 except ValidationError as e:
670 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
671
672 def list(self, session, filter_q=None):
673 """
674 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100675 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100676 :param filter_q: filter of data to be applied
677 :return: The list, it can be empty if no one match the filter.
678 """
tierno1546f2a2019-08-20 15:38:11 +0000679 users = self.auth.get_user_list(filter_q)
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100680
681 return users
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100682
tierno65ca36d2019-02-12 19:27:52 +0100683 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100684 """
685 Delete item by its internal _id
686
tierno65ca36d2019-02-12 19:27:52 +0100687 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100688 :param _id: server internal id
689 :param force: indicates if deletion must be forced in case of conflict
690 :param dry_run: make checking but do not delete
691 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
692 """
tiernocf042d32019-06-13 09:06:40 +0000693 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200694 user = self.auth.get_user(_id)
695 uid = user["_id"]
696 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100697 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200698 v = self.auth.delete_user(uid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100699 return v
700 return None
701
702
703class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100704 # topic = "projects"
705 # topic_msg = "projects"
Eduardo Sousa44603902019-06-04 08:10:32 +0100706 schema_new = project_new_schema
707 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100708
709 def __init__(self, db, fs, msg, auth):
710 ProjectTopic.__init__(self, db, fs, msg)
711 self.auth = auth
712
tierno65ca36d2019-02-12 19:27:52 +0100713 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100714 """
715 Check that the data to be inserted is valid
716
tierno65ca36d2019-02-12 19:27:52 +0100717 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100718 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100719 :return: None or raises EngineException
720 """
tiernocf042d32019-06-13 09:06:40 +0000721 project_name = indata.get("name")
722 if is_valid_uuid(project_name):
delacruzramoceb8baf2019-06-21 14:25:38 +0200723 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000724 HTTPStatus.UNPROCESSABLE_ENTITY)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100725
tiernocf042d32019-06-13 09:06:40 +0000726 project_list = self.auth.get_project_list(filter_q={"name": project_name})
727
728 if project_list:
729 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
730
731 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
732 """
733 Check that the data to be edited/uploaded is valid
734
735 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
736 :param final_content: data once modified
737 :param edit_content: incremental data that contains the modifications to apply
738 :param _id: internal _id
739 :return: None or raises EngineException
740 """
741
742 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +0200743 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +0000744 if is_valid_uuid(project_name):
delacruzramo01b15d32019-07-02 14:37:47 +0200745 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000746 HTTPStatus.UNPROCESSABLE_ENTITY)
747
delacruzramo01b15d32019-07-02 14:37:47 +0200748 if final_content["name"] == "admin":
749 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
750
tiernocf042d32019-06-13 09:06:40 +0000751 # Check that project name is not used, regardless keystone already checks this
752 if self.auth.get_project_list(filter_q={"name": project_name}):
753 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100754
tiernob4844ab2019-05-23 08:42:12 +0000755 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100756 """
757 Check if deletion can be done because of dependencies if it is not force. To override
758
tierno65ca36d2019-02-12 19:27:52 +0100759 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100760 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000761 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100762 :return: None if ok or raises EngineException with the conflict
763 """
delacruzramo01b15d32019-07-02 14:37:47 +0200764
765 def check_rw_projects(topic, title, id_field):
766 for desc in self.db.get_list(topic):
767 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
768 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
769 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
770
771 if _id in session["project_id"]:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100772 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
773
delacruzramo01b15d32019-07-02 14:37:47 +0200774 if db_content["name"] == "admin":
775 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
776
777 # If any user is using this project, raise CONFLICT exception
778 if not session["force"]:
779 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +0000780 for prm in user.get("project_role_mappings"):
781 if prm["project"] == _id:
782 raise EngineException("Project '{}' ({}) is being used by user '{}'"
783 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200784
785 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
786 if not session["force"]:
787 check_rw_projects("vnfds", "VNF Descriptor", "id")
788 check_rw_projects("nsds", "NS Descriptor", "id")
789 check_rw_projects("nsts", "NS Template", "id")
790 check_rw_projects("pdus", "PDU Descriptor", "name")
791
tierno65ca36d2019-02-12 19:27:52 +0100792 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100793 """
794 Creates a new entry into the authentication backend.
795
796 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
797
798 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100799 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100800 :param indata: data to be inserted
801 :param kwargs: used to override the indata descriptor
802 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200803 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100804 """
805 try:
806 content = BaseTopic._remove_envelop(indata)
807
808 # Override descriptor with query string kwargs
809 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100810 content = self._validate_input_new(content, session["force"])
811 self.check_conflict_on_new(session, content)
812 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200813 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100814 rollback.append({"topic": self.topic, "_id": _id})
815 # self._send_msg("create", content)
delacruzramo01b15d32019-07-02 14:37:47 +0200816 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100817 except ValidationError as e:
818 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
819
820 def show(self, session, _id):
821 """
822 Get complete information on an topic
823
tierno65ca36d2019-02-12 19:27:52 +0100824 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100825 :param _id: server internal id
826 :return: dictionary, raise exception if not found.
827 """
tiernocf042d32019-06-13 09:06:40 +0000828 # Allow _id to be a name or uuid
829 filter_q = {self.id_field(self.topic, _id): _id}
830 projects = self.auth.get_project_list(filter_q=filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100831
832 if len(projects) == 1:
833 return projects[0]
834 elif len(projects) > 1:
835 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
836 else:
837 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
838
839 def list(self, session, filter_q=None):
840 """
841 Get a list of the topic that matches a filter
842
tierno65ca36d2019-02-12 19:27:52 +0100843 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100844 :param filter_q: filter of data to be applied
845 :return: The list, it can be empty if no one match the filter.
846 """
Eduardo Sousafa54cd92019-05-20 15:58:41 +0100847 return self.auth.get_project_list(filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100848
tierno65ca36d2019-02-12 19:27:52 +0100849 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100850 """
851 Delete item by its internal _id
852
tierno65ca36d2019-02-12 19:27:52 +0100853 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100854 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100855 :param dry_run: make checking but do not delete
856 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
857 """
tiernocf042d32019-06-13 09:06:40 +0000858 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200859 proj = self.auth.get_project(_id)
860 pid = proj["_id"]
861 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100862 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200863 v = self.auth.delete_project(pid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100864 return v
865 return None
866
tierno4015b472019-06-10 13:57:29 +0000867 def edit(self, session, _id, indata=None, kwargs=None, content=None):
868 """
869 Updates a project entry.
870
871 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
872 :param _id:
873 :param indata: data to be inserted
874 :param kwargs: used to override the indata descriptor
875 :param content:
876 :return: _id: identity of the inserted data.
877 """
878 indata = self._remove_envelop(indata)
879
880 # Override descriptor with query string kwargs
881 if kwargs:
882 BaseTopic._update_input_with_kwargs(indata, kwargs)
883 try:
884 indata = self._validate_input_edit(indata, force=session["force"])
885
886 if not content:
887 content = self.show(session, _id)
888 self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +0200889 self.format_on_edit(content, indata)
tierno4015b472019-06-10 13:57:29 +0000890
891 if "name" in indata:
delacruzramo01b15d32019-07-02 14:37:47 +0200892 content["name"] = indata["name"]
893 self.auth.update_project(content["_id"], content)
tierno4015b472019-06-10 13:57:29 +0000894 except ValidationError as e:
895 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
896
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100897
898class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +0200899 topic = "roles"
900 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100901 schema_new = roles_new_schema
902 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100903 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100904
905 def __init__(self, db, fs, msg, auth, ops):
906 BaseTopic.__init__(self, db, fs, msg)
907 self.auth = auth
908 self.operations = ops
delacruzramo01b15d32019-07-02 14:37:47 +0200909 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100910
911 @staticmethod
912 def validate_role_definition(operations, role_definitions):
913 """
914 Validates the role definition against the operations defined in
915 the resources to operations files.
916
917 :param operations: operations list
918 :param role_definitions: role definition to test
919 :return: None if ok, raises ValidationError exception on error
920 """
tierno1f029d82019-06-13 22:37:04 +0000921 if not role_definitions.get("permissions"):
922 return
923 ignore_fields = ["admin", "default"]
924 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +0100925 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100926 continue
Eduardo Sousac7689372019-06-04 16:01:46 +0100927 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +0000928 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +0100929
delacruzramoc061f562019-04-05 11:00:02 +0200930 role_def_matches = [op for op in operations if op.startswith(role_def)]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100931
932 if len(role_def_matches) == 0:
tierno1f029d82019-06-13 22:37:04 +0000933 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +0100934
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100935 def _validate_input_new(self, input, force=False):
936 """
937 Validates input user content for a new entry.
938
939 :param input: user input content for the new topic
940 :param force: may be used for being more tolerant
941 :return: The same input content, or a changed version of it.
942 """
943 if self.schema_new:
944 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +0100945 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +0100946
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100947 return input
948
949 def _validate_input_edit(self, input, force=False):
950 """
951 Validates input user content for updating an entry.
952
953 :param input: user input content for the new topic
954 :param force: may be used for being more tolerant
955 :return: The same input content, or a changed version of it.
956 """
957 if self.schema_edit:
958 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +0100959 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +0100960
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100961 return input
962
tierno65ca36d2019-02-12 19:27:52 +0100963 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100964 """
965 Check that the data to be inserted is valid
966
tierno65ca36d2019-02-12 19:27:52 +0100967 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100968 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100969 :return: None or raises EngineException
970 """
tierno1f029d82019-06-13 22:37:04 +0000971 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +0200972 name = indata["name"]
973 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
974 if self.auth.get_role_list({"name": name}):
975 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100976
tierno65ca36d2019-02-12 19:27:52 +0100977 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100978 """
979 Check that the data to be edited/uploaded is valid
980
tierno65ca36d2019-02-12 19:27:52 +0100981 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100982 :param final_content: data once modified
983 :param edit_content: incremental data that contains the modifications to apply
984 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100985 :return: None or raises EngineException
986 """
tierno1f029d82019-06-13 22:37:04 +0000987 if "default" not in final_content["permissions"]:
988 final_content["permissions"]["default"] = False
989 if "admin" not in final_content["permissions"]:
990 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100991
tierno1f029d82019-06-13 22:37:04 +0000992 # check name not exists
993 if "name" in edit_content:
994 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +0200995 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
996 roles = self.auth.get_role_list({"name": role_name})
997 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
tierno1f029d82019-06-13 22:37:04 +0000998 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100999
tiernob4844ab2019-05-23 08:42:12 +00001000 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001001 """
1002 Check if deletion can be done because of dependencies if it is not force. To override
1003
tierno65ca36d2019-02-12 19:27:52 +01001004 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001005 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001006 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001007 :return: None if ok or raises EngineException with the conflict
1008 """
delacruzramo01b15d32019-07-02 14:37:47 +02001009 role = self.auth.get_role(_id)
1010 if role["name"] in ["system_admin", "project_admin"]:
1011 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001012
delacruzramo01b15d32019-07-02 14:37:47 +02001013 # If any user is using this role, raise CONFLICT exception
1014 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001015 for prm in user.get("project_role_mappings"):
1016 if prm["role"] == _id:
1017 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1018 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001019
1020 @staticmethod
delacruzramo01b15d32019-07-02 14:37:47 +02001021 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001022 """
1023 Modifies content descriptor to include _admin
1024
1025 :param content: descriptor to be modified
1026 :param project_id: if included, it add project read/write permissions
1027 :param make_public: if included it is generated as public for reading.
1028 :return: None, but content is modified
1029 """
1030 now = time()
1031 if "_admin" not in content:
1032 content["_admin"] = {}
1033 if not content["_admin"].get("created"):
1034 content["_admin"]["created"] = now
1035 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001036
tierno1f029d82019-06-13 22:37:04 +00001037 if "permissions" not in content:
1038 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001039
tierno1f029d82019-06-13 22:37:04 +00001040 if "default" not in content["permissions"]:
1041 content["permissions"]["default"] = False
1042 if "admin" not in content["permissions"]:
1043 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001044
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001045 @staticmethod
1046 def format_on_edit(final_content, edit_content):
1047 """
1048 Modifies final_content descriptor to include the modified date.
1049
1050 :param final_content: final descriptor generated
1051 :param edit_content: alterations to be include
1052 :return: None, but final_content is modified
1053 """
delacruzramo01b15d32019-07-02 14:37:47 +02001054 if "_admin" in final_content:
1055 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001056
tierno1f029d82019-06-13 22:37:04 +00001057 if "permissions" not in final_content:
1058 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001059
tierno1f029d82019-06-13 22:37:04 +00001060 if "default" not in final_content["permissions"]:
1061 final_content["permissions"]["default"] = False
1062 if "admin" not in final_content["permissions"]:
1063 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001064 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001065
delacruzramo01b15d32019-07-02 14:37:47 +02001066 def show(self, session, _id):
1067 """
1068 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001069
delacruzramo01b15d32019-07-02 14:37:47 +02001070 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1071 :param _id: server internal id
1072 :return: dictionary, raise exception if not found.
1073 """
1074 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1075 roles = self.auth.get_role_list(filter_q)
1076 if not roles:
1077 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1078 elif len(roles) > 1:
1079 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1080 return roles[0]
1081
1082 def list(self, session, filter_q=None):
1083 """
1084 Get a list of the topic that matches a filter
1085
1086 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1087 :param filter_q: filter of data to be applied
1088 :return: The list, it can be empty if no one match the filter.
1089 """
1090 return self.auth.get_role_list(filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001091
tierno65ca36d2019-02-12 19:27:52 +01001092 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001093 """
1094 Creates a new entry into database.
1095
1096 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001097 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001098 :param indata: data to be inserted
1099 :param kwargs: used to override the indata descriptor
1100 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001101 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001102 """
1103 try:
tierno1f029d82019-06-13 22:37:04 +00001104 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001105
1106 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001107 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001108 content = self._validate_input_new(content, session["force"])
1109 self.check_conflict_on_new(session, content)
1110 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001111 # role_name = content["name"]
1112 rid = self.auth.create_role(content)
1113 content["_id"] = rid
1114 # _id = self.db.create(self.topic, content)
1115 rollback.append({"topic": self.topic, "_id": rid})
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001116 # self._send_msg("create", content)
delacruzramo01b15d32019-07-02 14:37:47 +02001117 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001118 except ValidationError as e:
1119 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1120
tierno65ca36d2019-02-12 19:27:52 +01001121 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001122 """
1123 Delete item by its internal _id
1124
tierno65ca36d2019-02-12 19:27:52 +01001125 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001126 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001127 :param dry_run: make checking but do not delete
1128 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1129 """
delacruzramo01b15d32019-07-02 14:37:47 +02001130 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1131 roles = self.auth.get_role_list(filter_q)
1132 if not roles:
1133 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1134 elif len(roles) > 1:
1135 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1136 rid = roles[0]["_id"]
1137 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001138 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001139 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001140 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001141 v = self.auth.delete_role(rid)
1142 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001143 return v
1144 return None
1145
tierno65ca36d2019-02-12 19:27:52 +01001146 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001147 """
1148 Updates a role entry.
1149
tierno65ca36d2019-02-12 19:27:52 +01001150 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001151 :param _id:
1152 :param indata: data to be inserted
1153 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001154 :param content:
1155 :return: _id: identity of the inserted data.
1156 """
delacruzramo01b15d32019-07-02 14:37:47 +02001157 if kwargs:
1158 self._update_input_with_kwargs(indata, kwargs)
1159 try:
1160 indata = self._validate_input_edit(indata, force=session["force"])
1161 if not content:
1162 content = self.show(session, _id)
1163 deep_update_rfc7396(content, indata)
1164 self.check_conflict_on_edit(session, content, indata, _id=_id)
1165 self.format_on_edit(content, indata)
1166 self.auth.update_role(content)
1167 except ValidationError as e:
1168 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)