blob: 4f9ab0c1401d99569fab5dbcc7bf3fe379cd8cc6 [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, \
Felipe Vicensb66b0412020-05-06 10:11:00 +020025 osmrepo_new_schema, osmrepo_edit_schema, \
26 validate_input, ValidationError, is_valid_uuid # To check that User/Project Names don't look like UUIDs
tierno23acf402019-08-28 13:36:34 +000027from osm_nbi.base_topic import BaseTopic, EngineException
28from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020029from osm_common.dbbase import deep_update_rfc7396
agarwalat53471982020-10-08 13:06:14 +000030import copy
tiernob24258a2018-10-04 18:39:49 +020031
32__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
33
34
35class UserTopic(BaseTopic):
36 topic = "users"
37 topic_msg = "users"
38 schema_new = user_new_schema
39 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010040 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020041
delacruzramo32bab472019-09-13 12:24:22 +020042 def __init__(self, db, fs, msg, auth):
43 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020044
45 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010046 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020047 """
48 Generates a filter dictionary for querying database users.
49 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010050 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020051 :return:
52 """
53 if session["admin"]: # allows all
54 return {}
55 else:
56 return {"username": session["username"]}
57
tierno65ca36d2019-02-12 19:27:52 +010058 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020059 # check username not exists
60 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
61 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
62 # check projects
tierno65ca36d2019-02-12 19:27:52 +010063 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020064 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020065 # To allow project addressing by Name as well as ID
66 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
67 fail_on_more=False):
68 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
tiernob24258a2018-10-04 18:39:49 +020069
tiernob4844ab2019-05-23 08:42:12 +000070 def check_conflict_on_del(self, session, _id, db_content):
71 """
72 Check if deletion can be done because of dependencies if it is not force. To override
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: internal _id
75 :param db_content: The database content of this item _id
76 :return: None if ok or raises EngineException with the conflict
77 """
tiernob24258a2018-10-04 18:39:49 +020078 if _id == session["username"]:
79 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
80
81 @staticmethod
82 def format_on_new(content, project_id=None, make_public=False):
83 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +020084 # Removed so that the UUID is kept, to allow User Name modification
85 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +020086 salt = uuid4().hex
87 content["_admin"]["salt"] = salt
88 if content.get("password"):
89 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +010090 if content.get("project_role_mappings"):
delacruzramo01b15d32019-07-02 14:37:47 +020091 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
Eduardo Sousa339ed782019-05-28 14:25:00 +010092
93 if content.get("projects"):
94 content["projects"] += projects
95 else:
96 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +020097
98 @staticmethod
99 def format_on_edit(final_content, edit_content):
100 BaseTopic.format_on_edit(final_content, edit_content)
101 if edit_content.get("password"):
102 salt = uuid4().hex
103 final_content["_admin"]["salt"] = salt
104 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
105 salt.encode('utf-8')).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000106 return None
tiernob24258a2018-10-04 18:39:49 +0200107
tierno65ca36d2019-02-12 19:27:52 +0100108 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200109 if not session["admin"]:
110 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200111 # Names that look like UUIDs are not allowed
112 name = (indata if indata else kwargs).get("username")
113 if is_valid_uuid(name):
114 raise EngineException("Usernames that look like UUIDs are not allowed",
115 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100116 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200117
tierno65ca36d2019-02-12 19:27:52 +0100118 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200119 if not session["admin"]:
120 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200121 # Names that look like UUIDs are not allowed
122 name = indata["username"] if indata else kwargs["username"]
123 if is_valid_uuid(name):
124 raise EngineException("Usernames that look like UUIDs are not allowed",
125 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100126 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200127
128
129class ProjectTopic(BaseTopic):
130 topic = "projects"
131 topic_msg = "projects"
132 schema_new = project_new_schema
133 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100134 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200135
delacruzramo32bab472019-09-13 12:24:22 +0200136 def __init__(self, db, fs, msg, auth):
137 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200138
tierno65ca36d2019-02-12 19:27:52 +0100139 @staticmethod
140 def _get_project_filter(session):
141 """
142 Generates a filter dictionary for querying database users.
143 Current policy is admin can show all, non admin, only its own user.
144 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
145 :return:
146 """
147 if session["admin"]: # allows all
148 return {}
149 else:
150 return {"_id.cont": session["project_id"]}
151
152 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200153 if not indata.get("name"):
154 raise EngineException("missing 'name'")
155 # check name not exists
156 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
157 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
158
159 @staticmethod
160 def format_on_new(content, project_id=None, make_public=False):
161 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200162 # Removed so that the UUID is kept, to allow Project Name modification
163 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200164
tiernob4844ab2019-05-23 08:42:12 +0000165 def check_conflict_on_del(self, session, _id, db_content):
166 """
167 Check if deletion can be done because of dependencies if it is not force. To override
168 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
169 :param _id: internal _id
170 :param db_content: The database content of this item _id
171 :return: None if ok or raises EngineException with the conflict
172 """
tierno65ca36d2019-02-12 19:27:52 +0100173 if _id in session["project_id"]:
tiernob24258a2018-10-04 18:39:49 +0200174 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
tierno65ca36d2019-02-12 19:27:52 +0100175 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200176 return
177 _filter = {"projects": _id}
178 if self.db.get_list("users", _filter):
179 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
180
tierno65ca36d2019-02-12 19:27:52 +0100181 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200182 if not session["admin"]:
183 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200184 # Names that look like UUIDs are not allowed
185 name = (indata if indata else kwargs).get("name")
186 if is_valid_uuid(name):
187 raise EngineException("Project names that look like UUIDs are not allowed",
188 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100189 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200190
tierno65ca36d2019-02-12 19:27:52 +0100191 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200192 if not session["admin"]:
193 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200194 # Names that look like UUIDs are not allowed
195 name = indata["name"] if indata else kwargs["name"]
196 if is_valid_uuid(name):
197 raise EngineException("Project names that look like UUIDs are not allowed",
198 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100199 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200200
201
tiernobdebce92019-07-01 15:36:49 +0000202class CommonVimWimSdn(BaseTopic):
203 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
tierno468aa242019-08-01 16:35:04 +0000204 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
tiernobdebce92019-07-01 15:36:49 +0000205 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200206
tiernobdebce92019-07-01 15:36:49 +0000207 @staticmethod
208 def _create_operation(op_type, params=None):
209 """
210 Creates a dictionary with the information to an operation, similar to ns-lcm-op
211 :param op_type: can be create, edit, delete
212 :param params: operation input parameters
213 :return: new dictionary with
214 """
215 now = time()
216 return {
217 "lcmOperationType": op_type,
218 "operationState": "PROCESSING",
219 "startTime": now,
220 "statusEnteredTime": now,
221 "detailed-status": "",
222 "operationParams": params,
223 }
tiernob24258a2018-10-04 18:39:49 +0200224
tierno65ca36d2019-02-12 19:27:52 +0100225 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000226 """
227 Check that the data to be inserted is valid. It is checked that name is unique
228 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
229 :param indata: data to be inserted
230 :return: None or raises EngineException
231 """
tiernob24258a2018-10-04 18:39:49 +0200232 self.check_unique_name(session, indata["name"], _id=None)
233
tierno65ca36d2019-02-12 19:27:52 +0100234 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000235 """
236 Check that the data to be edited/uploaded is valid. It is checked that name is unique
237 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
238 :param final_content: data once modified. This method may change it.
239 :param edit_content: incremental data that contains the modifications to apply
240 :param _id: internal _id
241 :return: None or raises EngineException
242 """
tierno65ca36d2019-02-12 19:27:52 +0100243 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200244 self.check_unique_name(session, edit_content["name"], _id=_id)
245
tiernobdebce92019-07-01 15:36:49 +0000246 def format_on_edit(self, final_content, edit_content):
247 """
248 Modifies final_content inserting admin information upon edition
249 :param final_content: final content to be stored at database
250 :param edit_content: user requested update content
251 :return: operation id
252 """
delacruzramofe598fe2019-10-23 18:25:11 +0200253 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000254
tierno92c1c7d2018-11-12 15:22:37 +0100255 # encrypt passwords
256 schema_version = final_content.get("schema_version")
257 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000258 if edit_content.get(self.password_to_encrypt):
259 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
260 schema_version=schema_version,
261 salt=final_content["_id"])
tierno468aa242019-08-01 16:35:04 +0000262 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
263 if edit_content.get("config") and config_to_encrypt_keys:
264
265 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100266 if edit_content["config"].get(p):
267 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
tiernobdebce92019-07-01 15:36:49 +0000268 schema_version=schema_version,
269 salt=final_content["_id"])
270
271 # create edit operation
272 final_content["_admin"]["operations"].append(self._create_operation("edit"))
273 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
tierno92c1c7d2018-11-12 15:22:37 +0100274
275 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000276 """
277 Modifies content descriptor to include _admin and insert create operation
278 :param content: descriptor to be modified
279 :param project_id: if included, it add project read/write permissions. Can be None or a list
280 :param make_public: if included it is generated as public for reading.
281 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
282 """
283 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000284 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100285
286 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000287 if content.get(self.password_to_encrypt):
288 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
289 schema_version=schema_version,
290 salt=content["_id"])
tierno468aa242019-08-01 16:35:04 +0000291 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
292 if content.get("config") and config_to_encrypt_keys:
293 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100294 if content["config"].get(p):
tiernobdebce92019-07-01 15:36:49 +0000295 content["config"][p] = self.db.encrypt(content["config"][p],
296 schema_version=schema_version,
tierno92c1c7d2018-11-12 15:22:37 +0100297 salt=content["_id"])
298
tiernob24258a2018-10-04 18:39:49 +0200299 content["_admin"]["operationalState"] = "PROCESSING"
300
tiernobdebce92019-07-01 15:36:49 +0000301 # create operation
302 content["_admin"]["operations"] = [self._create_operation("create")]
303 content["_admin"]["current_operation"] = None
304
305 return "{}:0".format(content["_id"])
306
tiernobee3bad2019-12-05 12:26:01 +0000307 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200308 """
309 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100310 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200311 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200312 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000313 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000314 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200315 """
tiernobdebce92019-07-01 15:36:49 +0000316
317 filter_q = self._get_project_filter(session)
318 filter_q["_id"] = _id
319 db_content = self.db.get_one(self.topic, filter_q)
320
321 self.check_conflict_on_del(session, _id, db_content)
322 if dry_run:
323 return None
324
tiernof5f2e3f2020-03-23 14:42:10 +0000325 # remove reference from project_read if there are more projects referencing it. If it last one,
326 # do not remove reference, but order via kafka to delete it
327 if session["project_id"] and session["project_id"]:
328 other_projects_referencing = next((p for p in db_content["_admin"]["projects_read"]
tierno20e74d22020-06-22 12:17:22 +0000329 if p not in session["project_id"] and p != "ANY"), None)
tiernobdebce92019-07-01 15:36:49 +0000330
tiernof5f2e3f2020-03-23 14:42:10 +0000331 # check if there are projects referencing it (apart from ANY, that means, public)....
332 if other_projects_referencing:
333 # remove references but not delete
tierno20e74d22020-06-22 12:17:22 +0000334 update_dict_pull = {"_admin.projects_read": session["project_id"],
335 "_admin.projects_write": session["project_id"]}
336 self.db.set_one(self.topic, filter_q, update_dict=None, pull_list=update_dict_pull)
tiernof5f2e3f2020-03-23 14:42:10 +0000337 return None
338 else:
339 can_write = next((p for p in db_content["_admin"]["projects_write"] if p == "ANY" or
340 p in session["project_id"]), None)
341 if not can_write:
342 raise EngineException("You have not write permission to delete it",
343 http_code=HTTPStatus.UNAUTHORIZED)
tiernobdebce92019-07-01 15:36:49 +0000344
345 # It must be deleted
346 if session["force"]:
347 self.db.del_one(self.topic, {"_id": _id})
348 op_id = None
tiernobee3bad2019-12-05 12:26:01 +0000349 self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000350 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000351 update_dict = {"_admin.to_delete": True}
tiernobdebce92019-07-01 15:36:49 +0000352 self.db.set_one(self.topic, {"_id": _id},
353 update_dict=update_dict,
354 push={"_admin.operations": self._create_operation("delete")}
355 )
356 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
357 # so the -1 is not needed
358 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
tiernobee3bad2019-12-05 12:26:01 +0000359 self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000360 return op_id
tiernob24258a2018-10-04 18:39:49 +0200361
362
tiernobdebce92019-07-01 15:36:49 +0000363class VimAccountTopic(CommonVimWimSdn):
364 topic = "vim_accounts"
365 topic_msg = "vim_account"
366 schema_new = vim_account_new_schema
367 schema_edit = vim_account_edit_schema
368 multiproject = True
369 password_to_encrypt = "vim_password"
tierno468aa242019-08-01 16:35:04 +0000370 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
371 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
tiernobdebce92019-07-01 15:36:49 +0000372
delacruzramo35c998b2019-11-21 11:09:16 +0100373 def check_conflict_on_del(self, session, _id, db_content):
374 """
375 Check if deletion can be done because of dependencies if it is not force. To override
376 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
377 :param _id: internal _id
378 :param db_content: The database content of this item _id
379 :return: None if ok or raises EngineException with the conflict
380 """
381 if session["force"]:
382 return
383 # check if used by VNF
384 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
385 raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
386 super().check_conflict_on_del(session, _id, db_content)
387
tiernobdebce92019-07-01 15:36:49 +0000388
389class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000390 topic = "wim_accounts"
391 topic_msg = "wim_account"
392 schema_new = wim_account_new_schema
393 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100394 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000395 password_to_encrypt = "wim_password"
tierno468aa242019-08-01 16:35:04 +0000396 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000397
398
tiernobdebce92019-07-01 15:36:49 +0000399class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200400 topic = "sdns"
401 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000402 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200403 schema_new = sdn_new_schema
404 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100405 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000406 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000407 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100408
tierno7adaeb02019-12-17 16:46:12 +0000409 def _obtain_url(self, input, create):
410 if input.get("ip") or input.get("port"):
411 if not input.get("ip") or not input.get("port") or input.get('url'):
412 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
413 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
414 del input["ip"]
415 del input["port"]
416 elif create and not input.get('url'):
417 raise ValidationError("You must provide 'url'")
418 return input
419
420 def _validate_input_new(self, input, force=False):
421 input = super()._validate_input_new(input, force)
422 return self._obtain_url(input, True)
423
Frank Brydendeba68e2020-07-27 13:55:11 +0000424 def _validate_input_edit(self, input, content, force=False):
425 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000426 return self._obtain_url(input, False)
427
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100428
delacruzramofe598fe2019-10-23 18:25:11 +0200429class K8sClusterTopic(CommonVimWimSdn):
430 topic = "k8sclusters"
431 topic_msg = "k8scluster"
432 schema_new = k8scluster_new_schema
433 schema_edit = k8scluster_edit_schema
434 multiproject = True
435 password_to_encrypt = None
436 config_to_encrypt = {}
437
438 def format_on_new(self, content, project_id=None, make_public=False):
439 oid = super().format_on_new(content, project_id, make_public)
440 self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
441 schema_version=content["schema_version"], salt=content["_id"])
delacruzramoc2d5fc62020-02-05 11:50:21 +0000442 # Add Helm/Juju Repo lists
443 repos = {"helm-chart": [], "juju-bundle": []}
444 for proj in content["_admin"]["projects_read"]:
445 if proj != 'ANY':
446 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
447 if repo["_id"] not in repos[repo["type"]]:
448 repos[repo["type"]].append(repo["_id"])
449 for k in repos:
450 content["_admin"][k.replace('-', '_')+"_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200451 return oid
452
453 def format_on_edit(self, final_content, edit_content):
454 if final_content.get("schema_version") and edit_content.get("credentials"):
455 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
456 schema_version=final_content["schema_version"], salt=final_content["_id"])
457 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
458 oid = super().format_on_edit(final_content, edit_content)
459 return oid
460
delacruzramoc2d5fc62020-02-05 11:50:21 +0000461 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
462 super(CommonVimWimSdn, self).check_conflict_on_edit(session, final_content, edit_content, _id)
463 super().check_conflict_on_edit(session, final_content, edit_content, _id)
464 # Update Helm/Juju Repo lists
465 repos = {"helm-chart": [], "juju-bundle": []}
466 for proj in session.get("set_project", []):
467 if proj != 'ANY':
468 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
469 if repo["_id"] not in repos[repo["type"]]:
470 repos[repo["type"]].append(repo["_id"])
471 for k in repos:
472 rlist = k.replace('-', '_') + "_repos"
473 if rlist not in final_content["_admin"]:
474 final_content["_admin"][rlist] = []
475 final_content["_admin"][rlist] += repos[k]
476
tiernoe19707b2020-04-21 13:08:04 +0000477 def check_conflict_on_del(self, session, _id, db_content):
478 """
479 Check if deletion can be done because of dependencies if it is not force. To override
480 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
481 :param _id: internal _id
482 :param db_content: The database content of this item _id
483 :return: None if ok or raises EngineException with the conflict
484 """
485 if session["force"]:
486 return
487 # check if used by VNF
488 filter_q = {"kdur.k8s-cluster.id": _id}
489 if session["project_id"]:
490 filter_q["_admin.projects_read.cont"] = session["project_id"]
491 if self.db.get_list("vnfrs", filter_q):
492 raise EngineException("There is at least one VNF using this k8scluster", http_code=HTTPStatus.CONFLICT)
493 super().check_conflict_on_del(session, _id, db_content)
494
delacruzramofe598fe2019-10-23 18:25:11 +0200495
496class K8sRepoTopic(CommonVimWimSdn):
497 topic = "k8srepos"
498 topic_msg = "k8srepo"
499 schema_new = k8srepo_new_schema
500 schema_edit = k8srepo_edit_schema
501 multiproject = True
502 password_to_encrypt = None
503 config_to_encrypt = {}
504
delacruzramoc2d5fc62020-02-05 11:50:21 +0000505 def format_on_new(self, content, project_id=None, make_public=False):
506 oid = super().format_on_new(content, project_id, make_public)
507 # Update Helm/Juju Repo lists
508 repo_list = content["type"].replace('-', '_')+"_repos"
509 for proj in content["_admin"]["projects_read"]:
510 if proj != 'ANY':
511 self.db.set_list("k8sclusters",
512 {"_admin.projects_read": proj, "_admin."+repo_list+".ne": content["_id"]}, {},
513 push={"_admin."+repo_list: content["_id"]})
514 return oid
515
516 def delete(self, session, _id, dry_run=False, not_send_msg=None):
517 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
518 oid = super().delete(session, _id, dry_run, not_send_msg)
519 if oid:
520 # Remove from Helm/Juju Repo lists
521 repo_list = type.replace('-', '_') + "_repos"
522 self.db.set_list("k8sclusters", {"_admin."+repo_list: _id}, {}, pull={"_admin."+repo_list: _id})
523 return oid
524
delacruzramofe598fe2019-10-23 18:25:11 +0200525
Felipe Vicensb66b0412020-05-06 10:11:00 +0200526class OsmRepoTopic(BaseTopic):
527 topic = "osmrepos"
528 topic_msg = "osmrepos"
529 schema_new = osmrepo_new_schema
530 schema_edit = osmrepo_edit_schema
531 multiproject = True
532 # TODO: Implement user/password
533
534
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100535class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100536 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000537 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100538 schema_new = user_new_schema
539 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100540
541 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200542 UserTopic.__init__(self, db, fs, msg, auth)
543 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100544
tierno65ca36d2019-02-12 19:27:52 +0100545 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100546 """
547 Check that the data to be inserted is valid
548
tierno65ca36d2019-02-12 19:27:52 +0100549 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100550 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100551 :return: None or raises EngineException
552 """
553 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000554 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200555 raise EngineException("username '{}' cannot have a uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000556 HTTPStatus.UNPROCESSABLE_ENTITY)
557
558 # Check that username is not used, regardless keystone already checks this
559 if self.auth.get_user_list(filter_q={"name": username}):
560 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100561
Eduardo Sousa339ed782019-05-28 14:25:00 +0100562 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000563 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200564 role = self.auth.get_role_list({"name": "project_admin"})
565 if not role:
566 role = self.auth.get_role_list()
567 if not role:
568 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
569 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000570 if not indata.get("project_role_mappings"):
571 indata["project_role_mappings"] = []
572 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200573 pid = self.auth.get_project(project)["_id"]
574 prm = {"project": pid, "role": rid}
575 if prm not in indata["project_role_mappings"]:
576 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000577 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
578 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100579
tierno65ca36d2019-02-12 19:27:52 +0100580 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100581 """
582 Check that the data to be edited/uploaded is valid
583
tierno65ca36d2019-02-12 19:27:52 +0100584 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100585 :param final_content: data once modified
586 :param edit_content: incremental data that contains the modifications to apply
587 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100588 :return: None or raises EngineException
589 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100590
tiernocf042d32019-06-13 09:06:40 +0000591 if "username" in edit_content:
592 username = edit_content.get("username")
593 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200594 raise EngineException("username '{}' cannot have an uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000595 HTTPStatus.UNPROCESSABLE_ENTITY)
596
597 # Check that username is not used, regardless keystone already checks this
598 if self.auth.get_user_list(filter_q={"name": username}):
599 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
600
601 if final_content["username"] == "admin":
602 for mapping in edit_content.get("remove_project_role_mappings", ()):
603 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
604 # TODO make this also available for project id and role id
605 raise EngineException("You cannot remove system_admin role from admin user",
606 http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100607
tiernob4844ab2019-05-23 08:42:12 +0000608 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100609 """
610 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100611 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100612 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000613 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100614 :return: None if ok or raises EngineException with the conflict
615 """
tiernocf042d32019-06-13 09:06:40 +0000616 if db_content["username"] == session["username"]:
617 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200618 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100619
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100620 @staticmethod
621 def format_on_show(content):
622 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100623 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100624 metadata from the role definition.
625 """
626 project_role_mappings = []
627
delacruzramo01b15d32019-07-02 14:37:47 +0200628 if "projects" in content:
629 for project in content["projects"]:
630 for role in project["roles"]:
631 project_role_mappings.append({"project": project["_id"],
632 "project_name": project["name"],
633 "role": role["_id"],
634 "role_name": role["name"]})
635 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100636 content["project_role_mappings"] = project_role_mappings
637
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100638 return content
639
tierno65ca36d2019-02-12 19:27:52 +0100640 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100641 """
642 Creates a new entry into the authentication backend.
643
644 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
645
646 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100647 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100648 :param indata: data to be inserted
649 :param kwargs: used to override the indata descriptor
650 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200651 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100652 """
653 try:
654 content = BaseTopic._remove_envelop(indata)
655
656 # Override descriptor with query string kwargs
657 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100658 content = self._validate_input_new(content, session["force"])
659 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000660 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200661 now = time()
662 content["_admin"] = {"created": now, "modified": now}
663 prms = []
664 for prm in content.get("project_role_mappings", []):
665 proj = self.auth.get_project(prm["project"], not session["force"])
666 role = self.auth.get_role(prm["role"], not session["force"])
667 pid = proj["_id"] if proj else None
668 rid = role["_id"] if role else None
669 prl = {"project": pid, "role": rid}
670 if prl not in prms:
671 prms.append(prl)
672 content["project_role_mappings"] = prms
673 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
674 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100675
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100676 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000677 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +0000678 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200679 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100680 except ValidationError as e:
681 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
682
K Sai Kirand010e3e2020-08-28 15:11:48 +0530683 def show(self, session, _id, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100684 """
685 Get complete information on an topic
686
tierno65ca36d2019-02-12 19:27:52 +0100687 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +0000688 :param _id: server internal id or username
K Sai Kirand010e3e2020-08-28 15:11:48 +0530689 :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 +0100690 :return: dictionary, raise exception if not found.
691 """
tiernocf042d32019-06-13 09:06:40 +0000692 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000693 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200694 # users = self.auth.get_user_list(filter_q)
695 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100696 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000697 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100698 elif len(users) > 1:
tierno5ec768a2020-03-31 09:46:44 +0000699 raise EngineException("Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100700 else:
tierno5ec768a2020-03-31 09:46:44 +0000701 raise EngineException("User '{}' not found".format(_id), HTTPStatus.NOT_FOUND)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100702
tierno65ca36d2019-02-12 19:27:52 +0100703 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100704 """
705 Updates an user entry.
706
tierno65ca36d2019-02-12 19:27:52 +0100707 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100708 :param _id:
709 :param indata: data to be inserted
710 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100711 :param content:
712 :return: _id: identity of the inserted data.
713 """
714 indata = self._remove_envelop(indata)
715
716 # Override descriptor with query string kwargs
717 if kwargs:
718 BaseTopic._update_input_with_kwargs(indata, kwargs)
719 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100720 if not content:
721 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +0000722 indata = self._validate_input_edit(indata, content, force=session["force"])
tierno65ca36d2019-02-12 19:27:52 +0100723 self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000724 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100725
delacruzramo01b15d32019-07-02 14:37:47 +0200726 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
727 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
728 indata.get("projects") or indata.get("add_projects")):
tiernocf042d32019-06-13 09:06:40 +0000729 return _id
delacruzramo01b15d32019-07-02 14:37:47 +0200730 if indata.get("project_role_mappings") \
731 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
tiernocf042d32019-06-13 09:06:40 +0000732 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
733 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
Eduardo Sousa44603902019-06-04 08:10:32 +0100734
delacruzramo01b15d32019-07-02 14:37:47 +0200735 if indata.get("projects") or indata.get("add_projects"):
736 role = self.auth.get_role_list({"name": "project_admin"})
737 if not role:
738 role = self.auth.get_role_list()
739 if not role:
740 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
741 .format(content["username"]))
742 rid = role[0]["_id"]
743 if "add_project_role_mappings" not in indata:
744 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +0000745 if "remove_project_role_mappings" not in indata:
746 indata["remove_project_role_mappings"] = []
747 if isinstance(indata.get("projects"), dict):
748 # backward compatible
749 for k, v in indata["projects"].items():
750 if k.startswith("$") and v is None:
751 indata["remove_project_role_mappings"].append({"project": k[1:]})
752 elif k.startswith("$+"):
753 indata["add_project_role_mappings"].append({"project": v, "role": rid})
754 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +0200755 for proj in indata.get("projects", []) + indata.get("add_projects", []):
756 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
757
758 # user = self.show(session, _id) # Already in 'content'
759 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100760
tiernocf042d32019-06-13 09:06:40 +0000761 mappings_to_add = []
762 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +0100763
tiernocf042d32019-06-13 09:06:40 +0000764 # remove
765 for to_remove in indata.get("remove_project_role_mappings", ()):
766 for mapping in original_mapping:
767 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
768 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
769 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +0100770
tiernocf042d32019-06-13 09:06:40 +0000771 # add
772 for to_add in indata.get("add_project_role_mappings", ()):
773 for mapping in original_mapping:
774 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
775 to_add["role"] in (mapping["role"], mapping["role_name"]):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100776
tiernocf042d32019-06-13 09:06:40 +0000777 if mapping in mappings_to_remove: # do not remove
778 mappings_to_remove.remove(mapping)
779 break # do not add, it is already at user
780 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200781 pid = self.auth.get_project(to_add["project"])["_id"]
782 rid = self.auth.get_role(to_add["role"])["_id"]
783 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000784
785 # set
786 if indata.get("project_role_mappings"):
787 for to_set in indata["project_role_mappings"]:
788 for mapping in original_mapping:
789 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
790 to_set["role"] in (mapping["role"], mapping["role_name"]):
tiernocf042d32019-06-13 09:06:40 +0000791 if mapping in mappings_to_remove: # do not remove
792 mappings_to_remove.remove(mapping)
793 break # do not add, it is already at user
794 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200795 pid = self.auth.get_project(to_set["project"])["_id"]
796 rid = self.auth.get_role(to_set["role"])["_id"]
797 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000798 for mapping in original_mapping:
799 for to_set in indata["project_role_mappings"]:
800 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
801 to_set["role"] in (mapping["role"], mapping["role_name"]):
802 break
803 else:
804 # delete
805 if mapping not in mappings_to_remove: # do not remove
806 mappings_to_remove.append(mapping)
807
delacruzramo01b15d32019-07-02 14:37:47 +0200808 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
809 "add_project_role_mappings": mappings_to_add,
810 "remove_project_role_mappings": mappings_to_remove
811 })
agarwalat53471982020-10-08 13:06:14 +0000812 data_to_send = {'_id': _id, "changes": indata}
813 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +0000814
delacruzramo01b15d32019-07-02 14:37:47 +0200815 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100816 except ValidationError as e:
817 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
818
tiernoc4e07d02020-08-14 14:25:32 +0000819 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100820 """
821 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100822 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100823 :param filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +0530824 :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 +0100825 :return: The list, it can be empty if no one match the filter.
826 """
delacruzramo029405d2019-09-26 10:52:56 +0200827 user_list = self.auth.get_user_list(filter_q)
828 if not session["allow_show_user_project_role"]:
829 # Bug 853 - Default filtering
830 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
831 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100832
tiernobee3bad2019-12-05 12:26:01 +0000833 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100834 """
835 Delete item by its internal _id
836
tierno65ca36d2019-02-12 19:27:52 +0100837 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100838 :param _id: server internal id
839 :param force: indicates if deletion must be forced in case of conflict
840 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000841 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100842 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
843 """
tiernocf042d32019-06-13 09:06:40 +0000844 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200845 user = self.auth.get_user(_id)
846 uid = user["_id"]
847 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100848 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200849 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +0000850 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100851 return v
852 return None
853
854
855class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100856 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +0000857 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +0100858 schema_new = project_new_schema
859 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100860
861 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200862 ProjectTopic.__init__(self, db, fs, msg, auth)
863 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100864
tierno65ca36d2019-02-12 19:27:52 +0100865 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100866 """
867 Check that the data to be inserted is valid
868
tierno65ca36d2019-02-12 19:27:52 +0100869 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100870 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100871 :return: None or raises EngineException
872 """
tiernocf042d32019-06-13 09:06:40 +0000873 project_name = indata.get("name")
874 if is_valid_uuid(project_name):
delacruzramoceb8baf2019-06-21 14:25:38 +0200875 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000876 HTTPStatus.UNPROCESSABLE_ENTITY)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100877
tiernocf042d32019-06-13 09:06:40 +0000878 project_list = self.auth.get_project_list(filter_q={"name": project_name})
879
880 if project_list:
881 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
882
883 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
884 """
885 Check that the data to be edited/uploaded is valid
886
887 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
888 :param final_content: data once modified
889 :param edit_content: incremental data that contains the modifications to apply
890 :param _id: internal _id
891 :return: None or raises EngineException
892 """
893
894 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +0200895 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +0000896 if is_valid_uuid(project_name):
delacruzramo79e40f42019-10-10 16:36:40 +0200897 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000898 HTTPStatus.UNPROCESSABLE_ENTITY)
899
delacruzramo01b15d32019-07-02 14:37:47 +0200900 if final_content["name"] == "admin":
901 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
902
tiernocf042d32019-06-13 09:06:40 +0000903 # Check that project name is not used, regardless keystone already checks this
delacruzramo32bab472019-09-13 12:24:22 +0200904 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
tiernocf042d32019-06-13 09:06:40 +0000905 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100906
tiernob4844ab2019-05-23 08:42:12 +0000907 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100908 """
909 Check if deletion can be done because of dependencies if it is not force. To override
910
tierno65ca36d2019-02-12 19:27:52 +0100911 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100912 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000913 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100914 :return: None if ok or raises EngineException with the conflict
915 """
delacruzramo01b15d32019-07-02 14:37:47 +0200916
917 def check_rw_projects(topic, title, id_field):
918 for desc in self.db.get_list(topic):
919 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
920 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
921 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
922
923 if _id in session["project_id"]:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100924 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
925
delacruzramo01b15d32019-07-02 14:37:47 +0200926 if db_content["name"] == "admin":
927 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
928
929 # If any user is using this project, raise CONFLICT exception
930 if not session["force"]:
931 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +0000932 for prm in user.get("project_role_mappings"):
933 if prm["project"] == _id:
934 raise EngineException("Project '{}' ({}) is being used by user '{}'"
935 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200936
937 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
938 if not session["force"]:
939 check_rw_projects("vnfds", "VNF Descriptor", "id")
940 check_rw_projects("nsds", "NS Descriptor", "id")
941 check_rw_projects("nsts", "NS Template", "id")
942 check_rw_projects("pdus", "PDU Descriptor", "name")
943
tierno65ca36d2019-02-12 19:27:52 +0100944 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100945 """
946 Creates a new entry into the authentication backend.
947
948 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
949
950 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100951 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100952 :param indata: data to be inserted
953 :param kwargs: used to override the indata descriptor
954 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200955 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100956 """
957 try:
958 content = BaseTopic._remove_envelop(indata)
959
960 # Override descriptor with query string kwargs
961 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100962 content = self._validate_input_new(content, session["force"])
963 self.check_conflict_on_new(session, content)
964 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200965 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100966 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +0000967 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200968 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100969 except ValidationError as e:
970 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
971
K Sai Kirand010e3e2020-08-28 15:11:48 +0530972 def show(self, session, _id, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100973 """
974 Get complete information on an topic
975
tierno65ca36d2019-02-12 19:27:52 +0100976 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100977 :param _id: server internal id
K Sai Kirand010e3e2020-08-28 15:11:48 +0530978 :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 +0100979 :return: dictionary, raise exception if not found.
980 """
tiernocf042d32019-06-13 09:06:40 +0000981 # Allow _id to be a name or uuid
982 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +0200983 # projects = self.auth.get_project_list(filter_q=filter_q)
984 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100985 if len(projects) == 1:
986 return projects[0]
987 elif len(projects) > 1:
988 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
989 else:
990 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
991
tiernoc4e07d02020-08-14 14:25:32 +0000992 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100993 """
994 Get a list of the topic that matches a filter
995
tierno65ca36d2019-02-12 19:27:52 +0100996 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100997 :param filter_q: filter of data to be applied
998 :return: The list, it can be empty if no one match the filter.
999 """
delacruzramo029405d2019-09-26 10:52:56 +02001000 project_list = self.auth.get_project_list(filter_q)
1001 if not session["allow_show_user_project_role"]:
1002 # Bug 853 - Default filtering
1003 user = self.auth.get_user(session["username"])
1004 projects = [prm["project"] for prm in user["project_role_mappings"]]
1005 project_list = [proj for proj in project_list if proj["_id"] in projects]
1006 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001007
tiernobee3bad2019-12-05 12:26:01 +00001008 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001009 """
1010 Delete item by its internal _id
1011
tierno65ca36d2019-02-12 19:27:52 +01001012 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001013 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001014 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001015 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001016 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1017 """
tiernocf042d32019-06-13 09:06:40 +00001018 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001019 proj = self.auth.get_project(_id)
1020 pid = proj["_id"]
1021 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001022 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001023 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001024 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001025 return v
1026 return None
1027
tierno4015b472019-06-10 13:57:29 +00001028 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1029 """
1030 Updates a project entry.
1031
1032 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1033 :param _id:
1034 :param indata: data to be inserted
1035 :param kwargs: used to override the indata descriptor
1036 :param content:
1037 :return: _id: identity of the inserted data.
1038 """
1039 indata = self._remove_envelop(indata)
1040
1041 # Override descriptor with query string kwargs
1042 if kwargs:
1043 BaseTopic._update_input_with_kwargs(indata, kwargs)
1044 try:
tierno4015b472019-06-10 13:57:29 +00001045 if not content:
1046 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001047 indata = self._validate_input_edit(indata, content, force=session["force"])
tierno4015b472019-06-10 13:57:29 +00001048 self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001049 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001050 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001051 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001052 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001053 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1054 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001055 except ValidationError as e:
1056 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1057
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001058
1059class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001060 topic = "roles"
1061 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001062 schema_new = roles_new_schema
1063 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001064 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001065
tierno9e87a7f2020-03-23 09:24:10 +00001066 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001067 BaseTopic.__init__(self, db, fs, msg, auth)
1068 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001069 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001070 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001071
1072 @staticmethod
1073 def validate_role_definition(operations, role_definitions):
1074 """
1075 Validates the role definition against the operations defined in
1076 the resources to operations files.
1077
1078 :param operations: operations list
1079 :param role_definitions: role definition to test
1080 :return: None if ok, raises ValidationError exception on error
1081 """
tierno1f029d82019-06-13 22:37:04 +00001082 if not role_definitions.get("permissions"):
1083 return
1084 ignore_fields = ["admin", "default"]
1085 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001086 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001087 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001088 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001089 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001090
tierno97639b42020-08-04 12:48:15 +00001091 match = next((op for op in operations if op == role_def or op.startswith(role_def + ":")), None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001092
tierno97639b42020-08-04 12:48:15 +00001093 if not match:
tierno1f029d82019-06-13 22:37:04 +00001094 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001095
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001096 def _validate_input_new(self, input, force=False):
1097 """
1098 Validates input user content for a new entry.
1099
1100 :param input: user input content for the new topic
1101 :param force: may be used for being more tolerant
1102 :return: The same input content, or a changed version of it.
1103 """
1104 if self.schema_new:
1105 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001106 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001107
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001108 return input
1109
Frank Brydendeba68e2020-07-27 13:55:11 +00001110 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001111 """
1112 Validates input user content for updating an entry.
1113
1114 :param input: user input content for the new topic
1115 :param force: may be used for being more tolerant
1116 :return: The same input content, or a changed version of it.
1117 """
1118 if self.schema_edit:
1119 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001120 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001121
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001122 return input
1123
tierno65ca36d2019-02-12 19:27:52 +01001124 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001125 """
1126 Check that the data to be inserted is valid
1127
tierno65ca36d2019-02-12 19:27:52 +01001128 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001129 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001130 :return: None or raises EngineException
1131 """
delacruzramo79e40f42019-10-10 16:36:40 +02001132 # check name is not uuid
1133 role_name = indata.get("name")
1134 if is_valid_uuid(role_name):
1135 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1136 HTTPStatus.UNPROCESSABLE_ENTITY)
tierno1f029d82019-06-13 22:37:04 +00001137 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001138 name = indata["name"]
1139 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1140 if self.auth.get_role_list({"name": name}):
1141 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001142
tierno65ca36d2019-02-12 19:27:52 +01001143 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001144 """
1145 Check that the data to be edited/uploaded is valid
1146
tierno65ca36d2019-02-12 19:27:52 +01001147 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001148 :param final_content: data once modified
1149 :param edit_content: incremental data that contains the modifications to apply
1150 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001151 :return: None or raises EngineException
1152 """
tierno1f029d82019-06-13 22:37:04 +00001153 if "default" not in final_content["permissions"]:
1154 final_content["permissions"]["default"] = False
1155 if "admin" not in final_content["permissions"]:
1156 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001157
delacruzramo79e40f42019-10-10 16:36:40 +02001158 # check name is not uuid
1159 role_name = edit_content.get("name")
1160 if is_valid_uuid(role_name):
1161 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1162 HTTPStatus.UNPROCESSABLE_ENTITY)
1163
1164 # Check renaming of admin roles
1165 role = self.auth.get_role(_id)
1166 if role["name"] in ["system_admin", "project_admin"]:
1167 raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1168
tierno1f029d82019-06-13 22:37:04 +00001169 # check name not exists
1170 if "name" in edit_content:
1171 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001172 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1173 roles = self.auth.get_role_list({"name": role_name})
1174 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
tierno1f029d82019-06-13 22:37:04 +00001175 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001176
tiernob4844ab2019-05-23 08:42:12 +00001177 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001178 """
1179 Check if deletion can be done because of dependencies if it is not force. To override
1180
tierno65ca36d2019-02-12 19:27:52 +01001181 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001182 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001183 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001184 :return: None if ok or raises EngineException with the conflict
1185 """
delacruzramo01b15d32019-07-02 14:37:47 +02001186 role = self.auth.get_role(_id)
1187 if role["name"] in ["system_admin", "project_admin"]:
1188 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001189
delacruzramo01b15d32019-07-02 14:37:47 +02001190 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001191 if not session["force"]:
1192 for user in self.auth.get_user_list():
1193 for prm in user.get("project_role_mappings"):
1194 if prm["role"] == _id:
1195 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1196 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001197
1198 @staticmethod
delacruzramo01b15d32019-07-02 14:37:47 +02001199 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001200 """
1201 Modifies content descriptor to include _admin
1202
1203 :param content: descriptor to be modified
1204 :param project_id: if included, it add project read/write permissions
1205 :param make_public: if included it is generated as public for reading.
1206 :return: None, but content is modified
1207 """
1208 now = time()
1209 if "_admin" not in content:
1210 content["_admin"] = {}
1211 if not content["_admin"].get("created"):
1212 content["_admin"]["created"] = now
1213 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001214
tierno1f029d82019-06-13 22:37:04 +00001215 if "permissions" not in content:
1216 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001217
tierno1f029d82019-06-13 22:37:04 +00001218 if "default" not in content["permissions"]:
1219 content["permissions"]["default"] = False
1220 if "admin" not in content["permissions"]:
1221 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001222
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001223 @staticmethod
1224 def format_on_edit(final_content, edit_content):
1225 """
1226 Modifies final_content descriptor to include the modified date.
1227
1228 :param final_content: final descriptor generated
1229 :param edit_content: alterations to be include
1230 :return: None, but final_content is modified
1231 """
delacruzramo01b15d32019-07-02 14:37:47 +02001232 if "_admin" in final_content:
1233 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001234
tierno1f029d82019-06-13 22:37:04 +00001235 if "permissions" not in final_content:
1236 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001237
tierno1f029d82019-06-13 22:37:04 +00001238 if "default" not in final_content["permissions"]:
1239 final_content["permissions"]["default"] = False
1240 if "admin" not in final_content["permissions"]:
1241 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001242 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001243
K Sai Kirand010e3e2020-08-28 15:11:48 +05301244 def show(self, session, _id, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001245 """
1246 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001247
delacruzramo01b15d32019-07-02 14:37:47 +02001248 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1249 :param _id: server internal id
K Sai Kirand010e3e2020-08-28 15:11:48 +05301250 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001251 :return: dictionary, raise exception if not found.
1252 """
1253 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001254 # roles = self.auth.get_role_list(filter_q)
1255 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001256 if not roles:
1257 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1258 elif len(roles) > 1:
1259 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1260 return roles[0]
1261
tiernoc4e07d02020-08-14 14:25:32 +00001262 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001263 """
1264 Get a list of the topic that matches a filter
1265
1266 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1267 :param filter_q: filter of data to be applied
1268 :return: The list, it can be empty if no one match the filter.
1269 """
delacruzramo029405d2019-09-26 10:52:56 +02001270 role_list = self.auth.get_role_list(filter_q)
1271 if not session["allow_show_user_project_role"]:
1272 # Bug 853 - Default filtering
1273 user = self.auth.get_user(session["username"])
1274 roles = [prm["role"] for prm in user["project_role_mappings"]]
1275 role_list = [role for role in role_list if role["_id"] in roles]
1276 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001277
tierno65ca36d2019-02-12 19:27:52 +01001278 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001279 """
1280 Creates a new entry into database.
1281
1282 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001283 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001284 :param indata: data to be inserted
1285 :param kwargs: used to override the indata descriptor
1286 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001287 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001288 """
1289 try:
tierno1f029d82019-06-13 22:37:04 +00001290 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001291
1292 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001293 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001294 content = self._validate_input_new(content, session["force"])
1295 self.check_conflict_on_new(session, content)
1296 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001297 # role_name = content["name"]
1298 rid = self.auth.create_role(content)
1299 content["_id"] = rid
1300 # _id = self.db.create(self.topic, content)
1301 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001302 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001303 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001304 except ValidationError as e:
1305 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1306
tiernobee3bad2019-12-05 12:26:01 +00001307 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001308 """
1309 Delete item by its internal _id
1310
tierno65ca36d2019-02-12 19:27:52 +01001311 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001312 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001313 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001314 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001315 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1316 """
delacruzramo01b15d32019-07-02 14:37:47 +02001317 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1318 roles = self.auth.get_role_list(filter_q)
1319 if not roles:
1320 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1321 elif len(roles) > 1:
1322 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1323 rid = roles[0]["_id"]
1324 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001325 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001326 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001327 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001328 v = self.auth.delete_role(rid)
1329 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001330 return v
1331 return None
1332
tierno65ca36d2019-02-12 19:27:52 +01001333 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001334 """
1335 Updates a role entry.
1336
tierno65ca36d2019-02-12 19:27:52 +01001337 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001338 :param _id:
1339 :param indata: data to be inserted
1340 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001341 :param content:
1342 :return: _id: identity of the inserted data.
1343 """
delacruzramo01b15d32019-07-02 14:37:47 +02001344 if kwargs:
1345 self._update_input_with_kwargs(indata, kwargs)
1346 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001347 if not content:
1348 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001349 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001350 deep_update_rfc7396(content, indata)
1351 self.check_conflict_on_edit(session, content, indata, _id=_id)
1352 self.format_on_edit(content, indata)
1353 self.auth.update_role(content)
1354 except ValidationError as e:
1355 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)