blob: ca886dc0f11114336330311ba6582193781a3f17 [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
garciadeblas4568a372021-03-24 09:19:48 +010021from osm_nbi.validation import (
22 user_new_schema,
23 user_edit_schema,
24 project_new_schema,
25 project_edit_schema,
26 vim_account_new_schema,
27 vim_account_edit_schema,
28 sdn_new_schema,
29 sdn_edit_schema,
30 wim_account_new_schema,
31 wim_account_edit_schema,
32 roles_new_schema,
33 roles_edit_schema,
34 k8scluster_new_schema,
35 k8scluster_edit_schema,
36 k8srepo_new_schema,
37 k8srepo_edit_schema,
38 vca_new_schema,
39 vca_edit_schema,
40 osmrepo_new_schema,
41 osmrepo_edit_schema,
42 validate_input,
43 ValidationError,
44 is_valid_uuid,
45) # To check that User/Project Names don't look like UUIDs
tierno23acf402019-08-28 13:36:34 +000046from osm_nbi.base_topic import BaseTopic, EngineException
47from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020048from osm_common.dbbase import deep_update_rfc7396
agarwalat53471982020-10-08 13:06:14 +000049import copy
tiernob24258a2018-10-04 18:39:49 +020050
51__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
52
53
54class UserTopic(BaseTopic):
55 topic = "users"
56 topic_msg = "users"
57 schema_new = user_new_schema
58 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010059 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020060
delacruzramo32bab472019-09-13 12:24:22 +020061 def __init__(self, db, fs, msg, auth):
62 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020063
64 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010065 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020066 """
67 Generates a filter dictionary for querying database users.
68 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020070 :return:
71 """
72 if session["admin"]: # allows all
73 return {}
74 else:
75 return {"username": session["username"]}
76
tierno65ca36d2019-02-12 19:27:52 +010077 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020078 # check username not exists
garciadeblas4568a372021-03-24 09:19:48 +010079 if self.db.get_one(
80 self.topic,
81 {"username": indata.get("username")},
82 fail_on_empty=False,
83 fail_on_more=False,
84 ):
85 raise EngineException(
86 "username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT
87 )
tiernob24258a2018-10-04 18:39:49 +020088 # check projects
tierno65ca36d2019-02-12 19:27:52 +010089 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020090 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020091 # To allow project addressing by Name as well as ID
garciadeblas4568a372021-03-24 09:19:48 +010092 if not self.db.get_one(
93 "projects",
94 {BaseTopic.id_field("projects", p): p},
95 fail_on_empty=False,
96 fail_on_more=False,
97 ):
98 raise EngineException(
99 "project '{}' does not exist".format(p), HTTPStatus.CONFLICT
100 )
tiernob24258a2018-10-04 18:39:49 +0200101
tiernob4844ab2019-05-23 08:42:12 +0000102 def check_conflict_on_del(self, session, _id, db_content):
103 """
104 Check if deletion can be done because of dependencies if it is not force. To override
105 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
106 :param _id: internal _id
107 :param db_content: The database content of this item _id
108 :return: None if ok or raises EngineException with the conflict
109 """
tiernob24258a2018-10-04 18:39:49 +0200110 if _id == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100111 raise EngineException(
112 "You cannot delete your own user", http_code=HTTPStatus.CONFLICT
113 )
tiernob24258a2018-10-04 18:39:49 +0200114
115 @staticmethod
116 def format_on_new(content, project_id=None, make_public=False):
117 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +0200118 # Removed so that the UUID is kept, to allow User Name modification
119 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +0200120 salt = uuid4().hex
121 content["_admin"]["salt"] = salt
122 if content.get("password"):
garciadeblas4568a372021-03-24 09:19:48 +0100123 content["password"] = sha256(
124 content["password"].encode("utf-8") + salt.encode("utf-8")
125 ).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +0100126 if content.get("project_role_mappings"):
garciadeblas4568a372021-03-24 09:19:48 +0100127 projects = [
128 mapping["project"] for mapping in content["project_role_mappings"]
129 ]
Eduardo Sousa339ed782019-05-28 14:25:00 +0100130
131 if content.get("projects"):
132 content["projects"] += projects
133 else:
134 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +0200135
136 @staticmethod
137 def format_on_edit(final_content, edit_content):
138 BaseTopic.format_on_edit(final_content, edit_content)
139 if edit_content.get("password"):
140 salt = uuid4().hex
141 final_content["_admin"]["salt"] = salt
garciadeblas4568a372021-03-24 09:19:48 +0100142 final_content["password"] = sha256(
143 edit_content["password"].encode("utf-8") + salt.encode("utf-8")
144 ).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000145 return None
tiernob24258a2018-10-04 18:39:49 +0200146
tierno65ca36d2019-02-12 19:27:52 +0100147 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200148 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100149 raise EngineException(
150 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
151 )
delacruzramoc061f562019-04-05 11:00:02 +0200152 # Names that look like UUIDs are not allowed
153 name = (indata if indata else kwargs).get("username")
154 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100155 raise EngineException(
156 "Usernames that look like UUIDs are not allowed",
157 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
158 )
159 return BaseTopic.edit(
160 self, session, _id, indata=indata, kwargs=kwargs, content=content
161 )
tiernob24258a2018-10-04 18:39:49 +0200162
tierno65ca36d2019-02-12 19:27:52 +0100163 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200164 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100165 raise EngineException(
166 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
167 )
delacruzramoc061f562019-04-05 11:00:02 +0200168 # Names that look like UUIDs are not allowed
169 name = indata["username"] if indata else kwargs["username"]
170 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100171 raise EngineException(
172 "Usernames that look like UUIDs are not allowed",
173 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
174 )
175 return BaseTopic.new(
176 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
177 )
tiernob24258a2018-10-04 18:39:49 +0200178
179
180class ProjectTopic(BaseTopic):
181 topic = "projects"
182 topic_msg = "projects"
183 schema_new = project_new_schema
184 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100185 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200186
delacruzramo32bab472019-09-13 12:24:22 +0200187 def __init__(self, db, fs, msg, auth):
188 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200189
tierno65ca36d2019-02-12 19:27:52 +0100190 @staticmethod
191 def _get_project_filter(session):
192 """
193 Generates a filter dictionary for querying database users.
194 Current policy is admin can show all, non admin, only its own user.
195 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
196 :return:
197 """
198 if session["admin"]: # allows all
199 return {}
200 else:
201 return {"_id.cont": session["project_id"]}
202
203 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200204 if not indata.get("name"):
205 raise EngineException("missing 'name'")
206 # check name not exists
garciadeblas4568a372021-03-24 09:19:48 +0100207 if self.db.get_one(
208 self.topic,
209 {"name": indata.get("name")},
210 fail_on_empty=False,
211 fail_on_more=False,
212 ):
213 raise EngineException(
214 "name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT
215 )
tiernob24258a2018-10-04 18:39:49 +0200216
217 @staticmethod
218 def format_on_new(content, project_id=None, make_public=False):
219 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200220 # Removed so that the UUID is kept, to allow Project Name modification
221 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200222
tiernob4844ab2019-05-23 08:42:12 +0000223 def check_conflict_on_del(self, session, _id, db_content):
224 """
225 Check if deletion can be done because of dependencies if it is not force. To override
226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
227 :param _id: internal _id
228 :param db_content: The database content of this item _id
229 :return: None if ok or raises EngineException with the conflict
230 """
tierno65ca36d2019-02-12 19:27:52 +0100231 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100232 raise EngineException(
233 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
234 )
tierno65ca36d2019-02-12 19:27:52 +0100235 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200236 return
237 _filter = {"projects": _id}
238 if self.db.get_list("users", _filter):
garciadeblas4568a372021-03-24 09:19:48 +0100239 raise EngineException(
240 "There is some USER that contains this project",
241 http_code=HTTPStatus.CONFLICT,
242 )
tiernob24258a2018-10-04 18:39:49 +0200243
tierno65ca36d2019-02-12 19:27:52 +0100244 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200245 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100246 raise EngineException(
247 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
248 )
delacruzramoc061f562019-04-05 11:00:02 +0200249 # Names that look like UUIDs are not allowed
250 name = (indata if indata else kwargs).get("name")
251 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100252 raise EngineException(
253 "Project names that look like UUIDs are not allowed",
254 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
255 )
256 return BaseTopic.edit(
257 self, session, _id, indata=indata, kwargs=kwargs, content=content
258 )
tiernob24258a2018-10-04 18:39:49 +0200259
tierno65ca36d2019-02-12 19:27:52 +0100260 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200261 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100262 raise EngineException(
263 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
264 )
delacruzramoc061f562019-04-05 11:00:02 +0200265 # Names that look like UUIDs are not allowed
266 name = indata["name"] if indata else kwargs["name"]
267 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100268 raise EngineException(
269 "Project names that look like UUIDs are not allowed",
270 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
271 )
272 return BaseTopic.new(
273 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
274 )
tiernob24258a2018-10-04 18:39:49 +0200275
276
tiernobdebce92019-07-01 15:36:49 +0000277class CommonVimWimSdn(BaseTopic):
278 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
garciadeblas4568a372021-03-24 09:19:48 +0100279
280 config_to_encrypt = (
281 {}
282 ) # what keys at config must be encrypted because contains passwords
283 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200284
tiernobdebce92019-07-01 15:36:49 +0000285 @staticmethod
286 def _create_operation(op_type, params=None):
287 """
288 Creates a dictionary with the information to an operation, similar to ns-lcm-op
289 :param op_type: can be create, edit, delete
290 :param params: operation input parameters
291 :return: new dictionary with
292 """
293 now = time()
294 return {
295 "lcmOperationType": op_type,
296 "operationState": "PROCESSING",
297 "startTime": now,
298 "statusEnteredTime": now,
299 "detailed-status": "",
300 "operationParams": params,
301 }
tiernob24258a2018-10-04 18:39:49 +0200302
tierno65ca36d2019-02-12 19:27:52 +0100303 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000304 """
305 Check that the data to be inserted is valid. It is checked that name is unique
306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
307 :param indata: data to be inserted
308 :return: None or raises EngineException
309 """
tiernob24258a2018-10-04 18:39:49 +0200310 self.check_unique_name(session, indata["name"], _id=None)
311
tierno65ca36d2019-02-12 19:27:52 +0100312 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000313 """
314 Check that the data to be edited/uploaded is valid. It is checked that name is unique
315 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
316 :param final_content: data once modified. This method may change it.
317 :param edit_content: incremental data that contains the modifications to apply
318 :param _id: internal _id
319 :return: None or raises EngineException
320 """
tierno65ca36d2019-02-12 19:27:52 +0100321 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200322 self.check_unique_name(session, edit_content["name"], _id=_id)
323
bravofb995ea22021-02-10 10:57:52 -0300324 return final_content
325
tiernobdebce92019-07-01 15:36:49 +0000326 def format_on_edit(self, final_content, edit_content):
327 """
328 Modifies final_content inserting admin information upon edition
329 :param final_content: final content to be stored at database
330 :param edit_content: user requested update content
331 :return: operation id
332 """
delacruzramofe598fe2019-10-23 18:25:11 +0200333 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000334
tierno92c1c7d2018-11-12 15:22:37 +0100335 # encrypt passwords
336 schema_version = final_content.get("schema_version")
337 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000338 if edit_content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100339 final_content[self.password_to_encrypt] = self.db.encrypt(
340 edit_content[self.password_to_encrypt],
341 schema_version=schema_version,
342 salt=final_content["_id"],
343 )
344 config_to_encrypt_keys = self.config_to_encrypt.get(
345 schema_version
346 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000347 if edit_content.get("config") and config_to_encrypt_keys:
tierno468aa242019-08-01 16:35:04 +0000348 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100349 if edit_content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100350 final_content["config"][p] = self.db.encrypt(
351 edit_content["config"][p],
352 schema_version=schema_version,
353 salt=final_content["_id"],
354 )
tiernobdebce92019-07-01 15:36:49 +0000355
356 # create edit operation
357 final_content["_admin"]["operations"].append(self._create_operation("edit"))
garciadeblas4568a372021-03-24 09:19:48 +0100358 return "{}:{}".format(
359 final_content["_id"], len(final_content["_admin"]["operations"]) - 1
360 )
tierno92c1c7d2018-11-12 15:22:37 +0100361
362 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000363 """
364 Modifies content descriptor to include _admin and insert create operation
365 :param content: descriptor to be modified
366 :param project_id: if included, it add project read/write permissions. Can be None or a list
367 :param make_public: if included it is generated as public for reading.
368 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
369 """
370 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000371 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100372
373 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000374 if content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100375 content[self.password_to_encrypt] = self.db.encrypt(
376 content[self.password_to_encrypt],
377 schema_version=schema_version,
378 salt=content["_id"],
379 )
380 config_to_encrypt_keys = self.config_to_encrypt.get(
381 schema_version
382 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000383 if content.get("config") and config_to_encrypt_keys:
384 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100385 if content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100386 content["config"][p] = self.db.encrypt(
387 content["config"][p],
388 schema_version=schema_version,
389 salt=content["_id"],
390 )
tierno92c1c7d2018-11-12 15:22:37 +0100391
tiernob24258a2018-10-04 18:39:49 +0200392 content["_admin"]["operationalState"] = "PROCESSING"
393
tiernobdebce92019-07-01 15:36:49 +0000394 # create operation
395 content["_admin"]["operations"] = [self._create_operation("create")]
396 content["_admin"]["current_operation"] = None
vijay.rd1eaf982021-05-14 11:54:59 +0000397 # create Resource in Openstack based VIM
398 if content.get("vim_type"):
399 if content["vim_type"] == "openstack":
400 compute = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100401 "ram": {"total": None, "used": None},
402 "vcpus": {"total": None, "used": None},
403 "instances": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000404 }
405 storage = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100406 "volumes": {"total": None, "used": None},
407 "snapshots": {"total": None, "used": None},
408 "storage": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000409 }
410 network = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100411 "networks": {"total": None, "used": None},
412 "subnets": {"total": None, "used": None},
413 "floating_ips": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000414 }
garciadeblasf2af4a12023-01-24 16:56:54 +0100415 content["resources"] = {
416 "compute": compute,
417 "storage": storage,
418 "network": network,
419 }
vijay.rd1eaf982021-05-14 11:54:59 +0000420
tiernobdebce92019-07-01 15:36:49 +0000421 return "{}:0".format(content["_id"])
422
tiernobee3bad2019-12-05 12:26:01 +0000423 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200424 """
425 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100426 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200427 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200428 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000429 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000430 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200431 """
tiernobdebce92019-07-01 15:36:49 +0000432
433 filter_q = self._get_project_filter(session)
434 filter_q["_id"] = _id
435 db_content = self.db.get_one(self.topic, filter_q)
436
437 self.check_conflict_on_del(session, _id, db_content)
438 if dry_run:
439 return None
440
tiernof5f2e3f2020-03-23 14:42:10 +0000441 # remove reference from project_read if there are more projects referencing it. If it last one,
442 # do not remove reference, but order via kafka to delete it
selvi.ja5e05112023-04-28 11:00:21 +0000443 if session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100444 other_projects_referencing = next(
445 (
446 p
447 for p in db_content["_admin"]["projects_read"]
448 if p not in session["project_id"] and p != "ANY"
449 ),
450 None,
451 )
tiernobdebce92019-07-01 15:36:49 +0000452
tiernof5f2e3f2020-03-23 14:42:10 +0000453 # check if there are projects referencing it (apart from ANY, that means, public)....
454 if other_projects_referencing:
455 # remove references but not delete
garciadeblas4568a372021-03-24 09:19:48 +0100456 update_dict_pull = {
457 "_admin.projects_read": session["project_id"],
458 "_admin.projects_write": session["project_id"],
459 }
460 self.db.set_one(
461 self.topic, filter_q, update_dict=None, pull_list=update_dict_pull
462 )
tiernof5f2e3f2020-03-23 14:42:10 +0000463 return None
464 else:
garciadeblas4568a372021-03-24 09:19:48 +0100465 can_write = next(
466 (
467 p
468 for p in db_content["_admin"]["projects_write"]
469 if p == "ANY" or p in session["project_id"]
470 ),
471 None,
472 )
tiernof5f2e3f2020-03-23 14:42:10 +0000473 if not can_write:
garciadeblas4568a372021-03-24 09:19:48 +0100474 raise EngineException(
475 "You have not write permission to delete it",
476 http_code=HTTPStatus.UNAUTHORIZED,
477 )
tiernobdebce92019-07-01 15:36:49 +0000478
479 # It must be deleted
480 if session["force"]:
481 self.db.del_one(self.topic, {"_id": _id})
482 op_id = None
garciadeblas4568a372021-03-24 09:19:48 +0100483 self._send_msg(
484 "deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
485 )
tiernobdebce92019-07-01 15:36:49 +0000486 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000487 update_dict = {"_admin.to_delete": True}
garciadeblas4568a372021-03-24 09:19:48 +0100488 self.db.set_one(
489 self.topic,
490 {"_id": _id},
491 update_dict=update_dict,
492 push={"_admin.operations": self._create_operation("delete")},
493 )
tiernobdebce92019-07-01 15:36:49 +0000494 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
495 # so the -1 is not needed
garciadeblas4568a372021-03-24 09:19:48 +0100496 op_id = "{}:{}".format(
497 db_content["_id"], len(db_content["_admin"]["operations"])
498 )
499 self._send_msg(
500 "delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
501 )
tiernobdebce92019-07-01 15:36:49 +0000502 return op_id
tiernob24258a2018-10-04 18:39:49 +0200503
504
tiernobdebce92019-07-01 15:36:49 +0000505class VimAccountTopic(CommonVimWimSdn):
506 topic = "vim_accounts"
507 topic_msg = "vim_account"
508 schema_new = vim_account_new_schema
509 schema_edit = vim_account_edit_schema
510 multiproject = True
511 password_to_encrypt = "vim_password"
garciadeblas4568a372021-03-24 09:19:48 +0100512 config_to_encrypt = {
513 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
514 "default": (
515 "admin_password",
516 "nsx_password",
517 "vcenter_password",
518 "vrops_password",
519 ),
520 }
tiernobdebce92019-07-01 15:36:49 +0000521
delacruzramo35c998b2019-11-21 11:09:16 +0100522 def check_conflict_on_del(self, session, _id, db_content):
523 """
524 Check if deletion can be done because of dependencies if it is not force. To override
525 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
526 :param _id: internal _id
527 :param db_content: The database content of this item _id
528 :return: None if ok or raises EngineException with the conflict
529 """
530 if session["force"]:
531 return
532 # check if used by VNF
533 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
garciadeblas4568a372021-03-24 09:19:48 +0100534 raise EngineException(
535 "There is at least one VNF using this VIM account",
536 http_code=HTTPStatus.CONFLICT,
537 )
delacruzramo35c998b2019-11-21 11:09:16 +0100538 super().check_conflict_on_del(session, _id, db_content)
539
tiernobdebce92019-07-01 15:36:49 +0000540
541class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000542 topic = "wim_accounts"
543 topic_msg = "wim_account"
544 schema_new = wim_account_new_schema
545 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100546 multiproject = True
gifrerenom44f5ec12022-03-07 16:57:25 +0000547 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000548 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000549
550
tiernobdebce92019-07-01 15:36:49 +0000551class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200552 topic = "sdns"
553 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000554 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200555 schema_new = sdn_new_schema
556 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100557 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000558 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000559 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100560
tierno7adaeb02019-12-17 16:46:12 +0000561 def _obtain_url(self, input, create):
562 if input.get("ip") or input.get("port"):
garciadeblas4568a372021-03-24 09:19:48 +0100563 if not input.get("ip") or not input.get("port") or input.get("url"):
564 raise ValidationError(
565 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
566 )
567 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
tierno7adaeb02019-12-17 16:46:12 +0000568 del input["ip"]
569 del input["port"]
garciadeblas4568a372021-03-24 09:19:48 +0100570 elif create and not input.get("url"):
tierno7adaeb02019-12-17 16:46:12 +0000571 raise ValidationError("You must provide 'url'")
572 return input
573
574 def _validate_input_new(self, input, force=False):
575 input = super()._validate_input_new(input, force)
576 return self._obtain_url(input, True)
577
Frank Brydendeba68e2020-07-27 13:55:11 +0000578 def _validate_input_edit(self, input, content, force=False):
579 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000580 return self._obtain_url(input, False)
581
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100582
delacruzramofe598fe2019-10-23 18:25:11 +0200583class K8sClusterTopic(CommonVimWimSdn):
584 topic = "k8sclusters"
585 topic_msg = "k8scluster"
586 schema_new = k8scluster_new_schema
587 schema_edit = k8scluster_edit_schema
588 multiproject = True
589 password_to_encrypt = None
590 config_to_encrypt = {}
591
592 def format_on_new(self, content, project_id=None, make_public=False):
593 oid = super().format_on_new(content, project_id, make_public)
garciadeblas4568a372021-03-24 09:19:48 +0100594 self.db.encrypt_decrypt_fields(
595 content["credentials"],
596 "encrypt",
597 ["password", "secret"],
598 schema_version=content["schema_version"],
599 salt=content["_id"],
600 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000601 # Add Helm/Juju Repo lists
602 repos = {"helm-chart": [], "juju-bundle": []}
603 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100604 if proj != "ANY":
605 for repo in self.db.get_list(
606 "k8srepos", {"_admin.projects_read": proj}
607 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000608 if repo["_id"] not in repos[repo["type"]]:
609 repos[repo["type"]].append(repo["_id"])
610 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100611 content["_admin"][k.replace("-", "_") + "_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200612 return oid
613
614 def format_on_edit(self, final_content, edit_content):
615 if final_content.get("schema_version") and edit_content.get("credentials"):
garciadeblas4568a372021-03-24 09:19:48 +0100616 self.db.encrypt_decrypt_fields(
617 edit_content["credentials"],
618 "encrypt",
619 ["password", "secret"],
620 schema_version=final_content["schema_version"],
621 salt=final_content["_id"],
622 )
623 deep_update_rfc7396(
624 final_content["credentials"], edit_content["credentials"]
625 )
delacruzramofe598fe2019-10-23 18:25:11 +0200626 oid = super().format_on_edit(final_content, edit_content)
627 return oid
628
delacruzramoc2d5fc62020-02-05 11:50:21 +0000629 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
garciadeblas4568a372021-03-24 09:19:48 +0100630 final_content = super(CommonVimWimSdn, self).check_conflict_on_edit(
631 session, final_content, edit_content, _id
632 )
633 final_content = super().check_conflict_on_edit(
634 session, final_content, edit_content, _id
635 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000636 # Update Helm/Juju Repo lists
637 repos = {"helm-chart": [], "juju-bundle": []}
638 for proj in session.get("set_project", []):
garciadeblas4568a372021-03-24 09:19:48 +0100639 if proj != "ANY":
640 for repo in self.db.get_list(
641 "k8srepos", {"_admin.projects_read": proj}
642 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000643 if repo["_id"] not in repos[repo["type"]]:
644 repos[repo["type"]].append(repo["_id"])
645 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100646 rlist = k.replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000647 if rlist not in final_content["_admin"]:
648 final_content["_admin"][rlist] = []
649 final_content["_admin"][rlist] += repos[k]
bravofb995ea22021-02-10 10:57:52 -0300650 return final_content
delacruzramoc2d5fc62020-02-05 11:50:21 +0000651
tiernoe19707b2020-04-21 13:08:04 +0000652 def check_conflict_on_del(self, session, _id, db_content):
653 """
654 Check if deletion can be done because of dependencies if it is not force. To override
655 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
656 :param _id: internal _id
657 :param db_content: The database content of this item _id
658 :return: None if ok or raises EngineException with the conflict
659 """
660 if session["force"]:
661 return
662 # check if used by VNF
663 filter_q = {"kdur.k8s-cluster.id": _id}
664 if session["project_id"]:
665 filter_q["_admin.projects_read.cont"] = session["project_id"]
666 if self.db.get_list("vnfrs", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100667 raise EngineException(
668 "There is at least one VNF using this k8scluster",
669 http_code=HTTPStatus.CONFLICT,
670 )
tiernoe19707b2020-04-21 13:08:04 +0000671 super().check_conflict_on_del(session, _id, db_content)
672
delacruzramofe598fe2019-10-23 18:25:11 +0200673
David Garciaecb41322021-03-31 19:10:46 +0200674class VcaTopic(CommonVimWimSdn):
675 topic = "vca"
676 topic_msg = "vca"
677 schema_new = vca_new_schema
678 schema_edit = vca_edit_schema
679 multiproject = True
680 password_to_encrypt = None
681
682 def format_on_new(self, content, project_id=None, make_public=False):
683 oid = super().format_on_new(content, project_id, make_public)
684 content["schema_version"] = schema_version = "1.11"
685 for key in ["secret", "cacert"]:
686 content[key] = self.db.encrypt(
garciadeblas4568a372021-03-24 09:19:48 +0100687 content[key], schema_version=schema_version, salt=content["_id"]
David Garciaecb41322021-03-31 19:10:46 +0200688 )
689 return oid
690
691 def format_on_edit(self, final_content, edit_content):
692 oid = super().format_on_edit(final_content, edit_content)
693 schema_version = final_content.get("schema_version")
694 for key in ["secret", "cacert"]:
695 if key in edit_content:
696 final_content[key] = self.db.encrypt(
697 edit_content[key],
698 schema_version=schema_version,
garciadeblas4568a372021-03-24 09:19:48 +0100699 salt=final_content["_id"],
David Garciaecb41322021-03-31 19:10:46 +0200700 )
701 return oid
702
703 def check_conflict_on_del(self, session, _id, db_content):
704 """
705 Check if deletion can be done because of dependencies if it is not force. To override
706 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
707 :param _id: internal _id
708 :param db_content: The database content of this item _id
709 :return: None if ok or raises EngineException with the conflict
710 """
711 if session["force"]:
712 return
713 # check if used by VNF
714 filter_q = {"vca": _id}
715 if session["project_id"]:
716 filter_q["_admin.projects_read.cont"] = session["project_id"]
717 if self.db.get_list("vim_accounts", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100718 raise EngineException(
719 "There is at least one VIM account using this vca",
720 http_code=HTTPStatus.CONFLICT,
721 )
David Garciaecb41322021-03-31 19:10:46 +0200722 super().check_conflict_on_del(session, _id, db_content)
723
724
delacruzramofe598fe2019-10-23 18:25:11 +0200725class K8sRepoTopic(CommonVimWimSdn):
726 topic = "k8srepos"
727 topic_msg = "k8srepo"
728 schema_new = k8srepo_new_schema
729 schema_edit = k8srepo_edit_schema
730 multiproject = True
731 password_to_encrypt = None
732 config_to_encrypt = {}
733
delacruzramoc2d5fc62020-02-05 11:50:21 +0000734 def format_on_new(self, content, project_id=None, make_public=False):
735 oid = super().format_on_new(content, project_id, make_public)
736 # Update Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100737 repo_list = content["type"].replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000738 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100739 if proj != "ANY":
740 self.db.set_list(
741 "k8sclusters",
742 {
743 "_admin.projects_read": proj,
744 "_admin." + repo_list + ".ne": content["_id"],
745 },
746 {},
747 push={"_admin." + repo_list: content["_id"]},
748 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000749 return oid
750
751 def delete(self, session, _id, dry_run=False, not_send_msg=None):
752 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
753 oid = super().delete(session, _id, dry_run, not_send_msg)
754 if oid:
755 # Remove from Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100756 repo_list = type.replace("-", "_") + "_repos"
757 self.db.set_list(
758 "k8sclusters",
759 {"_admin." + repo_list: _id},
760 {},
761 pull={"_admin." + repo_list: _id},
762 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000763 return oid
764
delacruzramofe598fe2019-10-23 18:25:11 +0200765
Felipe Vicensb66b0412020-05-06 10:11:00 +0200766class OsmRepoTopic(BaseTopic):
767 topic = "osmrepos"
768 topic_msg = "osmrepos"
769 schema_new = osmrepo_new_schema
770 schema_edit = osmrepo_edit_schema
771 multiproject = True
772 # TODO: Implement user/password
773
774
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100775class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100776 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000777 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100778 schema_new = user_new_schema
779 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100780
781 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200782 UserTopic.__init__(self, db, fs, msg, auth)
783 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100784
tierno65ca36d2019-02-12 19:27:52 +0100785 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100786 """
787 Check that the data to be inserted is valid
788
tierno65ca36d2019-02-12 19:27:52 +0100789 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100790 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100791 :return: None or raises EngineException
792 """
793 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000794 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100795 raise EngineException(
796 "username '{}' cannot have a uuid format".format(username),
797 HTTPStatus.UNPROCESSABLE_ENTITY,
798 )
tiernocf042d32019-06-13 09:06:40 +0000799
800 # Check that username is not used, regardless keystone already checks this
801 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100802 raise EngineException(
803 "username '{}' is already used".format(username), HTTPStatus.CONFLICT
804 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100805
Eduardo Sousa339ed782019-05-28 14:25:00 +0100806 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000807 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200808 role = self.auth.get_role_list({"name": "project_admin"})
809 if not role:
810 role = self.auth.get_role_list()
811 if not role:
garciadeblas4568a372021-03-24 09:19:48 +0100812 raise AuthconnNotFoundException(
813 "Can't find default role for user '{}'".format(username)
814 )
delacruzramo01b15d32019-07-02 14:37:47 +0200815 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000816 if not indata.get("project_role_mappings"):
817 indata["project_role_mappings"] = []
818 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200819 pid = self.auth.get_project(project)["_id"]
820 prm = {"project": pid, "role": rid}
821 if prm not in indata["project_role_mappings"]:
822 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000823 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
824 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100825
tierno65ca36d2019-02-12 19:27:52 +0100826 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100827 """
828 Check that the data to be edited/uploaded is valid
829
tierno65ca36d2019-02-12 19:27:52 +0100830 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100831 :param final_content: data once modified
832 :param edit_content: incremental data that contains the modifications to apply
833 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100834 :return: None or raises EngineException
835 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100836
tiernocf042d32019-06-13 09:06:40 +0000837 if "username" in edit_content:
838 username = edit_content.get("username")
839 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100840 raise EngineException(
841 "username '{}' cannot have an uuid format".format(username),
842 HTTPStatus.UNPROCESSABLE_ENTITY,
843 )
tiernocf042d32019-06-13 09:06:40 +0000844
845 # Check that username is not used, regardless keystone already checks this
846 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100847 raise EngineException(
848 "username '{}' is already used".format(username),
849 HTTPStatus.CONFLICT,
850 )
tiernocf042d32019-06-13 09:06:40 +0000851
852 if final_content["username"] == "admin":
853 for mapping in edit_content.get("remove_project_role_mappings", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100854 if mapping["project"] == "admin" and mapping.get("role") in (
855 None,
856 "system_admin",
857 ):
tiernocf042d32019-06-13 09:06:40 +0000858 # TODO make this also available for project id and role id
garciadeblas4568a372021-03-24 09:19:48 +0100859 raise EngineException(
860 "You cannot remove system_admin role from admin user",
861 http_code=HTTPStatus.FORBIDDEN,
862 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100863
bravofb995ea22021-02-10 10:57:52 -0300864 return final_content
865
tiernob4844ab2019-05-23 08:42:12 +0000866 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100867 """
868 Check if deletion can be done because of dependencies if it is not force. To override
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 _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000871 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100872 :return: None if ok or raises EngineException with the conflict
873 """
tiernocf042d32019-06-13 09:06:40 +0000874 if db_content["username"] == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100875 raise EngineException(
876 "You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT
877 )
delacruzramo01b15d32019-07-02 14:37:47 +0200878 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100879
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100880 @staticmethod
881 def format_on_show(content):
882 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100883 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100884 metadata from the role definition.
885 """
886 project_role_mappings = []
887
delacruzramo01b15d32019-07-02 14:37:47 +0200888 if "projects" in content:
889 for project in content["projects"]:
890 for role in project["roles"]:
garciadeblas4568a372021-03-24 09:19:48 +0100891 project_role_mappings.append(
892 {
893 "project": project["_id"],
894 "project_name": project["name"],
895 "role": role["_id"],
896 "role_name": role["name"],
897 }
898 )
delacruzramo01b15d32019-07-02 14:37:47 +0200899 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100900 content["project_role_mappings"] = project_role_mappings
901
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100902 return content
903
tierno65ca36d2019-02-12 19:27:52 +0100904 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100905 """
906 Creates a new entry into the authentication backend.
907
908 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
909
910 :param rollback: list to append created items at database in case a rollback may to be done
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 indata: data to be inserted
913 :param kwargs: used to override the indata descriptor
914 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200915 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100916 """
917 try:
918 content = BaseTopic._remove_envelop(indata)
919
920 # Override descriptor with query string kwargs
921 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100922 content = self._validate_input_new(content, session["force"])
923 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000924 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200925 now = time()
926 content["_admin"] = {"created": now, "modified": now}
927 prms = []
928 for prm in content.get("project_role_mappings", []):
929 proj = self.auth.get_project(prm["project"], not session["force"])
930 role = self.auth.get_role(prm["role"], not session["force"])
931 pid = proj["_id"] if proj else None
932 rid = role["_id"] if role else None
933 prl = {"project": pid, "role": rid}
934 if prl not in prms:
935 prms.append(prl)
936 content["project_role_mappings"] = prms
937 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
938 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100939
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100940 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000941 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +0000942 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200943 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100944 except ValidationError as e:
945 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
946
K Sai Kiran57589552021-01-27 21:38:34 +0530947 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100948 """
949 Get complete information on an topic
950
tierno65ca36d2019-02-12 19:27:52 +0100951 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +0000952 :param _id: server internal id or username
K Sai Kiran57589552021-01-27 21:38:34 +0530953 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +0530954 :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 +0100955 :return: dictionary, raise exception if not found.
956 """
tiernocf042d32019-06-13 09:06:40 +0000957 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000958 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200959 # users = self.auth.get_user_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +0100960 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100961 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000962 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100963 elif len(users) > 1:
garciadeblas4568a372021-03-24 09:19:48 +0100964 raise EngineException(
965 "Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT
966 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100967 else:
garciadeblas4568a372021-03-24 09:19:48 +0100968 raise EngineException(
969 "User '{}' not found".format(_id), HTTPStatus.NOT_FOUND
970 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100971
tierno65ca36d2019-02-12 19:27:52 +0100972 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100973 """
974 Updates an user entry.
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:
978 :param indata: data to be inserted
979 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100980 :param content:
981 :return: _id: identity of the inserted data.
982 """
983 indata = self._remove_envelop(indata)
984
985 # Override descriptor with query string kwargs
986 if kwargs:
987 BaseTopic._update_input_with_kwargs(indata, kwargs)
988 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100989 if not content:
990 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +0000991 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -0300992 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000993 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100994
garciadeblas4568a372021-03-24 09:19:48 +0100995 if not (
996 "password" in indata
997 or "username" in indata
998 or indata.get("remove_project_role_mappings")
999 or indata.get("add_project_role_mappings")
1000 or indata.get("project_role_mappings")
1001 or indata.get("projects")
1002 or indata.get("add_projects")
garciadeblas6d83f8f2023-06-19 22:34:49 +02001003 or indata.get("unlock")
1004 or indata.get("renew")
garciadeblas4568a372021-03-24 09:19:48 +01001005 ):
tiernocf042d32019-06-13 09:06:40 +00001006 return _id
garciadeblas4568a372021-03-24 09:19:48 +01001007 if indata.get("project_role_mappings") and (
1008 indata.get("remove_project_role_mappings")
1009 or indata.get("add_project_role_mappings")
1010 ):
1011 raise EngineException(
1012 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1013 "' or 'remove_project_role_mappings'",
1014 http_code=HTTPStatus.BAD_REQUEST,
1015 )
Eduardo Sousa44603902019-06-04 08:10:32 +01001016
delacruzramo01b15d32019-07-02 14:37:47 +02001017 if indata.get("projects") or indata.get("add_projects"):
1018 role = self.auth.get_role_list({"name": "project_admin"})
1019 if not role:
1020 role = self.auth.get_role_list()
1021 if not role:
garciadeblas4568a372021-03-24 09:19:48 +01001022 raise AuthconnNotFoundException(
1023 "Can't find a default role for user '{}'".format(
1024 content["username"]
1025 )
1026 )
delacruzramo01b15d32019-07-02 14:37:47 +02001027 rid = role[0]["_id"]
1028 if "add_project_role_mappings" not in indata:
1029 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +00001030 if "remove_project_role_mappings" not in indata:
1031 indata["remove_project_role_mappings"] = []
1032 if isinstance(indata.get("projects"), dict):
1033 # backward compatible
1034 for k, v in indata["projects"].items():
1035 if k.startswith("$") and v is None:
garciadeblas4568a372021-03-24 09:19:48 +01001036 indata["remove_project_role_mappings"].append(
1037 {"project": k[1:]}
1038 )
tierno1546f2a2019-08-20 15:38:11 +00001039 elif k.startswith("$+"):
garciadeblas4568a372021-03-24 09:19:48 +01001040 indata["add_project_role_mappings"].append(
1041 {"project": v, "role": rid}
1042 )
tierno1546f2a2019-08-20 15:38:11 +00001043 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +02001044 for proj in indata.get("projects", []) + indata.get("add_projects", []):
garciadeblas4568a372021-03-24 09:19:48 +01001045 indata["add_project_role_mappings"].append(
1046 {"project": proj, "role": rid}
1047 )
Adurti8d046062024-05-07 06:04:37 +00001048 if (
1049 indata.get("remove_project_role_mappings")
1050 or indata.get("add_project_role_mappings")
1051 or indata.get("project_role_mappings")
1052 ):
1053 user_details = self.db.get_one("users", {"_id": session.get("user_id")})
1054 edit_role = False
1055 for pr in user_details["project_role_mappings"]:
1056 role_id = pr.get("role")
1057 role_details = self.db.get_one("roles", {"_id": role_id})
1058 if role_details["permissions"].get("default"):
1059 if "roles" not in role_details["permissions"] or role_details[
1060 "permissions"
1061 ].get("roles"):
1062 edit_role = True
1063 elif role_details["permissions"].get("roles"):
1064 edit_role = True
1065 if not edit_role:
1066 raise EngineException(
1067 "User {} has no privileges to edit or delete project-role mappings".format(
1068 session.get("username")
1069 ),
1070 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1071 )
delacruzramo01b15d32019-07-02 14:37:47 +02001072
Adurti0b3e0782024-03-25 10:58:29 +00001073 # check before deleting project-role
1074 delete_session_project = False
1075 if indata.get("remove_project_role_mappings"):
1076 for pr in indata["remove_project_role_mappings"]:
1077 project_name = pr.get("project")
1078 project_details = self.db.get_one(
1079 "projects", {"_id": session.get("project_id")[0]}
1080 )
1081 if project_details["name"] == project_name:
1082 delete_session_project = True
1083
37177ba1e0632024-11-01 08:55:59 +00001084 # password change
1085 if indata.get("password"):
1086 if not session.get("admin_show"):
1087 if not indata.get("system_admin_id"):
1088 if _id != session["user_id"]:
1089 raise EngineException(
1090 "You are not allowed to change other users password",
1091 http_code=HTTPStatus.BAD_REQUEST,
1092 )
1093 if not indata.get("old_password"):
1094 raise EngineException(
1095 "Password change requires old password or admin ID",
1096 http_code=HTTPStatus.BAD_REQUEST,
1097 )
1098
delacruzramo01b15d32019-07-02 14:37:47 +02001099 # user = self.show(session, _id) # Already in 'content'
1100 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +01001101
tiernocf042d32019-06-13 09:06:40 +00001102 mappings_to_add = []
1103 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +01001104
tiernocf042d32019-06-13 09:06:40 +00001105 # remove
1106 for to_remove in indata.get("remove_project_role_mappings", ()):
1107 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001108 if to_remove["project"] in (
1109 mapping["project"],
1110 mapping["project_name"],
1111 ):
1112 if not to_remove.get("role") or to_remove["role"] in (
1113 mapping["role"],
1114 mapping["role_name"],
1115 ):
tiernocf042d32019-06-13 09:06:40 +00001116 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +01001117
tiernocf042d32019-06-13 09:06:40 +00001118 # add
1119 for to_add in indata.get("add_project_role_mappings", ()):
1120 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001121 if to_add["project"] in (
1122 mapping["project"],
1123 mapping["project_name"],
1124 ) and to_add["role"] in (
1125 mapping["role"],
1126 mapping["role_name"],
1127 ):
garciadeblas4568a372021-03-24 09:19:48 +01001128 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001129 mappings_to_remove.remove(mapping)
1130 break # do not add, it is already at user
1131 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001132 pid = self.auth.get_project(to_add["project"])["_id"]
1133 rid = self.auth.get_role(to_add["role"])["_id"]
1134 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001135
1136 # set
1137 if indata.get("project_role_mappings"):
Adurtiee5dbd12024-03-25 08:21:36 +00001138 duplicates = []
1139 for pr in indata.get("project_role_mappings"):
1140 if pr not in duplicates:
1141 duplicates.append(pr)
1142 if len(indata.get("project_role_mappings")) > len(duplicates):
1143 raise EngineException(
1144 "Project-role combination should not be repeated",
1145 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1146 )
tiernocf042d32019-06-13 09:06:40 +00001147 for to_set in indata["project_role_mappings"]:
1148 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001149 if to_set["project"] in (
1150 mapping["project"],
1151 mapping["project_name"],
1152 ) and to_set["role"] in (
1153 mapping["role"],
1154 mapping["role_name"],
1155 ):
1156 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001157 mappings_to_remove.remove(mapping)
1158 break # do not add, it is already at user
1159 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001160 pid = self.auth.get_project(to_set["project"])["_id"]
1161 rid = self.auth.get_role(to_set["role"])["_id"]
1162 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001163 for mapping in original_mapping:
1164 for to_set in indata["project_role_mappings"]:
garciadeblas4568a372021-03-24 09:19:48 +01001165 if to_set["project"] in (
1166 mapping["project"],
1167 mapping["project_name"],
1168 ) and to_set["role"] in (
1169 mapping["role"],
1170 mapping["role_name"],
1171 ):
tiernocf042d32019-06-13 09:06:40 +00001172 break
1173 else:
1174 # delete
garciadeblas4568a372021-03-24 09:19:48 +01001175 if mapping not in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001176 mappings_to_remove.append(mapping)
1177
garciadeblas4568a372021-03-24 09:19:48 +01001178 self.auth.update_user(
1179 {
1180 "_id": _id,
1181 "username": indata.get("username"),
1182 "password": indata.get("password"),
selvi.ja9a1fc82022-04-04 06:54:30 +00001183 "old_password": indata.get("old_password"),
garciadeblas4568a372021-03-24 09:19:48 +01001184 "add_project_role_mappings": mappings_to_add,
1185 "remove_project_role_mappings": mappings_to_remove,
garciadeblas6d83f8f2023-06-19 22:34:49 +02001186 "system_admin_id": indata.get("system_admin_id"),
1187 "unlock": indata.get("unlock"),
1188 "renew": indata.get("renew"),
Adurti0b3e0782024-03-25 10:58:29 +00001189 "remove_session_project": delete_session_project,
garciadeblas4568a372021-03-24 09:19:48 +01001190 }
1191 )
1192 data_to_send = {"_id": _id, "changes": indata}
agarwalat53471982020-10-08 13:06:14 +00001193 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +00001194
delacruzramo01b15d32019-07-02 14:37:47 +02001195 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001196 except ValidationError as e:
1197 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1198
tiernoc4e07d02020-08-14 14:25:32 +00001199 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001200 """
1201 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +01001202 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001203 :param filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +05301204 :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 +01001205 :return: The list, it can be empty if no one match the filter.
1206 """
delacruzramo029405d2019-09-26 10:52:56 +02001207 user_list = self.auth.get_user_list(filter_q)
1208 if not session["allow_show_user_project_role"]:
1209 # Bug 853 - Default filtering
garciadeblas4568a372021-03-24 09:19:48 +01001210 user_list = [
1211 usr for usr in user_list if usr["username"] == session["username"]
1212 ]
delacruzramo029405d2019-09-26 10:52:56 +02001213 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001214
tiernobee3bad2019-12-05 12:26:01 +00001215 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001216 """
1217 Delete item by its internal _id
1218
tierno65ca36d2019-02-12 19:27:52 +01001219 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001220 :param _id: server internal id
1221 :param force: indicates if deletion must be forced in case of conflict
1222 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001223 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001224 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1225 """
tiernocf042d32019-06-13 09:06:40 +00001226 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001227 user = self.auth.get_user(_id)
1228 uid = user["_id"]
1229 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001230 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001231 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +00001232 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001233 return v
1234 return None
1235
1236
1237class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +01001238 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +00001239 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +01001240 schema_new = project_new_schema
1241 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001242
1243 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001244 ProjectTopic.__init__(self, db, fs, msg, auth)
1245 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001246
tierno65ca36d2019-02-12 19:27:52 +01001247 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001248 """
1249 Check that the data to be inserted is valid
1250
tierno65ca36d2019-02-12 19:27:52 +01001251 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001252 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001253 :return: None or raises EngineException
1254 """
tiernocf042d32019-06-13 09:06:40 +00001255 project_name = indata.get("name")
1256 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001257 raise EngineException(
1258 "project name '{}' cannot have an uuid format".format(project_name),
1259 HTTPStatus.UNPROCESSABLE_ENTITY,
1260 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001261
tiernocf042d32019-06-13 09:06:40 +00001262 project_list = self.auth.get_project_list(filter_q={"name": project_name})
1263
1264 if project_list:
garciadeblas4568a372021-03-24 09:19:48 +01001265 raise EngineException(
1266 "project '{}' exists".format(project_name), HTTPStatus.CONFLICT
1267 )
tiernocf042d32019-06-13 09:06:40 +00001268
1269 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1270 """
1271 Check that the data to be edited/uploaded is valid
1272
1273 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1274 :param final_content: data once modified
1275 :param edit_content: incremental data that contains the modifications to apply
1276 :param _id: internal _id
1277 :return: None or raises EngineException
1278 """
1279
1280 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +02001281 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +00001282 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001283 raise EngineException(
1284 "project name '{}' cannot have an uuid format".format(project_name),
1285 HTTPStatus.UNPROCESSABLE_ENTITY,
1286 )
tiernocf042d32019-06-13 09:06:40 +00001287
delacruzramo01b15d32019-07-02 14:37:47 +02001288 if final_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001289 raise EngineException(
1290 "You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT
1291 )
delacruzramo01b15d32019-07-02 14:37:47 +02001292
tiernocf042d32019-06-13 09:06:40 +00001293 # Check that project name is not used, regardless keystone already checks this
garciadeblas4568a372021-03-24 09:19:48 +01001294 if project_name and self.auth.get_project_list(
1295 filter_q={"name": project_name}
1296 ):
1297 raise EngineException(
1298 "project '{}' is already used".format(project_name),
1299 HTTPStatus.CONFLICT,
1300 )
bravofb995ea22021-02-10 10:57:52 -03001301 return final_content
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001302
tiernob4844ab2019-05-23 08:42:12 +00001303 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001304 """
1305 Check if deletion can be done because of dependencies if it is not force. To override
1306
tierno65ca36d2019-02-12 19:27:52 +01001307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001308 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001309 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001310 :return: None if ok or raises EngineException with the conflict
1311 """
delacruzramo01b15d32019-07-02 14:37:47 +02001312
1313 def check_rw_projects(topic, title, id_field):
1314 for desc in self.db.get_list(topic):
garciadeblas4568a372021-03-24 09:19:48 +01001315 if (
1316 _id
1317 in desc["_admin"]["projects_read"]
1318 + desc["_admin"]["projects_write"]
1319 ):
1320 raise EngineException(
1321 "Project '{}' ({}) is being used by {} '{}'".format(
1322 db_content["name"], _id, title, desc[id_field]
1323 ),
1324 HTTPStatus.CONFLICT,
1325 )
delacruzramo01b15d32019-07-02 14:37:47 +02001326
1327 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +01001328 raise EngineException(
1329 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
1330 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001331
delacruzramo01b15d32019-07-02 14:37:47 +02001332 if db_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001333 raise EngineException(
1334 "You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT
1335 )
delacruzramo01b15d32019-07-02 14:37:47 +02001336
1337 # If any user is using this project, raise CONFLICT exception
1338 if not session["force"]:
1339 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001340 for prm in user.get("project_role_mappings"):
1341 if prm["project"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001342 raise EngineException(
1343 "Project '{}' ({}) is being used by user '{}'".format(
1344 db_content["name"], _id, user["username"]
1345 ),
1346 HTTPStatus.CONFLICT,
1347 )
delacruzramo01b15d32019-07-02 14:37:47 +02001348
1349 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1350 if not session["force"]:
1351 check_rw_projects("vnfds", "VNF Descriptor", "id")
1352 check_rw_projects("nsds", "NS Descriptor", "id")
1353 check_rw_projects("nsts", "NS Template", "id")
1354 check_rw_projects("pdus", "PDU Descriptor", "name")
1355
tierno65ca36d2019-02-12 19:27:52 +01001356 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001357 """
1358 Creates a new entry into the authentication backend.
1359
1360 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1361
1362 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001363 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001364 :param indata: data to be inserted
1365 :param kwargs: used to override the indata descriptor
1366 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001367 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001368 """
1369 try:
1370 content = BaseTopic._remove_envelop(indata)
1371
1372 # Override descriptor with query string kwargs
1373 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001374 content = self._validate_input_new(content, session["force"])
1375 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001376 self.format_on_new(
1377 content, project_id=session["project_id"], make_public=session["public"]
1378 )
delacruzramo01b15d32019-07-02 14:37:47 +02001379 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001380 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +00001381 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001382 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001383 except ValidationError as e:
1384 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1385
K Sai Kiran57589552021-01-27 21:38:34 +05301386 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001387 """
1388 Get complete information on an topic
1389
tierno65ca36d2019-02-12 19:27:52 +01001390 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001391 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301392 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301393 :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 +01001394 :return: dictionary, raise exception if not found.
1395 """
tiernocf042d32019-06-13 09:06:40 +00001396 # Allow _id to be a name or uuid
1397 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001398 # projects = self.auth.get_project_list(filter_q=filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001399 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001400 if len(projects) == 1:
1401 return projects[0]
1402 elif len(projects) > 1:
1403 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
1404 else:
1405 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
1406
tiernoc4e07d02020-08-14 14:25:32 +00001407 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001408 """
1409 Get a list of the topic that matches a filter
1410
tierno65ca36d2019-02-12 19:27:52 +01001411 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001412 :param filter_q: filter of data to be applied
1413 :return: The list, it can be empty if no one match the filter.
1414 """
delacruzramo029405d2019-09-26 10:52:56 +02001415 project_list = self.auth.get_project_list(filter_q)
1416 if not session["allow_show_user_project_role"]:
1417 # Bug 853 - Default filtering
1418 user = self.auth.get_user(session["username"])
1419 projects = [prm["project"] for prm in user["project_role_mappings"]]
1420 project_list = [proj for proj in project_list if proj["_id"] in projects]
1421 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001422
tiernobee3bad2019-12-05 12:26:01 +00001423 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001424 """
1425 Delete item by its internal _id
1426
tierno65ca36d2019-02-12 19:27:52 +01001427 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001428 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001429 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001430 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001431 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1432 """
tiernocf042d32019-06-13 09:06:40 +00001433 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001434 proj = self.auth.get_project(_id)
1435 pid = proj["_id"]
1436 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001437 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001438 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001439 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001440 return v
1441 return None
1442
tierno4015b472019-06-10 13:57:29 +00001443 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1444 """
1445 Updates a project entry.
1446
1447 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1448 :param _id:
1449 :param indata: data to be inserted
1450 :param kwargs: used to override the indata descriptor
1451 :param content:
1452 :return: _id: identity of the inserted data.
1453 """
1454 indata = self._remove_envelop(indata)
1455
1456 # Override descriptor with query string kwargs
1457 if kwargs:
1458 BaseTopic._update_input_with_kwargs(indata, kwargs)
1459 try:
tierno4015b472019-06-10 13:57:29 +00001460 if not content:
1461 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001462 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001463 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001464 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001465 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001466 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001467 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001468 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1469 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001470 except ValidationError as e:
1471 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1472
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001473
1474class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001475 topic = "roles"
garciadeblas4568a372021-03-24 09:19:48 +01001476 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001477 schema_new = roles_new_schema
1478 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001479 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001480
tierno9e87a7f2020-03-23 09:24:10 +00001481 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001482 BaseTopic.__init__(self, db, fs, msg, auth)
1483 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001484 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001485 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001486
1487 @staticmethod
1488 def validate_role_definition(operations, role_definitions):
1489 """
1490 Validates the role definition against the operations defined in
1491 the resources to operations files.
1492
1493 :param operations: operations list
1494 :param role_definitions: role definition to test
1495 :return: None if ok, raises ValidationError exception on error
1496 """
tierno1f029d82019-06-13 22:37:04 +00001497 if not role_definitions.get("permissions"):
1498 return
1499 ignore_fields = ["admin", "default"]
1500 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001501 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001502 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001503 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001504 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001505
garciadeblas4568a372021-03-24 09:19:48 +01001506 match = next(
1507 (
1508 op
1509 for op in operations
1510 if op == role_def or op.startswith(role_def + ":")
1511 ),
1512 None,
1513 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001514
tierno97639b42020-08-04 12:48:15 +00001515 if not match:
tierno1f029d82019-06-13 22:37:04 +00001516 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001517
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001518 def _validate_input_new(self, input, force=False):
1519 """
1520 Validates input user content for a new entry.
1521
1522 :param input: user input content for the new topic
1523 :param force: may be used for being more tolerant
1524 :return: The same input content, or a changed version of it.
1525 """
1526 if self.schema_new:
1527 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001528 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001529
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001530 return input
1531
Frank Brydendeba68e2020-07-27 13:55:11 +00001532 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001533 """
1534 Validates input user content for updating an entry.
1535
1536 :param input: user input content for the new topic
1537 :param force: may be used for being more tolerant
1538 :return: The same input content, or a changed version of it.
1539 """
1540 if self.schema_edit:
1541 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001542 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001543
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001544 return input
1545
tierno65ca36d2019-02-12 19:27:52 +01001546 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001547 """
1548 Check that the data to be inserted is valid
1549
tierno65ca36d2019-02-12 19:27:52 +01001550 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001551 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001552 :return: None or raises EngineException
1553 """
delacruzramo79e40f42019-10-10 16:36:40 +02001554 # check name is not uuid
1555 role_name = indata.get("name")
1556 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001557 raise EngineException(
1558 "role name '{}' cannot have an uuid format".format(role_name),
1559 HTTPStatus.UNPROCESSABLE_ENTITY,
1560 )
tierno1f029d82019-06-13 22:37:04 +00001561 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001562 name = indata["name"]
1563 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1564 if self.auth.get_role_list({"name": name}):
garciadeblas4568a372021-03-24 09:19:48 +01001565 raise EngineException(
1566 "role name '{}' exists".format(name), HTTPStatus.CONFLICT
1567 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001568
tierno65ca36d2019-02-12 19:27:52 +01001569 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001570 """
1571 Check that the data to be edited/uploaded is valid
1572
tierno65ca36d2019-02-12 19:27:52 +01001573 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001574 :param final_content: data once modified
1575 :param edit_content: incremental data that contains the modifications to apply
1576 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001577 :return: None or raises EngineException
1578 """
tierno1f029d82019-06-13 22:37:04 +00001579 if "default" not in final_content["permissions"]:
1580 final_content["permissions"]["default"] = False
1581 if "admin" not in final_content["permissions"]:
1582 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001583
delacruzramo79e40f42019-10-10 16:36:40 +02001584 # check name is not uuid
1585 role_name = edit_content.get("name")
1586 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001587 raise EngineException(
1588 "role name '{}' cannot have an uuid format".format(role_name),
1589 HTTPStatus.UNPROCESSABLE_ENTITY,
1590 )
delacruzramo79e40f42019-10-10 16:36:40 +02001591
1592 # Check renaming of admin roles
1593 role = self.auth.get_role(_id)
1594 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001595 raise EngineException(
1596 "You cannot rename role '{}'".format(role["name"]),
1597 http_code=HTTPStatus.FORBIDDEN,
1598 )
delacruzramo79e40f42019-10-10 16:36:40 +02001599
tierno1f029d82019-06-13 22:37:04 +00001600 # check name not exists
1601 if "name" in edit_content:
1602 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001603 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1604 roles = self.auth.get_role_list({"name": role_name})
1605 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
garciadeblas4568a372021-03-24 09:19:48 +01001606 raise EngineException(
1607 "role name '{}' exists".format(role_name), HTTPStatus.CONFLICT
1608 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001609
bravofb995ea22021-02-10 10:57:52 -03001610 return final_content
1611
tiernob4844ab2019-05-23 08:42:12 +00001612 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001613 """
1614 Check if deletion can be done because of dependencies if it is not force. To override
1615
tierno65ca36d2019-02-12 19:27:52 +01001616 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001617 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001618 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001619 :return: None if ok or raises EngineException with the conflict
1620 """
delacruzramo01b15d32019-07-02 14:37:47 +02001621 role = self.auth.get_role(_id)
1622 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001623 raise EngineException(
1624 "You cannot delete role '{}'".format(role["name"]),
1625 http_code=HTTPStatus.FORBIDDEN,
1626 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001627
delacruzramo01b15d32019-07-02 14:37:47 +02001628 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001629 if not session["force"]:
1630 for user in self.auth.get_user_list():
1631 for prm in user.get("project_role_mappings"):
1632 if prm["role"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001633 raise EngineException(
1634 "Role '{}' ({}) is being used by user '{}'".format(
1635 role["name"], _id, user["username"]
1636 ),
1637 HTTPStatus.CONFLICT,
1638 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001639
1640 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +01001641 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001642 """
1643 Modifies content descriptor to include _admin
1644
1645 :param content: descriptor to be modified
1646 :param project_id: if included, it add project read/write permissions
1647 :param make_public: if included it is generated as public for reading.
1648 :return: None, but content is modified
1649 """
1650 now = time()
1651 if "_admin" not in content:
1652 content["_admin"] = {}
1653 if not content["_admin"].get("created"):
1654 content["_admin"]["created"] = now
1655 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001656
tierno1f029d82019-06-13 22:37:04 +00001657 if "permissions" not in content:
1658 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001659
tierno1f029d82019-06-13 22:37:04 +00001660 if "default" not in content["permissions"]:
1661 content["permissions"]["default"] = False
1662 if "admin" not in content["permissions"]:
1663 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001664
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001665 @staticmethod
1666 def format_on_edit(final_content, edit_content):
1667 """
1668 Modifies final_content descriptor to include the modified date.
1669
1670 :param final_content: final descriptor generated
1671 :param edit_content: alterations to be include
1672 :return: None, but final_content is modified
1673 """
delacruzramo01b15d32019-07-02 14:37:47 +02001674 if "_admin" in final_content:
1675 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001676
tierno1f029d82019-06-13 22:37:04 +00001677 if "permissions" not in final_content:
1678 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001679
tierno1f029d82019-06-13 22:37:04 +00001680 if "default" not in final_content["permissions"]:
1681 final_content["permissions"]["default"] = False
1682 if "admin" not in final_content["permissions"]:
1683 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001684 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001685
K Sai Kiran57589552021-01-27 21:38:34 +05301686 def show(self, session, _id, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001687 """
1688 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001689
delacruzramo01b15d32019-07-02 14:37:47 +02001690 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1691 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301692 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301693 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001694 :return: dictionary, raise exception if not found.
1695 """
1696 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001697 # roles = self.auth.get_role_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001698 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001699 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001700 raise AuthconnNotFoundException(
1701 "Not found any role with filter {}".format(filter_q)
1702 )
delacruzramo01b15d32019-07-02 14:37:47 +02001703 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001704 raise AuthconnConflictException(
1705 "Found more than one role with filter {}".format(filter_q)
1706 )
delacruzramo01b15d32019-07-02 14:37:47 +02001707 return roles[0]
1708
tiernoc4e07d02020-08-14 14:25:32 +00001709 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001710 """
1711 Get a list of the topic that matches a filter
1712
1713 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1714 :param filter_q: filter of data to be applied
1715 :return: The list, it can be empty if no one match the filter.
1716 """
delacruzramo029405d2019-09-26 10:52:56 +02001717 role_list = self.auth.get_role_list(filter_q)
1718 if not session["allow_show_user_project_role"]:
1719 # Bug 853 - Default filtering
1720 user = self.auth.get_user(session["username"])
1721 roles = [prm["role"] for prm in user["project_role_mappings"]]
1722 role_list = [role for role in role_list if role["_id"] in roles]
1723 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001724
tierno65ca36d2019-02-12 19:27:52 +01001725 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001726 """
1727 Creates a new entry into database.
1728
1729 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001730 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001731 :param indata: data to be inserted
1732 :param kwargs: used to override the indata descriptor
1733 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001734 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001735 """
1736 try:
tierno1f029d82019-06-13 22:37:04 +00001737 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001738
1739 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001740 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001741 content = self._validate_input_new(content, session["force"])
1742 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001743 self.format_on_new(
1744 content, project_id=session["project_id"], make_public=session["public"]
1745 )
delacruzramo01b15d32019-07-02 14:37:47 +02001746 # role_name = content["name"]
1747 rid = self.auth.create_role(content)
1748 content["_id"] = rid
1749 # _id = self.db.create(self.topic, content)
1750 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001751 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001752 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001753 except ValidationError as e:
1754 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1755
tiernobee3bad2019-12-05 12:26:01 +00001756 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001757 """
1758 Delete item by its internal _id
1759
tierno65ca36d2019-02-12 19:27:52 +01001760 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001761 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001762 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001763 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001764 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1765 """
delacruzramo01b15d32019-07-02 14:37:47 +02001766 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1767 roles = self.auth.get_role_list(filter_q)
1768 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001769 raise AuthconnNotFoundException(
1770 "Not found any role with filter {}".format(filter_q)
1771 )
delacruzramo01b15d32019-07-02 14:37:47 +02001772 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001773 raise AuthconnConflictException(
1774 "Found more than one role with filter {}".format(filter_q)
1775 )
delacruzramo01b15d32019-07-02 14:37:47 +02001776 rid = roles[0]["_id"]
1777 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001778 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001779 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001780 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001781 v = self.auth.delete_role(rid)
1782 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001783 return v
1784 return None
1785
tierno65ca36d2019-02-12 19:27:52 +01001786 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001787 """
1788 Updates a role entry.
1789
tierno65ca36d2019-02-12 19:27:52 +01001790 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001791 :param _id:
1792 :param indata: data to be inserted
1793 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001794 :param content:
1795 :return: _id: identity of the inserted data.
1796 """
delacruzramo01b15d32019-07-02 14:37:47 +02001797 if kwargs:
1798 self._update_input_with_kwargs(indata, kwargs)
1799 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001800 if not content:
1801 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001802 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001803 deep_update_rfc7396(content, indata)
bravofb995ea22021-02-10 10:57:52 -03001804 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001805 self.format_on_edit(content, indata)
1806 self.auth.update_role(content)
1807 except ValidationError as e:
1808 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)