blob: 24c99a9f4e86e5b141daa3f240ee8a270125b099 [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, \
delacruzramofe598fe2019-10-23 18:25:11 +020024 k8scluster_new_schema, k8scluster_edit_schema, k8srepo_new_schema, k8srepo_edit_schema, \
David Garciaecb41322021-03-31 19:10:46 +020025 vca_new_schema, vca_edit_schema, \
Felipe Vicensb66b0412020-05-06 10:11:00 +020026 osmrepo_new_schema, osmrepo_edit_schema, \
27 validate_input, ValidationError, is_valid_uuid # To check that User/Project Names don't look like UUIDs
tierno23acf402019-08-28 13:36:34 +000028from osm_nbi.base_topic import BaseTopic, EngineException
29from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020030from osm_common.dbbase import deep_update_rfc7396
agarwalat53471982020-10-08 13:06:14 +000031import copy
tiernob24258a2018-10-04 18:39:49 +020032
33__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
34
35
36class UserTopic(BaseTopic):
37 topic = "users"
38 topic_msg = "users"
39 schema_new = user_new_schema
40 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010041 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020042
delacruzramo32bab472019-09-13 12:24:22 +020043 def __init__(self, db, fs, msg, auth):
44 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020045
46 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010047 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020048 """
49 Generates a filter dictionary for querying database users.
50 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010051 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020052 :return:
53 """
54 if session["admin"]: # allows all
55 return {}
56 else:
57 return {"username": session["username"]}
58
tierno65ca36d2019-02-12 19:27:52 +010059 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020060 # check username not exists
61 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
62 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
63 # check projects
tierno65ca36d2019-02-12 19:27:52 +010064 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020065 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020066 # To allow project addressing by Name as well as ID
67 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
68 fail_on_more=False):
69 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
tiernob24258a2018-10-04 18:39:49 +020070
tiernob4844ab2019-05-23 08:42:12 +000071 def check_conflict_on_del(self, session, _id, db_content):
72 """
73 Check if deletion can be done because of dependencies if it is not force. To override
74 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
75 :param _id: internal _id
76 :param db_content: The database content of this item _id
77 :return: None if ok or raises EngineException with the conflict
78 """
tiernob24258a2018-10-04 18:39:49 +020079 if _id == session["username"]:
80 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
81
82 @staticmethod
83 def format_on_new(content, project_id=None, make_public=False):
84 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +020085 # Removed so that the UUID is kept, to allow User Name modification
86 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +020087 salt = uuid4().hex
88 content["_admin"]["salt"] = salt
89 if content.get("password"):
90 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +010091 if content.get("project_role_mappings"):
delacruzramo01b15d32019-07-02 14:37:47 +020092 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
Eduardo Sousa339ed782019-05-28 14:25:00 +010093
94 if content.get("projects"):
95 content["projects"] += projects
96 else:
97 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +020098
99 @staticmethod
100 def format_on_edit(final_content, edit_content):
101 BaseTopic.format_on_edit(final_content, edit_content)
102 if edit_content.get("password"):
103 salt = uuid4().hex
104 final_content["_admin"]["salt"] = salt
105 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
106 salt.encode('utf-8')).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000107 return None
tiernob24258a2018-10-04 18:39:49 +0200108
tierno65ca36d2019-02-12 19:27:52 +0100109 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200110 if not session["admin"]:
111 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200112 # Names that look like UUIDs are not allowed
113 name = (indata if indata else kwargs).get("username")
114 if is_valid_uuid(name):
115 raise EngineException("Usernames that look like UUIDs are not allowed",
116 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100117 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200118
tierno65ca36d2019-02-12 19:27:52 +0100119 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200120 if not session["admin"]:
121 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200122 # Names that look like UUIDs are not allowed
123 name = indata["username"] if indata else kwargs["username"]
124 if is_valid_uuid(name):
125 raise EngineException("Usernames that look like UUIDs are not allowed",
126 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100127 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200128
129
130class ProjectTopic(BaseTopic):
131 topic = "projects"
132 topic_msg = "projects"
133 schema_new = project_new_schema
134 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100135 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200136
delacruzramo32bab472019-09-13 12:24:22 +0200137 def __init__(self, db, fs, msg, auth):
138 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200139
tierno65ca36d2019-02-12 19:27:52 +0100140 @staticmethod
141 def _get_project_filter(session):
142 """
143 Generates a filter dictionary for querying database users.
144 Current policy is admin can show all, non admin, only its own user.
145 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
146 :return:
147 """
148 if session["admin"]: # allows all
149 return {}
150 else:
151 return {"_id.cont": session["project_id"]}
152
153 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200154 if not indata.get("name"):
155 raise EngineException("missing 'name'")
156 # check name not exists
157 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
158 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
159
160 @staticmethod
161 def format_on_new(content, project_id=None, make_public=False):
162 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200163 # Removed so that the UUID is kept, to allow Project Name modification
164 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200165
tiernob4844ab2019-05-23 08:42:12 +0000166 def check_conflict_on_del(self, session, _id, db_content):
167 """
168 Check if deletion can be done because of dependencies if it is not force. To override
169 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
170 :param _id: internal _id
171 :param db_content: The database content of this item _id
172 :return: None if ok or raises EngineException with the conflict
173 """
tierno65ca36d2019-02-12 19:27:52 +0100174 if _id in session["project_id"]:
tiernob24258a2018-10-04 18:39:49 +0200175 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
tierno65ca36d2019-02-12 19:27:52 +0100176 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200177 return
178 _filter = {"projects": _id}
179 if self.db.get_list("users", _filter):
180 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
181
tierno65ca36d2019-02-12 19:27:52 +0100182 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200183 if not session["admin"]:
184 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200185 # Names that look like UUIDs are not allowed
186 name = (indata if indata else kwargs).get("name")
187 if is_valid_uuid(name):
188 raise EngineException("Project names that look like UUIDs are not allowed",
189 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100190 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200191
tierno65ca36d2019-02-12 19:27:52 +0100192 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200193 if not session["admin"]:
194 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200195 # Names that look like UUIDs are not allowed
196 name = indata["name"] if indata else kwargs["name"]
197 if is_valid_uuid(name):
198 raise EngineException("Project names that look like UUIDs are not allowed",
199 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100200 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200201
202
tiernobdebce92019-07-01 15:36:49 +0000203class CommonVimWimSdn(BaseTopic):
204 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
tierno468aa242019-08-01 16:35:04 +0000205 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
tiernobdebce92019-07-01 15:36:49 +0000206 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200207
tiernobdebce92019-07-01 15:36:49 +0000208 @staticmethod
209 def _create_operation(op_type, params=None):
210 """
211 Creates a dictionary with the information to an operation, similar to ns-lcm-op
212 :param op_type: can be create, edit, delete
213 :param params: operation input parameters
214 :return: new dictionary with
215 """
216 now = time()
217 return {
218 "lcmOperationType": op_type,
219 "operationState": "PROCESSING",
220 "startTime": now,
221 "statusEnteredTime": now,
222 "detailed-status": "",
223 "operationParams": params,
224 }
tiernob24258a2018-10-04 18:39:49 +0200225
tierno65ca36d2019-02-12 19:27:52 +0100226 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000227 """
228 Check that the data to be inserted is valid. It is checked that name is unique
229 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
230 :param indata: data to be inserted
231 :return: None or raises EngineException
232 """
tiernob24258a2018-10-04 18:39:49 +0200233 self.check_unique_name(session, indata["name"], _id=None)
234
tierno65ca36d2019-02-12 19:27:52 +0100235 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000236 """
237 Check that the data to be edited/uploaded is valid. It is checked that name is unique
238 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
239 :param final_content: data once modified. This method may change it.
240 :param edit_content: incremental data that contains the modifications to apply
241 :param _id: internal _id
242 :return: None or raises EngineException
243 """
tierno65ca36d2019-02-12 19:27:52 +0100244 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200245 self.check_unique_name(session, edit_content["name"], _id=_id)
246
bravofb995ea22021-02-10 10:57:52 -0300247 return final_content
248
tiernobdebce92019-07-01 15:36:49 +0000249 def format_on_edit(self, final_content, edit_content):
250 """
251 Modifies final_content inserting admin information upon edition
252 :param final_content: final content to be stored at database
253 :param edit_content: user requested update content
254 :return: operation id
255 """
delacruzramofe598fe2019-10-23 18:25:11 +0200256 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000257
tierno92c1c7d2018-11-12 15:22:37 +0100258 # encrypt passwords
259 schema_version = final_content.get("schema_version")
260 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000261 if edit_content.get(self.password_to_encrypt):
262 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
263 schema_version=schema_version,
264 salt=final_content["_id"])
tierno468aa242019-08-01 16:35:04 +0000265 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
266 if edit_content.get("config") and config_to_encrypt_keys:
267
268 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100269 if edit_content["config"].get(p):
270 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
tiernobdebce92019-07-01 15:36:49 +0000271 schema_version=schema_version,
272 salt=final_content["_id"])
273
274 # create edit operation
275 final_content["_admin"]["operations"].append(self._create_operation("edit"))
276 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
tierno92c1c7d2018-11-12 15:22:37 +0100277
278 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000279 """
280 Modifies content descriptor to include _admin and insert create operation
281 :param content: descriptor to be modified
282 :param project_id: if included, it add project read/write permissions. Can be None or a list
283 :param make_public: if included it is generated as public for reading.
284 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
285 """
286 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000287 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100288
289 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000290 if content.get(self.password_to_encrypt):
291 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
292 schema_version=schema_version,
293 salt=content["_id"])
tierno468aa242019-08-01 16:35:04 +0000294 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
295 if content.get("config") and config_to_encrypt_keys:
296 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100297 if content["config"].get(p):
tiernobdebce92019-07-01 15:36:49 +0000298 content["config"][p] = self.db.encrypt(content["config"][p],
299 schema_version=schema_version,
tierno92c1c7d2018-11-12 15:22:37 +0100300 salt=content["_id"])
301
tiernob24258a2018-10-04 18:39:49 +0200302 content["_admin"]["operationalState"] = "PROCESSING"
303
tiernobdebce92019-07-01 15:36:49 +0000304 # create operation
305 content["_admin"]["operations"] = [self._create_operation("create")]
306 content["_admin"]["current_operation"] = None
307
308 return "{}:0".format(content["_id"])
309
tiernobee3bad2019-12-05 12:26:01 +0000310 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200311 """
312 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100313 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200314 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200315 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000316 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000317 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200318 """
tiernobdebce92019-07-01 15:36:49 +0000319
320 filter_q = self._get_project_filter(session)
321 filter_q["_id"] = _id
322 db_content = self.db.get_one(self.topic, filter_q)
323
324 self.check_conflict_on_del(session, _id, db_content)
325 if dry_run:
326 return None
327
tiernof5f2e3f2020-03-23 14:42:10 +0000328 # remove reference from project_read if there are more projects referencing it. If it last one,
329 # do not remove reference, but order via kafka to delete it
330 if session["project_id"] and session["project_id"]:
331 other_projects_referencing = next((p for p in db_content["_admin"]["projects_read"]
tierno20e74d22020-06-22 12:17:22 +0000332 if p not in session["project_id"] and p != "ANY"), None)
tiernobdebce92019-07-01 15:36:49 +0000333
tiernof5f2e3f2020-03-23 14:42:10 +0000334 # check if there are projects referencing it (apart from ANY, that means, public)....
335 if other_projects_referencing:
336 # remove references but not delete
tierno20e74d22020-06-22 12:17:22 +0000337 update_dict_pull = {"_admin.projects_read": session["project_id"],
338 "_admin.projects_write": session["project_id"]}
339 self.db.set_one(self.topic, filter_q, update_dict=None, pull_list=update_dict_pull)
tiernof5f2e3f2020-03-23 14:42:10 +0000340 return None
341 else:
342 can_write = next((p for p in db_content["_admin"]["projects_write"] if p == "ANY" or
343 p in session["project_id"]), None)
344 if not can_write:
345 raise EngineException("You have not write permission to delete it",
346 http_code=HTTPStatus.UNAUTHORIZED)
tiernobdebce92019-07-01 15:36:49 +0000347
348 # It must be deleted
349 if session["force"]:
350 self.db.del_one(self.topic, {"_id": _id})
351 op_id = None
tiernobee3bad2019-12-05 12:26:01 +0000352 self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000353 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000354 update_dict = {"_admin.to_delete": True}
tiernobdebce92019-07-01 15:36:49 +0000355 self.db.set_one(self.topic, {"_id": _id},
356 update_dict=update_dict,
357 push={"_admin.operations": self._create_operation("delete")}
358 )
359 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
360 # so the -1 is not needed
361 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
tiernobee3bad2019-12-05 12:26:01 +0000362 self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000363 return op_id
tiernob24258a2018-10-04 18:39:49 +0200364
365
tiernobdebce92019-07-01 15:36:49 +0000366class VimAccountTopic(CommonVimWimSdn):
367 topic = "vim_accounts"
368 topic_msg = "vim_account"
369 schema_new = vim_account_new_schema
370 schema_edit = vim_account_edit_schema
371 multiproject = True
372 password_to_encrypt = "vim_password"
tierno468aa242019-08-01 16:35:04 +0000373 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
374 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
tiernobdebce92019-07-01 15:36:49 +0000375
delacruzramo35c998b2019-11-21 11:09:16 +0100376 def check_conflict_on_del(self, session, _id, db_content):
377 """
378 Check if deletion can be done because of dependencies if it is not force. To override
379 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
380 :param _id: internal _id
381 :param db_content: The database content of this item _id
382 :return: None if ok or raises EngineException with the conflict
383 """
384 if session["force"]:
385 return
386 # check if used by VNF
387 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
388 raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
389 super().check_conflict_on_del(session, _id, db_content)
390
tiernobdebce92019-07-01 15:36:49 +0000391
392class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000393 topic = "wim_accounts"
394 topic_msg = "wim_account"
395 schema_new = wim_account_new_schema
396 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100397 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000398 password_to_encrypt = "wim_password"
tierno468aa242019-08-01 16:35:04 +0000399 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000400
401
tiernobdebce92019-07-01 15:36:49 +0000402class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200403 topic = "sdns"
404 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000405 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200406 schema_new = sdn_new_schema
407 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100408 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000409 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000410 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100411
tierno7adaeb02019-12-17 16:46:12 +0000412 def _obtain_url(self, input, create):
413 if input.get("ip") or input.get("port"):
414 if not input.get("ip") or not input.get("port") or input.get('url'):
415 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
416 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
417 del input["ip"]
418 del input["port"]
419 elif create and not input.get('url'):
420 raise ValidationError("You must provide 'url'")
421 return input
422
423 def _validate_input_new(self, input, force=False):
424 input = super()._validate_input_new(input, force)
425 return self._obtain_url(input, True)
426
Frank Brydendeba68e2020-07-27 13:55:11 +0000427 def _validate_input_edit(self, input, content, force=False):
428 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000429 return self._obtain_url(input, False)
430
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100431
delacruzramofe598fe2019-10-23 18:25:11 +0200432class K8sClusterTopic(CommonVimWimSdn):
433 topic = "k8sclusters"
434 topic_msg = "k8scluster"
435 schema_new = k8scluster_new_schema
436 schema_edit = k8scluster_edit_schema
437 multiproject = True
438 password_to_encrypt = None
439 config_to_encrypt = {}
440
441 def format_on_new(self, content, project_id=None, make_public=False):
442 oid = super().format_on_new(content, project_id, make_public)
443 self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
444 schema_version=content["schema_version"], salt=content["_id"])
delacruzramoc2d5fc62020-02-05 11:50:21 +0000445 # Add Helm/Juju Repo lists
446 repos = {"helm-chart": [], "juju-bundle": []}
447 for proj in content["_admin"]["projects_read"]:
448 if proj != 'ANY':
449 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
450 if repo["_id"] not in repos[repo["type"]]:
451 repos[repo["type"]].append(repo["_id"])
452 for k in repos:
453 content["_admin"][k.replace('-', '_')+"_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200454 return oid
455
456 def format_on_edit(self, final_content, edit_content):
457 if final_content.get("schema_version") and edit_content.get("credentials"):
458 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
459 schema_version=final_content["schema_version"], salt=final_content["_id"])
460 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
461 oid = super().format_on_edit(final_content, edit_content)
462 return oid
463
delacruzramoc2d5fc62020-02-05 11:50:21 +0000464 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
bravofb995ea22021-02-10 10:57:52 -0300465 final_content = super(CommonVimWimSdn, self).check_conflict_on_edit(session, final_content, edit_content, _id)
466 final_content = super().check_conflict_on_edit(session, final_content, edit_content, _id)
delacruzramoc2d5fc62020-02-05 11:50:21 +0000467 # Update Helm/Juju Repo lists
468 repos = {"helm-chart": [], "juju-bundle": []}
469 for proj in session.get("set_project", []):
470 if proj != 'ANY':
471 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
472 if repo["_id"] not in repos[repo["type"]]:
473 repos[repo["type"]].append(repo["_id"])
474 for k in repos:
475 rlist = k.replace('-', '_') + "_repos"
476 if rlist not in final_content["_admin"]:
477 final_content["_admin"][rlist] = []
478 final_content["_admin"][rlist] += repos[k]
bravofb995ea22021-02-10 10:57:52 -0300479 return final_content
delacruzramoc2d5fc62020-02-05 11:50:21 +0000480
tiernoe19707b2020-04-21 13:08:04 +0000481 def check_conflict_on_del(self, session, _id, db_content):
482 """
483 Check if deletion can be done because of dependencies if it is not force. To override
484 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
485 :param _id: internal _id
486 :param db_content: The database content of this item _id
487 :return: None if ok or raises EngineException with the conflict
488 """
489 if session["force"]:
490 return
491 # check if used by VNF
492 filter_q = {"kdur.k8s-cluster.id": _id}
493 if session["project_id"]:
494 filter_q["_admin.projects_read.cont"] = session["project_id"]
495 if self.db.get_list("vnfrs", filter_q):
496 raise EngineException("There is at least one VNF using this k8scluster", http_code=HTTPStatus.CONFLICT)
497 super().check_conflict_on_del(session, _id, db_content)
498
delacruzramofe598fe2019-10-23 18:25:11 +0200499
David Garciaecb41322021-03-31 19:10:46 +0200500class VcaTopic(CommonVimWimSdn):
501 topic = "vca"
502 topic_msg = "vca"
503 schema_new = vca_new_schema
504 schema_edit = vca_edit_schema
505 multiproject = True
506 password_to_encrypt = None
507
508 def format_on_new(self, content, project_id=None, make_public=False):
509 oid = super().format_on_new(content, project_id, make_public)
510 content["schema_version"] = schema_version = "1.11"
511 for key in ["secret", "cacert"]:
512 content[key] = self.db.encrypt(
513 content[key],
514 schema_version=schema_version,
515 salt=content["_id"]
516 )
517 return oid
518
519 def format_on_edit(self, final_content, edit_content):
520 oid = super().format_on_edit(final_content, edit_content)
521 schema_version = final_content.get("schema_version")
522 for key in ["secret", "cacert"]:
523 if key in edit_content:
524 final_content[key] = self.db.encrypt(
525 edit_content[key],
526 schema_version=schema_version,
527 salt=final_content["_id"]
528 )
529 return oid
530
531 def check_conflict_on_del(self, session, _id, db_content):
532 """
533 Check if deletion can be done because of dependencies if it is not force. To override
534 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
535 :param _id: internal _id
536 :param db_content: The database content of this item _id
537 :return: None if ok or raises EngineException with the conflict
538 """
539 if session["force"]:
540 return
541 # check if used by VNF
542 filter_q = {"vca": _id}
543 if session["project_id"]:
544 filter_q["_admin.projects_read.cont"] = session["project_id"]
545 if self.db.get_list("vim_accounts", filter_q):
546 raise EngineException("There is at least one VIM account using this vca", http_code=HTTPStatus.CONFLICT)
547 super().check_conflict_on_del(session, _id, db_content)
548
549
delacruzramofe598fe2019-10-23 18:25:11 +0200550class K8sRepoTopic(CommonVimWimSdn):
551 topic = "k8srepos"
552 topic_msg = "k8srepo"
553 schema_new = k8srepo_new_schema
554 schema_edit = k8srepo_edit_schema
555 multiproject = True
556 password_to_encrypt = None
557 config_to_encrypt = {}
558
delacruzramoc2d5fc62020-02-05 11:50:21 +0000559 def format_on_new(self, content, project_id=None, make_public=False):
560 oid = super().format_on_new(content, project_id, make_public)
561 # Update Helm/Juju Repo lists
562 repo_list = content["type"].replace('-', '_')+"_repos"
563 for proj in content["_admin"]["projects_read"]:
564 if proj != 'ANY':
565 self.db.set_list("k8sclusters",
566 {"_admin.projects_read": proj, "_admin."+repo_list+".ne": content["_id"]}, {},
567 push={"_admin."+repo_list: content["_id"]})
568 return oid
569
570 def delete(self, session, _id, dry_run=False, not_send_msg=None):
571 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
572 oid = super().delete(session, _id, dry_run, not_send_msg)
573 if oid:
574 # Remove from Helm/Juju Repo lists
575 repo_list = type.replace('-', '_') + "_repos"
576 self.db.set_list("k8sclusters", {"_admin."+repo_list: _id}, {}, pull={"_admin."+repo_list: _id})
577 return oid
578
delacruzramofe598fe2019-10-23 18:25:11 +0200579
Felipe Vicensb66b0412020-05-06 10:11:00 +0200580class OsmRepoTopic(BaseTopic):
581 topic = "osmrepos"
582 topic_msg = "osmrepos"
583 schema_new = osmrepo_new_schema
584 schema_edit = osmrepo_edit_schema
585 multiproject = True
586 # TODO: Implement user/password
587
588
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100589class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100590 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000591 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100592 schema_new = user_new_schema
593 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100594
595 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200596 UserTopic.__init__(self, db, fs, msg, auth)
597 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100598
tierno65ca36d2019-02-12 19:27:52 +0100599 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100600 """
601 Check that the data to be inserted is valid
602
tierno65ca36d2019-02-12 19:27:52 +0100603 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100604 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100605 :return: None or raises EngineException
606 """
607 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000608 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200609 raise EngineException("username '{}' cannot have a uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000610 HTTPStatus.UNPROCESSABLE_ENTITY)
611
612 # Check that username is not used, regardless keystone already checks this
613 if self.auth.get_user_list(filter_q={"name": username}):
614 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100615
Eduardo Sousa339ed782019-05-28 14:25:00 +0100616 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000617 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200618 role = self.auth.get_role_list({"name": "project_admin"})
619 if not role:
620 role = self.auth.get_role_list()
621 if not role:
622 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
623 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000624 if not indata.get("project_role_mappings"):
625 indata["project_role_mappings"] = []
626 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200627 pid = self.auth.get_project(project)["_id"]
628 prm = {"project": pid, "role": rid}
629 if prm not in indata["project_role_mappings"]:
630 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000631 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
632 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100633
tierno65ca36d2019-02-12 19:27:52 +0100634 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100635 """
636 Check that the data to be edited/uploaded is valid
637
tierno65ca36d2019-02-12 19:27:52 +0100638 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100639 :param final_content: data once modified
640 :param edit_content: incremental data that contains the modifications to apply
641 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100642 :return: None or raises EngineException
643 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100644
tiernocf042d32019-06-13 09:06:40 +0000645 if "username" in edit_content:
646 username = edit_content.get("username")
647 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200648 raise EngineException("username '{}' cannot have an uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000649 HTTPStatus.UNPROCESSABLE_ENTITY)
650
651 # Check that username is not used, regardless keystone already checks this
652 if self.auth.get_user_list(filter_q={"name": username}):
653 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
654
655 if final_content["username"] == "admin":
656 for mapping in edit_content.get("remove_project_role_mappings", ()):
657 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
658 # TODO make this also available for project id and role id
659 raise EngineException("You cannot remove system_admin role from admin user",
660 http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100661
bravofb995ea22021-02-10 10:57:52 -0300662 return final_content
663
tiernob4844ab2019-05-23 08:42:12 +0000664 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100665 """
666 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100667 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100668 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000669 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100670 :return: None if ok or raises EngineException with the conflict
671 """
tiernocf042d32019-06-13 09:06:40 +0000672 if db_content["username"] == session["username"]:
673 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200674 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100675
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100676 @staticmethod
677 def format_on_show(content):
678 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100679 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100680 metadata from the role definition.
681 """
682 project_role_mappings = []
683
delacruzramo01b15d32019-07-02 14:37:47 +0200684 if "projects" in content:
685 for project in content["projects"]:
686 for role in project["roles"]:
687 project_role_mappings.append({"project": project["_id"],
688 "project_name": project["name"],
689 "role": role["_id"],
690 "role_name": role["name"]})
691 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100692 content["project_role_mappings"] = project_role_mappings
693
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100694 return content
695
tierno65ca36d2019-02-12 19:27:52 +0100696 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100697 """
698 Creates a new entry into the authentication backend.
699
700 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
701
702 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100703 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100704 :param indata: data to be inserted
705 :param kwargs: used to override the indata descriptor
706 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200707 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100708 """
709 try:
710 content = BaseTopic._remove_envelop(indata)
711
712 # Override descriptor with query string kwargs
713 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100714 content = self._validate_input_new(content, session["force"])
715 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000716 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200717 now = time()
718 content["_admin"] = {"created": now, "modified": now}
719 prms = []
720 for prm in content.get("project_role_mappings", []):
721 proj = self.auth.get_project(prm["project"], not session["force"])
722 role = self.auth.get_role(prm["role"], not session["force"])
723 pid = proj["_id"] if proj else None
724 rid = role["_id"] if role else None
725 prl = {"project": pid, "role": rid}
726 if prl not in prms:
727 prms.append(prl)
728 content["project_role_mappings"] = prms
729 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
730 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100731
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100732 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000733 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +0000734 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200735 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100736 except ValidationError as e:
737 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
738
K Sai Kirand010e3e2020-08-28 15:11:48 +0530739 def show(self, session, _id, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100740 """
741 Get complete information on an topic
742
tierno65ca36d2019-02-12 19:27:52 +0100743 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +0000744 :param _id: server internal id or username
K Sai Kirand010e3e2020-08-28 15:11:48 +0530745 :param api_req: True if this call is serving an external API request. False if serving internal request.
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100746 :return: dictionary, raise exception if not found.
747 """
tiernocf042d32019-06-13 09:06:40 +0000748 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000749 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200750 # users = self.auth.get_user_list(filter_q)
751 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100752 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000753 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100754 elif len(users) > 1:
tierno5ec768a2020-03-31 09:46:44 +0000755 raise EngineException("Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100756 else:
tierno5ec768a2020-03-31 09:46:44 +0000757 raise EngineException("User '{}' not found".format(_id), HTTPStatus.NOT_FOUND)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100758
tierno65ca36d2019-02-12 19:27:52 +0100759 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100760 """
761 Updates an user entry.
762
tierno65ca36d2019-02-12 19:27:52 +0100763 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100764 :param _id:
765 :param indata: data to be inserted
766 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100767 :param content:
768 :return: _id: identity of the inserted data.
769 """
770 indata = self._remove_envelop(indata)
771
772 # Override descriptor with query string kwargs
773 if kwargs:
774 BaseTopic._update_input_with_kwargs(indata, kwargs)
775 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100776 if not content:
777 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +0000778 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -0300779 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000780 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100781
delacruzramo01b15d32019-07-02 14:37:47 +0200782 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
783 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
784 indata.get("projects") or indata.get("add_projects")):
tiernocf042d32019-06-13 09:06:40 +0000785 return _id
delacruzramo01b15d32019-07-02 14:37:47 +0200786 if indata.get("project_role_mappings") \
787 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
tiernocf042d32019-06-13 09:06:40 +0000788 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
789 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
Eduardo Sousa44603902019-06-04 08:10:32 +0100790
delacruzramo01b15d32019-07-02 14:37:47 +0200791 if indata.get("projects") or indata.get("add_projects"):
792 role = self.auth.get_role_list({"name": "project_admin"})
793 if not role:
794 role = self.auth.get_role_list()
795 if not role:
796 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
797 .format(content["username"]))
798 rid = role[0]["_id"]
799 if "add_project_role_mappings" not in indata:
800 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +0000801 if "remove_project_role_mappings" not in indata:
802 indata["remove_project_role_mappings"] = []
803 if isinstance(indata.get("projects"), dict):
804 # backward compatible
805 for k, v in indata["projects"].items():
806 if k.startswith("$") and v is None:
807 indata["remove_project_role_mappings"].append({"project": k[1:]})
808 elif k.startswith("$+"):
809 indata["add_project_role_mappings"].append({"project": v, "role": rid})
810 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +0200811 for proj in indata.get("projects", []) + indata.get("add_projects", []):
812 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
813
814 # user = self.show(session, _id) # Already in 'content'
815 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100816
tiernocf042d32019-06-13 09:06:40 +0000817 mappings_to_add = []
818 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +0100819
tiernocf042d32019-06-13 09:06:40 +0000820 # remove
821 for to_remove in indata.get("remove_project_role_mappings", ()):
822 for mapping in original_mapping:
823 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
824 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
825 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +0100826
tiernocf042d32019-06-13 09:06:40 +0000827 # add
828 for to_add in indata.get("add_project_role_mappings", ()):
829 for mapping in original_mapping:
830 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
831 to_add["role"] in (mapping["role"], mapping["role_name"]):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100832
tiernocf042d32019-06-13 09:06:40 +0000833 if mapping in mappings_to_remove: # do not remove
834 mappings_to_remove.remove(mapping)
835 break # do not add, it is already at user
836 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200837 pid = self.auth.get_project(to_add["project"])["_id"]
838 rid = self.auth.get_role(to_add["role"])["_id"]
839 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000840
841 # set
842 if indata.get("project_role_mappings"):
843 for to_set in indata["project_role_mappings"]:
844 for mapping in original_mapping:
845 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
846 to_set["role"] in (mapping["role"], mapping["role_name"]):
tiernocf042d32019-06-13 09:06:40 +0000847 if mapping in mappings_to_remove: # do not remove
848 mappings_to_remove.remove(mapping)
849 break # do not add, it is already at user
850 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200851 pid = self.auth.get_project(to_set["project"])["_id"]
852 rid = self.auth.get_role(to_set["role"])["_id"]
853 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000854 for mapping in original_mapping:
855 for to_set in indata["project_role_mappings"]:
856 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
857 to_set["role"] in (mapping["role"], mapping["role_name"]):
858 break
859 else:
860 # delete
861 if mapping not in mappings_to_remove: # do not remove
862 mappings_to_remove.append(mapping)
863
delacruzramo01b15d32019-07-02 14:37:47 +0200864 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
865 "add_project_role_mappings": mappings_to_add,
866 "remove_project_role_mappings": mappings_to_remove
867 })
agarwalat53471982020-10-08 13:06:14 +0000868 data_to_send = {'_id': _id, "changes": indata}
869 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +0000870
delacruzramo01b15d32019-07-02 14:37:47 +0200871 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100872 except ValidationError as e:
873 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
874
tiernoc4e07d02020-08-14 14:25:32 +0000875 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100876 """
877 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100878 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100879 :param filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +0530880 :param api_req: True if this call is serving an external API request. False if serving internal request.
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100881 :return: The list, it can be empty if no one match the filter.
882 """
delacruzramo029405d2019-09-26 10:52:56 +0200883 user_list = self.auth.get_user_list(filter_q)
884 if not session["allow_show_user_project_role"]:
885 # Bug 853 - Default filtering
886 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
887 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100888
tiernobee3bad2019-12-05 12:26:01 +0000889 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100890 """
891 Delete item by its internal _id
892
tierno65ca36d2019-02-12 19:27:52 +0100893 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100894 :param _id: server internal id
895 :param force: indicates if deletion must be forced in case of conflict
896 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000897 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100898 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
899 """
tiernocf042d32019-06-13 09:06:40 +0000900 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200901 user = self.auth.get_user(_id)
902 uid = user["_id"]
903 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100904 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200905 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +0000906 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100907 return v
908 return None
909
910
911class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100912 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +0000913 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +0100914 schema_new = project_new_schema
915 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100916
917 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200918 ProjectTopic.__init__(self, db, fs, msg, auth)
919 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100920
tierno65ca36d2019-02-12 19:27:52 +0100921 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100922 """
923 Check that the data to be inserted is valid
924
tierno65ca36d2019-02-12 19:27:52 +0100925 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100926 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100927 :return: None or raises EngineException
928 """
tiernocf042d32019-06-13 09:06:40 +0000929 project_name = indata.get("name")
930 if is_valid_uuid(project_name):
delacruzramoceb8baf2019-06-21 14:25:38 +0200931 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000932 HTTPStatus.UNPROCESSABLE_ENTITY)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100933
tiernocf042d32019-06-13 09:06:40 +0000934 project_list = self.auth.get_project_list(filter_q={"name": project_name})
935
936 if project_list:
937 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
938
939 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
940 """
941 Check that the data to be edited/uploaded is valid
942
943 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
944 :param final_content: data once modified
945 :param edit_content: incremental data that contains the modifications to apply
946 :param _id: internal _id
947 :return: None or raises EngineException
948 """
949
950 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +0200951 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +0000952 if is_valid_uuid(project_name):
delacruzramo79e40f42019-10-10 16:36:40 +0200953 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000954 HTTPStatus.UNPROCESSABLE_ENTITY)
955
delacruzramo01b15d32019-07-02 14:37:47 +0200956 if final_content["name"] == "admin":
957 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
958
tiernocf042d32019-06-13 09:06:40 +0000959 # Check that project name is not used, regardless keystone already checks this
delacruzramo32bab472019-09-13 12:24:22 +0200960 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
tiernocf042d32019-06-13 09:06:40 +0000961 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
bravofb995ea22021-02-10 10:57:52 -0300962 return final_content
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100963
tiernob4844ab2019-05-23 08:42:12 +0000964 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100965 """
966 Check if deletion can be done because of dependencies if it is not force. To override
967
tierno65ca36d2019-02-12 19:27:52 +0100968 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100969 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000970 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100971 :return: None if ok or raises EngineException with the conflict
972 """
delacruzramo01b15d32019-07-02 14:37:47 +0200973
974 def check_rw_projects(topic, title, id_field):
975 for desc in self.db.get_list(topic):
976 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
977 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
978 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
979
980 if _id in session["project_id"]:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100981 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
982
delacruzramo01b15d32019-07-02 14:37:47 +0200983 if db_content["name"] == "admin":
984 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
985
986 # If any user is using this project, raise CONFLICT exception
987 if not session["force"]:
988 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +0000989 for prm in user.get("project_role_mappings"):
990 if prm["project"] == _id:
991 raise EngineException("Project '{}' ({}) is being used by user '{}'"
992 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200993
994 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
995 if not session["force"]:
996 check_rw_projects("vnfds", "VNF Descriptor", "id")
997 check_rw_projects("nsds", "NS Descriptor", "id")
998 check_rw_projects("nsts", "NS Template", "id")
999 check_rw_projects("pdus", "PDU Descriptor", "name")
1000
tierno65ca36d2019-02-12 19:27:52 +01001001 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001002 """
1003 Creates a new entry into the authentication backend.
1004
1005 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1006
1007 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001008 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001009 :param indata: data to be inserted
1010 :param kwargs: used to override the indata descriptor
1011 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001012 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001013 """
1014 try:
1015 content = BaseTopic._remove_envelop(indata)
1016
1017 # Override descriptor with query string kwargs
1018 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001019 content = self._validate_input_new(content, session["force"])
1020 self.check_conflict_on_new(session, content)
1021 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001022 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001023 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +00001024 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001025 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001026 except ValidationError as e:
1027 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1028
K Sai Kirand010e3e2020-08-28 15:11:48 +05301029 def show(self, session, _id, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001030 """
1031 Get complete information on an topic
1032
tierno65ca36d2019-02-12 19:27:52 +01001033 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001034 :param _id: server internal id
K Sai Kirand010e3e2020-08-28 15:11:48 +05301035 :param api_req: True if this call is serving an external API request. False if serving internal request.
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001036 :return: dictionary, raise exception if not found.
1037 """
tiernocf042d32019-06-13 09:06:40 +00001038 # Allow _id to be a name or uuid
1039 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001040 # projects = self.auth.get_project_list(filter_q=filter_q)
1041 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001042 if len(projects) == 1:
1043 return projects[0]
1044 elif len(projects) > 1:
1045 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
1046 else:
1047 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
1048
tiernoc4e07d02020-08-14 14:25:32 +00001049 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001050 """
1051 Get a list of the topic that matches a filter
1052
tierno65ca36d2019-02-12 19:27:52 +01001053 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001054 :param filter_q: filter of data to be applied
1055 :return: The list, it can be empty if no one match the filter.
1056 """
delacruzramo029405d2019-09-26 10:52:56 +02001057 project_list = self.auth.get_project_list(filter_q)
1058 if not session["allow_show_user_project_role"]:
1059 # Bug 853 - Default filtering
1060 user = self.auth.get_user(session["username"])
1061 projects = [prm["project"] for prm in user["project_role_mappings"]]
1062 project_list = [proj for proj in project_list if proj["_id"] in projects]
1063 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001064
tiernobee3bad2019-12-05 12:26:01 +00001065 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001066 """
1067 Delete item by its internal _id
1068
tierno65ca36d2019-02-12 19:27:52 +01001069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001070 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001071 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001072 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001073 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1074 """
tiernocf042d32019-06-13 09:06:40 +00001075 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001076 proj = self.auth.get_project(_id)
1077 pid = proj["_id"]
1078 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001079 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001080 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001081 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001082 return v
1083 return None
1084
tierno4015b472019-06-10 13:57:29 +00001085 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1086 """
1087 Updates a project entry.
1088
1089 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1090 :param _id:
1091 :param indata: data to be inserted
1092 :param kwargs: used to override the indata descriptor
1093 :param content:
1094 :return: _id: identity of the inserted data.
1095 """
1096 indata = self._remove_envelop(indata)
1097
1098 # Override descriptor with query string kwargs
1099 if kwargs:
1100 BaseTopic._update_input_with_kwargs(indata, kwargs)
1101 try:
tierno4015b472019-06-10 13:57:29 +00001102 if not content:
1103 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001104 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001105 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001106 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001107 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001108 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001109 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001110 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1111 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001112 except ValidationError as e:
1113 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1114
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001115
1116class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001117 topic = "roles"
1118 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001119 schema_new = roles_new_schema
1120 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001121 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001122
tierno9e87a7f2020-03-23 09:24:10 +00001123 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001124 BaseTopic.__init__(self, db, fs, msg, auth)
1125 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001126 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001127 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001128
1129 @staticmethod
1130 def validate_role_definition(operations, role_definitions):
1131 """
1132 Validates the role definition against the operations defined in
1133 the resources to operations files.
1134
1135 :param operations: operations list
1136 :param role_definitions: role definition to test
1137 :return: None if ok, raises ValidationError exception on error
1138 """
tierno1f029d82019-06-13 22:37:04 +00001139 if not role_definitions.get("permissions"):
1140 return
1141 ignore_fields = ["admin", "default"]
1142 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001143 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001144 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001145 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001146 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001147
tierno97639b42020-08-04 12:48:15 +00001148 match = next((op for op in operations if op == role_def or op.startswith(role_def + ":")), None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001149
tierno97639b42020-08-04 12:48:15 +00001150 if not match:
tierno1f029d82019-06-13 22:37:04 +00001151 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001152
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001153 def _validate_input_new(self, input, force=False):
1154 """
1155 Validates input user content for a new entry.
1156
1157 :param input: user input content for the new topic
1158 :param force: may be used for being more tolerant
1159 :return: The same input content, or a changed version of it.
1160 """
1161 if self.schema_new:
1162 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001163 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001164
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001165 return input
1166
Frank Brydendeba68e2020-07-27 13:55:11 +00001167 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001168 """
1169 Validates input user content for updating an entry.
1170
1171 :param input: user input content for the new topic
1172 :param force: may be used for being more tolerant
1173 :return: The same input content, or a changed version of it.
1174 """
1175 if self.schema_edit:
1176 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001177 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001178
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001179 return input
1180
tierno65ca36d2019-02-12 19:27:52 +01001181 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001182 """
1183 Check that the data to be inserted is valid
1184
tierno65ca36d2019-02-12 19:27:52 +01001185 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001186 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001187 :return: None or raises EngineException
1188 """
delacruzramo79e40f42019-10-10 16:36:40 +02001189 # check name is not uuid
1190 role_name = indata.get("name")
1191 if is_valid_uuid(role_name):
1192 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1193 HTTPStatus.UNPROCESSABLE_ENTITY)
tierno1f029d82019-06-13 22:37:04 +00001194 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001195 name = indata["name"]
1196 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1197 if self.auth.get_role_list({"name": name}):
1198 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001199
tierno65ca36d2019-02-12 19:27:52 +01001200 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001201 """
1202 Check that the data to be edited/uploaded is valid
1203
tierno65ca36d2019-02-12 19:27:52 +01001204 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001205 :param final_content: data once modified
1206 :param edit_content: incremental data that contains the modifications to apply
1207 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001208 :return: None or raises EngineException
1209 """
tierno1f029d82019-06-13 22:37:04 +00001210 if "default" not in final_content["permissions"]:
1211 final_content["permissions"]["default"] = False
1212 if "admin" not in final_content["permissions"]:
1213 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001214
delacruzramo79e40f42019-10-10 16:36:40 +02001215 # check name is not uuid
1216 role_name = edit_content.get("name")
1217 if is_valid_uuid(role_name):
1218 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1219 HTTPStatus.UNPROCESSABLE_ENTITY)
1220
1221 # Check renaming of admin roles
1222 role = self.auth.get_role(_id)
1223 if role["name"] in ["system_admin", "project_admin"]:
1224 raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1225
tierno1f029d82019-06-13 22:37:04 +00001226 # check name not exists
1227 if "name" in edit_content:
1228 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001229 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1230 roles = self.auth.get_role_list({"name": role_name})
1231 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
tierno1f029d82019-06-13 22:37:04 +00001232 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001233
bravofb995ea22021-02-10 10:57:52 -03001234 return final_content
1235
tiernob4844ab2019-05-23 08:42:12 +00001236 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001237 """
1238 Check if deletion can be done because of dependencies if it is not force. To override
1239
tierno65ca36d2019-02-12 19:27:52 +01001240 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001241 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001242 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001243 :return: None if ok or raises EngineException with the conflict
1244 """
delacruzramo01b15d32019-07-02 14:37:47 +02001245 role = self.auth.get_role(_id)
1246 if role["name"] in ["system_admin", "project_admin"]:
1247 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001248
delacruzramo01b15d32019-07-02 14:37:47 +02001249 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001250 if not session["force"]:
1251 for user in self.auth.get_user_list():
1252 for prm in user.get("project_role_mappings"):
1253 if prm["role"] == _id:
1254 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1255 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001256
1257 @staticmethod
delacruzramo01b15d32019-07-02 14:37:47 +02001258 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001259 """
1260 Modifies content descriptor to include _admin
1261
1262 :param content: descriptor to be modified
1263 :param project_id: if included, it add project read/write permissions
1264 :param make_public: if included it is generated as public for reading.
1265 :return: None, but content is modified
1266 """
1267 now = time()
1268 if "_admin" not in content:
1269 content["_admin"] = {}
1270 if not content["_admin"].get("created"):
1271 content["_admin"]["created"] = now
1272 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001273
tierno1f029d82019-06-13 22:37:04 +00001274 if "permissions" not in content:
1275 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001276
tierno1f029d82019-06-13 22:37:04 +00001277 if "default" not in content["permissions"]:
1278 content["permissions"]["default"] = False
1279 if "admin" not in content["permissions"]:
1280 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001281
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001282 @staticmethod
1283 def format_on_edit(final_content, edit_content):
1284 """
1285 Modifies final_content descriptor to include the modified date.
1286
1287 :param final_content: final descriptor generated
1288 :param edit_content: alterations to be include
1289 :return: None, but final_content is modified
1290 """
delacruzramo01b15d32019-07-02 14:37:47 +02001291 if "_admin" in final_content:
1292 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001293
tierno1f029d82019-06-13 22:37:04 +00001294 if "permissions" not in final_content:
1295 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001296
tierno1f029d82019-06-13 22:37:04 +00001297 if "default" not in final_content["permissions"]:
1298 final_content["permissions"]["default"] = False
1299 if "admin" not in final_content["permissions"]:
1300 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001301 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001302
K Sai Kirand010e3e2020-08-28 15:11:48 +05301303 def show(self, session, _id, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001304 """
1305 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001306
delacruzramo01b15d32019-07-02 14:37:47 +02001307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1308 :param _id: server internal id
K Sai Kirand010e3e2020-08-28 15:11:48 +05301309 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001310 :return: dictionary, raise exception if not found.
1311 """
1312 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001313 # roles = self.auth.get_role_list(filter_q)
1314 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001315 if not roles:
1316 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1317 elif len(roles) > 1:
1318 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1319 return roles[0]
1320
tiernoc4e07d02020-08-14 14:25:32 +00001321 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001322 """
1323 Get a list of the topic that matches a filter
1324
1325 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1326 :param filter_q: filter of data to be applied
1327 :return: The list, it can be empty if no one match the filter.
1328 """
delacruzramo029405d2019-09-26 10:52:56 +02001329 role_list = self.auth.get_role_list(filter_q)
1330 if not session["allow_show_user_project_role"]:
1331 # Bug 853 - Default filtering
1332 user = self.auth.get_user(session["username"])
1333 roles = [prm["role"] for prm in user["project_role_mappings"]]
1334 role_list = [role for role in role_list if role["_id"] in roles]
1335 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001336
tierno65ca36d2019-02-12 19:27:52 +01001337 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001338 """
1339 Creates a new entry into database.
1340
1341 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001342 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001343 :param indata: data to be inserted
1344 :param kwargs: used to override the indata descriptor
1345 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001346 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001347 """
1348 try:
tierno1f029d82019-06-13 22:37:04 +00001349 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001350
1351 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001352 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001353 content = self._validate_input_new(content, session["force"])
1354 self.check_conflict_on_new(session, content)
1355 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001356 # role_name = content["name"]
1357 rid = self.auth.create_role(content)
1358 content["_id"] = rid
1359 # _id = self.db.create(self.topic, content)
1360 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001361 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001362 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001363 except ValidationError as e:
1364 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1365
tiernobee3bad2019-12-05 12:26:01 +00001366 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001367 """
1368 Delete item by its internal _id
1369
tierno65ca36d2019-02-12 19:27:52 +01001370 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001371 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001372 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001373 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001374 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1375 """
delacruzramo01b15d32019-07-02 14:37:47 +02001376 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1377 roles = self.auth.get_role_list(filter_q)
1378 if not roles:
1379 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1380 elif len(roles) > 1:
1381 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1382 rid = roles[0]["_id"]
1383 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001384 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001385 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001386 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001387 v = self.auth.delete_role(rid)
1388 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001389 return v
1390 return None
1391
tierno65ca36d2019-02-12 19:27:52 +01001392 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001393 """
1394 Updates a role entry.
1395
tierno65ca36d2019-02-12 19:27:52 +01001396 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001397 :param _id:
1398 :param indata: data to be inserted
1399 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001400 :param content:
1401 :return: _id: identity of the inserted data.
1402 """
delacruzramo01b15d32019-07-02 14:37:47 +02001403 if kwargs:
1404 self._update_input_with_kwargs(indata, kwargs)
1405 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001406 if not content:
1407 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001408 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001409 deep_update_rfc7396(content, indata)
bravofb995ea22021-02-10 10:57:52 -03001410 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001411 self.format_on_edit(content, indata)
1412 self.auth.update_role(content)
1413 except ValidationError as e:
1414 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)