blob: f70c4972a46248606b176cf899c329b1ca9a7a86 [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
Patricia Reinoso62fa6732023-02-22 17:57:53 +000050from osm_nbi.temporal.nbi_temporal import NbiTemporal
tiernob24258a2018-10-04 18:39:49 +020051
52__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
53
54
55class UserTopic(BaseTopic):
56 topic = "users"
57 topic_msg = "users"
58 schema_new = user_new_schema
59 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010060 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020061
delacruzramo32bab472019-09-13 12:24:22 +020062 def __init__(self, db, fs, msg, auth):
63 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020064
65 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010066 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020067 """
68 Generates a filter dictionary for querying database users.
69 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010070 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020071 :return:
72 """
73 if session["admin"]: # allows all
74 return {}
75 else:
76 return {"username": session["username"]}
77
tierno65ca36d2019-02-12 19:27:52 +010078 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020079 # check username not exists
garciadeblas4568a372021-03-24 09:19:48 +010080 if self.db.get_one(
81 self.topic,
82 {"username": indata.get("username")},
83 fail_on_empty=False,
84 fail_on_more=False,
85 ):
86 raise EngineException(
87 "username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT
88 )
tiernob24258a2018-10-04 18:39:49 +020089 # check projects
tierno65ca36d2019-02-12 19:27:52 +010090 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020091 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020092 # To allow project addressing by Name as well as ID
garciadeblas4568a372021-03-24 09:19:48 +010093 if not self.db.get_one(
94 "projects",
95 {BaseTopic.id_field("projects", p): p},
96 fail_on_empty=False,
97 fail_on_more=False,
98 ):
99 raise EngineException(
100 "project '{}' does not exist".format(p), HTTPStatus.CONFLICT
101 )
tiernob24258a2018-10-04 18:39:49 +0200102
tiernob4844ab2019-05-23 08:42:12 +0000103 def check_conflict_on_del(self, session, _id, db_content):
104 """
105 Check if deletion can be done because of dependencies if it is not force. To override
106 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
107 :param _id: internal _id
108 :param db_content: The database content of this item _id
109 :return: None if ok or raises EngineException with the conflict
110 """
tiernob24258a2018-10-04 18:39:49 +0200111 if _id == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100112 raise EngineException(
113 "You cannot delete your own user", http_code=HTTPStatus.CONFLICT
114 )
tiernob24258a2018-10-04 18:39:49 +0200115
116 @staticmethod
117 def format_on_new(content, project_id=None, make_public=False):
118 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +0200119 # Removed so that the UUID is kept, to allow User Name modification
120 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +0200121 salt = uuid4().hex
122 content["_admin"]["salt"] = salt
123 if content.get("password"):
garciadeblas4568a372021-03-24 09:19:48 +0100124 content["password"] = sha256(
125 content["password"].encode("utf-8") + salt.encode("utf-8")
126 ).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +0100127 if content.get("project_role_mappings"):
garciadeblas4568a372021-03-24 09:19:48 +0100128 projects = [
129 mapping["project"] for mapping in content["project_role_mappings"]
130 ]
Eduardo Sousa339ed782019-05-28 14:25:00 +0100131
132 if content.get("projects"):
133 content["projects"] += projects
134 else:
135 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +0200136
137 @staticmethod
138 def format_on_edit(final_content, edit_content):
139 BaseTopic.format_on_edit(final_content, edit_content)
140 if edit_content.get("password"):
141 salt = uuid4().hex
142 final_content["_admin"]["salt"] = salt
garciadeblas4568a372021-03-24 09:19:48 +0100143 final_content["password"] = sha256(
144 edit_content["password"].encode("utf-8") + salt.encode("utf-8")
145 ).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000146 return None
tiernob24258a2018-10-04 18:39:49 +0200147
tierno65ca36d2019-02-12 19:27:52 +0100148 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200149 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100150 raise EngineException(
151 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
152 )
delacruzramoc061f562019-04-05 11:00:02 +0200153 # Names that look like UUIDs are not allowed
154 name = (indata if indata else kwargs).get("username")
155 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100156 raise EngineException(
157 "Usernames that look like UUIDs are not allowed",
158 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
159 )
160 return BaseTopic.edit(
161 self, session, _id, indata=indata, kwargs=kwargs, content=content
162 )
tiernob24258a2018-10-04 18:39:49 +0200163
tierno65ca36d2019-02-12 19:27:52 +0100164 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200165 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100166 raise EngineException(
167 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
168 )
delacruzramoc061f562019-04-05 11:00:02 +0200169 # Names that look like UUIDs are not allowed
170 name = indata["username"] if indata else kwargs["username"]
171 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100172 raise EngineException(
173 "Usernames that look like UUIDs are not allowed",
174 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
175 )
176 return BaseTopic.new(
177 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
178 )
tiernob24258a2018-10-04 18:39:49 +0200179
180
181class ProjectTopic(BaseTopic):
182 topic = "projects"
183 topic_msg = "projects"
184 schema_new = project_new_schema
185 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100186 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200187
delacruzramo32bab472019-09-13 12:24:22 +0200188 def __init__(self, db, fs, msg, auth):
189 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200190
tierno65ca36d2019-02-12 19:27:52 +0100191 @staticmethod
192 def _get_project_filter(session):
193 """
194 Generates a filter dictionary for querying database users.
195 Current policy is admin can show all, non admin, only its own user.
196 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
197 :return:
198 """
199 if session["admin"]: # allows all
200 return {}
201 else:
202 return {"_id.cont": session["project_id"]}
203
204 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200205 if not indata.get("name"):
206 raise EngineException("missing 'name'")
207 # check name not exists
garciadeblas4568a372021-03-24 09:19:48 +0100208 if self.db.get_one(
209 self.topic,
210 {"name": indata.get("name")},
211 fail_on_empty=False,
212 fail_on_more=False,
213 ):
214 raise EngineException(
215 "name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT
216 )
tiernob24258a2018-10-04 18:39:49 +0200217
218 @staticmethod
219 def format_on_new(content, project_id=None, make_public=False):
220 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200221 # Removed so that the UUID is kept, to allow Project Name modification
222 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200223
tiernob4844ab2019-05-23 08:42:12 +0000224 def check_conflict_on_del(self, session, _id, db_content):
225 """
226 Check if deletion can be done because of dependencies if it is not force. To override
227 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
228 :param _id: internal _id
229 :param db_content: The database content of this item _id
230 :return: None if ok or raises EngineException with the conflict
231 """
tierno65ca36d2019-02-12 19:27:52 +0100232 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100233 raise EngineException(
234 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
235 )
tierno65ca36d2019-02-12 19:27:52 +0100236 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200237 return
238 _filter = {"projects": _id}
239 if self.db.get_list("users", _filter):
garciadeblas4568a372021-03-24 09:19:48 +0100240 raise EngineException(
241 "There is some USER that contains this project",
242 http_code=HTTPStatus.CONFLICT,
243 )
tiernob24258a2018-10-04 18:39:49 +0200244
tierno65ca36d2019-02-12 19:27:52 +0100245 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200246 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100247 raise EngineException(
248 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
249 )
delacruzramoc061f562019-04-05 11:00:02 +0200250 # Names that look like UUIDs are not allowed
251 name = (indata if indata else kwargs).get("name")
252 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100253 raise EngineException(
254 "Project names that look like UUIDs are not allowed",
255 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
256 )
257 return BaseTopic.edit(
258 self, session, _id, indata=indata, kwargs=kwargs, content=content
259 )
tiernob24258a2018-10-04 18:39:49 +0200260
tierno65ca36d2019-02-12 19:27:52 +0100261 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200262 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100263 raise EngineException(
264 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
265 )
delacruzramoc061f562019-04-05 11:00:02 +0200266 # Names that look like UUIDs are not allowed
267 name = indata["name"] if indata else kwargs["name"]
268 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100269 raise EngineException(
270 "Project names that look like UUIDs are not allowed",
271 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
272 )
273 return BaseTopic.new(
274 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
275 )
tiernob24258a2018-10-04 18:39:49 +0200276
277
tiernobdebce92019-07-01 15:36:49 +0000278class CommonVimWimSdn(BaseTopic):
279 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
garciadeblas4568a372021-03-24 09:19:48 +0100280
281 config_to_encrypt = (
282 {}
283 ) # what keys at config must be encrypted because contains passwords
284 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200285
tiernobdebce92019-07-01 15:36:49 +0000286 @staticmethod
287 def _create_operation(op_type, params=None):
288 """
289 Creates a dictionary with the information to an operation, similar to ns-lcm-op
290 :param op_type: can be create, edit, delete
291 :param params: operation input parameters
292 :return: new dictionary with
293 """
294 now = time()
295 return {
296 "lcmOperationType": op_type,
297 "operationState": "PROCESSING",
298 "startTime": now,
299 "statusEnteredTime": now,
300 "detailed-status": "",
301 "operationParams": params,
302 }
tiernob24258a2018-10-04 18:39:49 +0200303
tierno65ca36d2019-02-12 19:27:52 +0100304 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000305 """
306 Check that the data to be inserted is valid. It is checked that name is unique
307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
308 :param indata: data to be inserted
309 :return: None or raises EngineException
310 """
tiernob24258a2018-10-04 18:39:49 +0200311 self.check_unique_name(session, indata["name"], _id=None)
312
tierno65ca36d2019-02-12 19:27:52 +0100313 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000314 """
315 Check that the data to be edited/uploaded is valid. It is checked that name is unique
316 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
317 :param final_content: data once modified. This method may change it.
318 :param edit_content: incremental data that contains the modifications to apply
319 :param _id: internal _id
320 :return: None or raises EngineException
321 """
tierno65ca36d2019-02-12 19:27:52 +0100322 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200323 self.check_unique_name(session, edit_content["name"], _id=_id)
324
bravofb995ea22021-02-10 10:57:52 -0300325 return final_content
326
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000327 def _validate_input_edit(self, input, content, force=False):
328 """
329 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
330 :param input: user input content for the new topic
331 :param force: may be used for being more tolerant
332 :return: The same input content, or a changed version of it.
333 """
334
335 if "vim_type" in content:
336 input["vim_type"] = content["vim_type"]
337 return super()._validate_input_edit(input, content, force)
338
tiernobdebce92019-07-01 15:36:49 +0000339 def format_on_edit(self, final_content, edit_content):
340 """
341 Modifies final_content inserting admin information upon edition
342 :param final_content: final content to be stored at database
343 :param edit_content: user requested update content
344 :return: operation id
345 """
delacruzramofe598fe2019-10-23 18:25:11 +0200346 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000347
tierno92c1c7d2018-11-12 15:22:37 +0100348 # encrypt passwords
349 schema_version = final_content.get("schema_version")
350 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000351 if edit_content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100352 final_content[self.password_to_encrypt] = self.db.encrypt(
353 edit_content[self.password_to_encrypt],
354 schema_version=schema_version,
355 salt=final_content["_id"],
356 )
357 config_to_encrypt_keys = self.config_to_encrypt.get(
358 schema_version
359 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000360 if edit_content.get("config") and config_to_encrypt_keys:
tierno468aa242019-08-01 16:35:04 +0000361 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100362 if edit_content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100363 final_content["config"][p] = self.db.encrypt(
364 edit_content["config"][p],
365 schema_version=schema_version,
366 salt=final_content["_id"],
367 )
tiernobdebce92019-07-01 15:36:49 +0000368
369 # create edit operation
370 final_content["_admin"]["operations"].append(self._create_operation("edit"))
garciadeblas4568a372021-03-24 09:19:48 +0100371 return "{}:{}".format(
372 final_content["_id"], len(final_content["_admin"]["operations"]) - 1
373 )
tierno92c1c7d2018-11-12 15:22:37 +0100374
375 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000376 """
377 Modifies content descriptor to include _admin and insert create operation
378 :param content: descriptor to be modified
379 :param project_id: if included, it add project read/write permissions. Can be None or a list
380 :param make_public: if included it is generated as public for reading.
381 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
382 """
383 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000384 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100385
Mark Beierlc528d882023-01-06 12:56:16 -0500386 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000387 if content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100388 content[self.password_to_encrypt] = self.db.encrypt(
389 content[self.password_to_encrypt],
390 schema_version=schema_version,
391 salt=content["_id"],
392 )
393 config_to_encrypt_keys = self.config_to_encrypt.get(
394 schema_version
395 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000396 if content.get("config") and config_to_encrypt_keys:
397 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100398 if content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100399 content["config"][p] = self.db.encrypt(
400 content["config"][p],
401 schema_version=schema_version,
402 salt=content["_id"],
403 )
tierno92c1c7d2018-11-12 15:22:37 +0100404
Mark Beierlc528d882023-01-06 12:56:16 -0500405 content["_admin"]["operationalState"] = "PROCESSING"
406
tiernobdebce92019-07-01 15:36:49 +0000407 # create operation
408 content["_admin"]["operations"] = [self._create_operation("create")]
409 content["_admin"]["current_operation"] = None
vijay.rd1eaf982021-05-14 11:54:59 +0000410 # create Resource in Openstack based VIM
411 if content.get("vim_type"):
412 if content["vim_type"] == "openstack":
413 compute = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100414 "ram": {"total": None, "used": None},
415 "vcpus": {"total": None, "used": None},
416 "instances": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000417 }
418 storage = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100419 "volumes": {"total": None, "used": None},
420 "snapshots": {"total": None, "used": None},
421 "storage": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000422 }
423 network = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100424 "networks": {"total": None, "used": None},
425 "subnets": {"total": None, "used": None},
426 "floating_ips": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000427 }
garciadeblasf2af4a12023-01-24 16:56:54 +0100428 content["resources"] = {
429 "compute": compute,
430 "storage": storage,
431 "network": network,
432 }
Mark Beierlc528d882023-01-06 12:56:16 -0500433
434 return "{}:0".format(content["_id"])
tiernobdebce92019-07-01 15:36:49 +0000435
tiernobee3bad2019-12-05 12:26:01 +0000436 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200437 """
438 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100439 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200440 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200441 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000442 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000443 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200444 """
tiernobdebce92019-07-01 15:36:49 +0000445
446 filter_q = self._get_project_filter(session)
447 filter_q["_id"] = _id
448 db_content = self.db.get_one(self.topic, filter_q)
449
450 self.check_conflict_on_del(session, _id, db_content)
451 if dry_run:
452 return None
453
tiernof5f2e3f2020-03-23 14:42:10 +0000454 # remove reference from project_read if there are more projects referencing it. If it last one,
455 # do not remove reference, but order via kafka to delete it
456 if session["project_id"] and session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100457 other_projects_referencing = next(
458 (
459 p
460 for p in db_content["_admin"]["projects_read"]
461 if p not in session["project_id"] and p != "ANY"
462 ),
463 None,
464 )
tiernobdebce92019-07-01 15:36:49 +0000465
tiernof5f2e3f2020-03-23 14:42:10 +0000466 # check if there are projects referencing it (apart from ANY, that means, public)....
467 if other_projects_referencing:
468 # remove references but not delete
garciadeblas4568a372021-03-24 09:19:48 +0100469 update_dict_pull = {
470 "_admin.projects_read": session["project_id"],
471 "_admin.projects_write": session["project_id"],
472 }
473 self.db.set_one(
474 self.topic, filter_q, update_dict=None, pull_list=update_dict_pull
475 )
tiernof5f2e3f2020-03-23 14:42:10 +0000476 return None
477 else:
garciadeblas4568a372021-03-24 09:19:48 +0100478 can_write = next(
479 (
480 p
481 for p in db_content["_admin"]["projects_write"]
482 if p == "ANY" or p in session["project_id"]
483 ),
484 None,
485 )
tiernof5f2e3f2020-03-23 14:42:10 +0000486 if not can_write:
garciadeblas4568a372021-03-24 09:19:48 +0100487 raise EngineException(
488 "You have not write permission to delete it",
489 http_code=HTTPStatus.UNAUTHORIZED,
490 )
tiernobdebce92019-07-01 15:36:49 +0000491
492 # It must be deleted
493 if session["force"]:
494 self.db.del_one(self.topic, {"_id": _id})
495 op_id = None
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000496 message = {"_id": _id, "op_id": op_id}
497 # The vim_type is a temporary hack to shim in temporal workflows in the create
498 if "vim_type" in db_content:
499 message["vim_type"] = db_content["vim_type"]
500
garciadeblas4568a372021-03-24 09:19:48 +0100501 self._send_msg(
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000502 "deleted",
503 message,
504 not_send_msg=not_send_msg,
garciadeblas4568a372021-03-24 09:19:48 +0100505 )
tiernobdebce92019-07-01 15:36:49 +0000506 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000507 update_dict = {"_admin.to_delete": True}
garciadeblas4568a372021-03-24 09:19:48 +0100508 self.db.set_one(
509 self.topic,
510 {"_id": _id},
511 update_dict=update_dict,
512 push={"_admin.operations": self._create_operation("delete")},
513 )
tiernobdebce92019-07-01 15:36:49 +0000514 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
515 # so the -1 is not needed
garciadeblas4568a372021-03-24 09:19:48 +0100516 op_id = "{}:{}".format(
517 db_content["_id"], len(db_content["_admin"]["operations"])
518 )
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000519 message = {"_id": _id, "op_id": op_id}
520 # The vim_type is a temporary hack to shim in temporal workflows in the create
521 if "vim_type" in db_content:
522 message["vim_type"] = db_content["vim_type"]
523
garciadeblas4568a372021-03-24 09:19:48 +0100524 self._send_msg(
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000525 "delete",
526 message,
527 not_send_msg=not_send_msg,
garciadeblas4568a372021-03-24 09:19:48 +0100528 )
tiernobdebce92019-07-01 15:36:49 +0000529 return op_id
tiernob24258a2018-10-04 18:39:49 +0200530
531
tiernobdebce92019-07-01 15:36:49 +0000532class VimAccountTopic(CommonVimWimSdn):
533 topic = "vim_accounts"
534 topic_msg = "vim_account"
535 schema_new = vim_account_new_schema
536 schema_edit = vim_account_edit_schema
537 multiproject = True
538 password_to_encrypt = "vim_password"
garciadeblas4568a372021-03-24 09:19:48 +0100539 config_to_encrypt = {
540 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
541 "default": (
542 "admin_password",
543 "nsx_password",
544 "vcenter_password",
545 "vrops_password",
546 ),
547 }
Patricia Reinosoa04d59b2023-02-02 15:00:40 +0000548 valid_paas_providers = ["juju"]
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000549 temporal = NbiTemporal()
Patricia Reinosoa04d59b2023-02-02 15:00:40 +0000550
551 def check_conflict_on_new(self, session, indata):
552 super().check_conflict_on_new(session, indata)
553 self._check_paas_account(indata)
554
555 def _is_paas_vim_type(self, indata):
556 return indata.get("vim_type") and indata["vim_type"] == "paas"
557
558 def _check_paas_account(self, indata):
Patricia Reinosoc85d3af2023-03-23 09:27:08 +0000559 if not self._is_paas_vim_type(indata):
560 return
561 if not self._is_valid_paas_config(indata.get("config")):
562 raise EngineException(
563 "Invalid config for VIM account '{}'.".format(indata["name"]),
564 HTTPStatus.UNPROCESSABLE_ENTITY,
565 )
Patricia Reinosoa04d59b2023-02-02 15:00:40 +0000566
Patricia Reinosoc85d3af2023-03-23 09:27:08 +0000567 def _is_valid_paas_config(self, config) -> bool:
568 if not config:
569 return False
570 paas_provider = config.get("paas_provider")
571 is_valid_paas_provider = paas_provider in self.valid_paas_providers
572 if paas_provider == "juju":
573 return self._is_valid_juju_paas_config(config)
574 return is_valid_paas_provider
575
576 def _is_valid_juju_paas_config(self, config) -> bool:
577 if not config:
578 return False
579 config_keys = [
580 "paas_provider",
581 "ca_cert_content",
582 "cloud",
583 "cloud_credentials",
584 "authorized_keys",
585 ]
586 return all(key in config for key in config_keys)
tiernobdebce92019-07-01 15:36:49 +0000587
delacruzramo35c998b2019-11-21 11:09:16 +0100588 def check_conflict_on_del(self, session, _id, db_content):
589 """
590 Check if deletion can be done because of dependencies if it is not force. To override
591 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
592 :param _id: internal _id
593 :param db_content: The database content of this item _id
594 :return: None if ok or raises EngineException with the conflict
595 """
596 if session["force"]:
597 return
598 # check if used by VNF
599 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
garciadeblas4568a372021-03-24 09:19:48 +0100600 raise EngineException(
601 "There is at least one VNF using this VIM account",
602 http_code=HTTPStatus.CONFLICT,
603 )
delacruzramo35c998b2019-11-21 11:09:16 +0100604 super().check_conflict_on_del(session, _id, db_content)
605
Patricia Reinosoa04d59b2023-02-02 15:00:40 +0000606 def _send_msg(self, action, content, not_send_msg=None):
607 if self._is_paas_vim_type(content):
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000608 self.temporal.start_vim_workflow(action, content)
Patricia Reinosoa04d59b2023-02-02 15:00:40 +0000609 return
Patricia Reinoso62fa6732023-02-22 17:57:53 +0000610
Patricia Reinosoa04d59b2023-02-02 15:00:40 +0000611 super()._send_msg(action, content, not_send_msg)
612
tiernobdebce92019-07-01 15:36:49 +0000613
614class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000615 topic = "wim_accounts"
616 topic_msg = "wim_account"
617 schema_new = wim_account_new_schema
618 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100619 multiproject = True
gifrerenom44f5ec12022-03-07 16:57:25 +0000620 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000621 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000622
623
tiernobdebce92019-07-01 15:36:49 +0000624class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200625 topic = "sdns"
626 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000627 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200628 schema_new = sdn_new_schema
629 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100630 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000631 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000632 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100633
tierno7adaeb02019-12-17 16:46:12 +0000634 def _obtain_url(self, input, create):
635 if input.get("ip") or input.get("port"):
garciadeblas4568a372021-03-24 09:19:48 +0100636 if not input.get("ip") or not input.get("port") or input.get("url"):
637 raise ValidationError(
638 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
639 )
640 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
tierno7adaeb02019-12-17 16:46:12 +0000641 del input["ip"]
642 del input["port"]
garciadeblas4568a372021-03-24 09:19:48 +0100643 elif create and not input.get("url"):
tierno7adaeb02019-12-17 16:46:12 +0000644 raise ValidationError("You must provide 'url'")
645 return input
646
647 def _validate_input_new(self, input, force=False):
648 input = super()._validate_input_new(input, force)
649 return self._obtain_url(input, True)
650
Frank Brydendeba68e2020-07-27 13:55:11 +0000651 def _validate_input_edit(self, input, content, force=False):
652 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000653 return self._obtain_url(input, False)
654
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100655
delacruzramofe598fe2019-10-23 18:25:11 +0200656class K8sClusterTopic(CommonVimWimSdn):
657 topic = "k8sclusters"
658 topic_msg = "k8scluster"
659 schema_new = k8scluster_new_schema
660 schema_edit = k8scluster_edit_schema
661 multiproject = True
662 password_to_encrypt = None
663 config_to_encrypt = {}
664
665 def format_on_new(self, content, project_id=None, make_public=False):
666 oid = super().format_on_new(content, project_id, make_public)
garciadeblas4568a372021-03-24 09:19:48 +0100667 self.db.encrypt_decrypt_fields(
668 content["credentials"],
669 "encrypt",
670 ["password", "secret"],
671 schema_version=content["schema_version"],
672 salt=content["_id"],
673 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000674 # Add Helm/Juju Repo lists
675 repos = {"helm-chart": [], "juju-bundle": []}
676 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100677 if proj != "ANY":
678 for repo in self.db.get_list(
679 "k8srepos", {"_admin.projects_read": proj}
680 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000681 if repo["_id"] not in repos[repo["type"]]:
682 repos[repo["type"]].append(repo["_id"])
683 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100684 content["_admin"][k.replace("-", "_") + "_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200685 return oid
686
687 def format_on_edit(self, final_content, edit_content):
688 if final_content.get("schema_version") and edit_content.get("credentials"):
garciadeblas4568a372021-03-24 09:19:48 +0100689 self.db.encrypt_decrypt_fields(
690 edit_content["credentials"],
691 "encrypt",
692 ["password", "secret"],
693 schema_version=final_content["schema_version"],
694 salt=final_content["_id"],
695 )
696 deep_update_rfc7396(
697 final_content["credentials"], edit_content["credentials"]
698 )
delacruzramofe598fe2019-10-23 18:25:11 +0200699 oid = super().format_on_edit(final_content, edit_content)
700 return oid
701
delacruzramoc2d5fc62020-02-05 11:50:21 +0000702 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
garciadeblas4568a372021-03-24 09:19:48 +0100703 final_content = super(CommonVimWimSdn, self).check_conflict_on_edit(
704 session, final_content, edit_content, _id
705 )
706 final_content = super().check_conflict_on_edit(
707 session, final_content, edit_content, _id
708 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000709 # Update Helm/Juju Repo lists
710 repos = {"helm-chart": [], "juju-bundle": []}
711 for proj in session.get("set_project", []):
garciadeblas4568a372021-03-24 09:19:48 +0100712 if proj != "ANY":
713 for repo in self.db.get_list(
714 "k8srepos", {"_admin.projects_read": proj}
715 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000716 if repo["_id"] not in repos[repo["type"]]:
717 repos[repo["type"]].append(repo["_id"])
718 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100719 rlist = k.replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000720 if rlist not in final_content["_admin"]:
721 final_content["_admin"][rlist] = []
722 final_content["_admin"][rlist] += repos[k]
bravofb995ea22021-02-10 10:57:52 -0300723 return final_content
delacruzramoc2d5fc62020-02-05 11:50:21 +0000724
tiernoe19707b2020-04-21 13:08:04 +0000725 def check_conflict_on_del(self, session, _id, db_content):
726 """
727 Check if deletion can be done because of dependencies if it is not force. To override
728 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
729 :param _id: internal _id
730 :param db_content: The database content of this item _id
731 :return: None if ok or raises EngineException with the conflict
732 """
733 if session["force"]:
734 return
735 # check if used by VNF
736 filter_q = {"kdur.k8s-cluster.id": _id}
737 if session["project_id"]:
738 filter_q["_admin.projects_read.cont"] = session["project_id"]
739 if self.db.get_list("vnfrs", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100740 raise EngineException(
741 "There is at least one VNF using this k8scluster",
742 http_code=HTTPStatus.CONFLICT,
743 )
tiernoe19707b2020-04-21 13:08:04 +0000744 super().check_conflict_on_del(session, _id, db_content)
745
delacruzramofe598fe2019-10-23 18:25:11 +0200746
David Garciaecb41322021-03-31 19:10:46 +0200747class VcaTopic(CommonVimWimSdn):
748 topic = "vca"
749 topic_msg = "vca"
750 schema_new = vca_new_schema
751 schema_edit = vca_edit_schema
752 multiproject = True
753 password_to_encrypt = None
754
755 def format_on_new(self, content, project_id=None, make_public=False):
756 oid = super().format_on_new(content, project_id, make_public)
757 content["schema_version"] = schema_version = "1.11"
758 for key in ["secret", "cacert"]:
759 content[key] = self.db.encrypt(
garciadeblas4568a372021-03-24 09:19:48 +0100760 content[key], schema_version=schema_version, salt=content["_id"]
David Garciaecb41322021-03-31 19:10:46 +0200761 )
762 return oid
763
764 def format_on_edit(self, final_content, edit_content):
765 oid = super().format_on_edit(final_content, edit_content)
766 schema_version = final_content.get("schema_version")
767 for key in ["secret", "cacert"]:
768 if key in edit_content:
769 final_content[key] = self.db.encrypt(
770 edit_content[key],
771 schema_version=schema_version,
garciadeblas4568a372021-03-24 09:19:48 +0100772 salt=final_content["_id"],
David Garciaecb41322021-03-31 19:10:46 +0200773 )
774 return oid
775
776 def check_conflict_on_del(self, session, _id, db_content):
777 """
778 Check if deletion can be done because of dependencies if it is not force. To override
779 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
780 :param _id: internal _id
781 :param db_content: The database content of this item _id
782 :return: None if ok or raises EngineException with the conflict
783 """
784 if session["force"]:
785 return
786 # check if used by VNF
787 filter_q = {"vca": _id}
788 if session["project_id"]:
789 filter_q["_admin.projects_read.cont"] = session["project_id"]
790 if self.db.get_list("vim_accounts", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100791 raise EngineException(
792 "There is at least one VIM account using this vca",
793 http_code=HTTPStatus.CONFLICT,
794 )
David Garciaecb41322021-03-31 19:10:46 +0200795 super().check_conflict_on_del(session, _id, db_content)
796
797
delacruzramofe598fe2019-10-23 18:25:11 +0200798class K8sRepoTopic(CommonVimWimSdn):
799 topic = "k8srepos"
800 topic_msg = "k8srepo"
801 schema_new = k8srepo_new_schema
802 schema_edit = k8srepo_edit_schema
803 multiproject = True
804 password_to_encrypt = None
805 config_to_encrypt = {}
806
delacruzramoc2d5fc62020-02-05 11:50:21 +0000807 def format_on_new(self, content, project_id=None, make_public=False):
808 oid = super().format_on_new(content, project_id, make_public)
809 # Update Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100810 repo_list = content["type"].replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000811 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100812 if proj != "ANY":
813 self.db.set_list(
814 "k8sclusters",
815 {
816 "_admin.projects_read": proj,
817 "_admin." + repo_list + ".ne": content["_id"],
818 },
819 {},
820 push={"_admin." + repo_list: content["_id"]},
821 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000822 return oid
823
824 def delete(self, session, _id, dry_run=False, not_send_msg=None):
825 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
826 oid = super().delete(session, _id, dry_run, not_send_msg)
827 if oid:
828 # Remove from Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100829 repo_list = type.replace("-", "_") + "_repos"
830 self.db.set_list(
831 "k8sclusters",
832 {"_admin." + repo_list: _id},
833 {},
834 pull={"_admin." + repo_list: _id},
835 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000836 return oid
837
delacruzramofe598fe2019-10-23 18:25:11 +0200838
Felipe Vicensb66b0412020-05-06 10:11:00 +0200839class OsmRepoTopic(BaseTopic):
840 topic = "osmrepos"
841 topic_msg = "osmrepos"
842 schema_new = osmrepo_new_schema
843 schema_edit = osmrepo_edit_schema
844 multiproject = True
845 # TODO: Implement user/password
846
847
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100848class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100849 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000850 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100851 schema_new = user_new_schema
852 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100853
854 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200855 UserTopic.__init__(self, db, fs, msg, auth)
856 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100857
tierno65ca36d2019-02-12 19:27:52 +0100858 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100859 """
860 Check that the data to be inserted is valid
861
tierno65ca36d2019-02-12 19:27:52 +0100862 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100863 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100864 :return: None or raises EngineException
865 """
866 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000867 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100868 raise EngineException(
869 "username '{}' cannot have a uuid format".format(username),
870 HTTPStatus.UNPROCESSABLE_ENTITY,
871 )
tiernocf042d32019-06-13 09:06:40 +0000872
873 # Check that username is not used, regardless keystone already checks this
874 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100875 raise EngineException(
876 "username '{}' is already used".format(username), HTTPStatus.CONFLICT
877 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100878
Eduardo Sousa339ed782019-05-28 14:25:00 +0100879 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000880 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200881 role = self.auth.get_role_list({"name": "project_admin"})
882 if not role:
883 role = self.auth.get_role_list()
884 if not role:
garciadeblas4568a372021-03-24 09:19:48 +0100885 raise AuthconnNotFoundException(
886 "Can't find default role for user '{}'".format(username)
887 )
delacruzramo01b15d32019-07-02 14:37:47 +0200888 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000889 if not indata.get("project_role_mappings"):
890 indata["project_role_mappings"] = []
891 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200892 pid = self.auth.get_project(project)["_id"]
893 prm = {"project": pid, "role": rid}
894 if prm not in indata["project_role_mappings"]:
895 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000896 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
897 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100898
tierno65ca36d2019-02-12 19:27:52 +0100899 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100900 """
901 Check that the data to be edited/uploaded is valid
902
tierno65ca36d2019-02-12 19:27:52 +0100903 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100904 :param final_content: data once modified
905 :param edit_content: incremental data that contains the modifications to apply
906 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100907 :return: None or raises EngineException
908 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100909
tiernocf042d32019-06-13 09:06:40 +0000910 if "username" in edit_content:
911 username = edit_content.get("username")
912 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100913 raise EngineException(
914 "username '{}' cannot have an uuid format".format(username),
915 HTTPStatus.UNPROCESSABLE_ENTITY,
916 )
tiernocf042d32019-06-13 09:06:40 +0000917
918 # Check that username is not used, regardless keystone already checks this
919 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100920 raise EngineException(
921 "username '{}' is already used".format(username),
922 HTTPStatus.CONFLICT,
923 )
tiernocf042d32019-06-13 09:06:40 +0000924
925 if final_content["username"] == "admin":
926 for mapping in edit_content.get("remove_project_role_mappings", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100927 if mapping["project"] == "admin" and mapping.get("role") in (
928 None,
929 "system_admin",
930 ):
tiernocf042d32019-06-13 09:06:40 +0000931 # TODO make this also available for project id and role id
garciadeblas4568a372021-03-24 09:19:48 +0100932 raise EngineException(
933 "You cannot remove system_admin role from admin user",
934 http_code=HTTPStatus.FORBIDDEN,
935 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100936
bravofb995ea22021-02-10 10:57:52 -0300937 return final_content
938
tiernob4844ab2019-05-23 08:42:12 +0000939 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100940 """
941 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100942 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100943 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000944 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100945 :return: None if ok or raises EngineException with the conflict
946 """
tiernocf042d32019-06-13 09:06:40 +0000947 if db_content["username"] == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100948 raise EngineException(
949 "You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT
950 )
delacruzramo01b15d32019-07-02 14:37:47 +0200951 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100952
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100953 @staticmethod
954 def format_on_show(content):
955 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100956 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100957 metadata from the role definition.
958 """
959 project_role_mappings = []
960
delacruzramo01b15d32019-07-02 14:37:47 +0200961 if "projects" in content:
962 for project in content["projects"]:
963 for role in project["roles"]:
garciadeblas4568a372021-03-24 09:19:48 +0100964 project_role_mappings.append(
965 {
966 "project": project["_id"],
967 "project_name": project["name"],
968 "role": role["_id"],
969 "role_name": role["name"],
970 }
971 )
delacruzramo01b15d32019-07-02 14:37:47 +0200972 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100973 content["project_role_mappings"] = project_role_mappings
974
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100975 return content
976
tierno65ca36d2019-02-12 19:27:52 +0100977 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100978 """
979 Creates a new entry into the authentication backend.
980
981 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
982
983 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100984 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100985 :param indata: data to be inserted
986 :param kwargs: used to override the indata descriptor
987 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200988 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100989 """
990 try:
991 content = BaseTopic._remove_envelop(indata)
992
993 # Override descriptor with query string kwargs
994 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100995 content = self._validate_input_new(content, session["force"])
996 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000997 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200998 now = time()
999 content["_admin"] = {"created": now, "modified": now}
1000 prms = []
1001 for prm in content.get("project_role_mappings", []):
1002 proj = self.auth.get_project(prm["project"], not session["force"])
1003 role = self.auth.get_role(prm["role"], not session["force"])
1004 pid = proj["_id"] if proj else None
1005 rid = role["_id"] if role else None
1006 prl = {"project": pid, "role": rid}
1007 if prl not in prms:
1008 prms.append(prl)
1009 content["project_role_mappings"] = prms
1010 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
1011 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +01001012
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001013 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +00001014 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +00001015 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001016 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001017 except ValidationError as e:
1018 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1019
K Sai Kiran57589552021-01-27 21:38:34 +05301020 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001021 """
1022 Get complete information on an topic
1023
tierno65ca36d2019-02-12 19:27:52 +01001024 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +00001025 :param _id: server internal id or username
K Sai Kiran57589552021-01-27 21:38:34 +05301026 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301027 :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 +01001028 :return: dictionary, raise exception if not found.
1029 """
tiernocf042d32019-06-13 09:06:40 +00001030 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +00001031 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +02001032 # users = self.auth.get_user_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001033 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001034 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +00001035 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001036 elif len(users) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001037 raise EngineException(
1038 "Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT
1039 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001040 else:
garciadeblas4568a372021-03-24 09:19:48 +01001041 raise EngineException(
1042 "User '{}' not found".format(_id), HTTPStatus.NOT_FOUND
1043 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001044
tierno65ca36d2019-02-12 19:27:52 +01001045 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001046 """
1047 Updates an user entry.
1048
tierno65ca36d2019-02-12 19:27:52 +01001049 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001050 :param _id:
1051 :param indata: data to be inserted
1052 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001053 :param content:
1054 :return: _id: identity of the inserted data.
1055 """
1056 indata = self._remove_envelop(indata)
1057
1058 # Override descriptor with query string kwargs
1059 if kwargs:
1060 BaseTopic._update_input_with_kwargs(indata, kwargs)
1061 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001062 if not content:
1063 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001064 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001065 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +00001066 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001067
garciadeblas4568a372021-03-24 09:19:48 +01001068 if not (
1069 "password" in indata
1070 or "username" in indata
1071 or indata.get("remove_project_role_mappings")
1072 or indata.get("add_project_role_mappings")
1073 or indata.get("project_role_mappings")
1074 or indata.get("projects")
1075 or indata.get("add_projects")
1076 ):
tiernocf042d32019-06-13 09:06:40 +00001077 return _id
garciadeblas4568a372021-03-24 09:19:48 +01001078 if indata.get("project_role_mappings") and (
1079 indata.get("remove_project_role_mappings")
1080 or indata.get("add_project_role_mappings")
1081 ):
1082 raise EngineException(
1083 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1084 "' or 'remove_project_role_mappings'",
1085 http_code=HTTPStatus.BAD_REQUEST,
1086 )
Eduardo Sousa44603902019-06-04 08:10:32 +01001087
delacruzramo01b15d32019-07-02 14:37:47 +02001088 if indata.get("projects") or indata.get("add_projects"):
1089 role = self.auth.get_role_list({"name": "project_admin"})
1090 if not role:
1091 role = self.auth.get_role_list()
1092 if not role:
garciadeblas4568a372021-03-24 09:19:48 +01001093 raise AuthconnNotFoundException(
1094 "Can't find a default role for user '{}'".format(
1095 content["username"]
1096 )
1097 )
delacruzramo01b15d32019-07-02 14:37:47 +02001098 rid = role[0]["_id"]
1099 if "add_project_role_mappings" not in indata:
1100 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +00001101 if "remove_project_role_mappings" not in indata:
1102 indata["remove_project_role_mappings"] = []
1103 if isinstance(indata.get("projects"), dict):
1104 # backward compatible
1105 for k, v in indata["projects"].items():
1106 if k.startswith("$") and v is None:
garciadeblas4568a372021-03-24 09:19:48 +01001107 indata["remove_project_role_mappings"].append(
1108 {"project": k[1:]}
1109 )
tierno1546f2a2019-08-20 15:38:11 +00001110 elif k.startswith("$+"):
garciadeblas4568a372021-03-24 09:19:48 +01001111 indata["add_project_role_mappings"].append(
1112 {"project": v, "role": rid}
1113 )
tierno1546f2a2019-08-20 15:38:11 +00001114 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +02001115 for proj in indata.get("projects", []) + indata.get("add_projects", []):
garciadeblas4568a372021-03-24 09:19:48 +01001116 indata["add_project_role_mappings"].append(
1117 {"project": proj, "role": rid}
1118 )
delacruzramo01b15d32019-07-02 14:37:47 +02001119
1120 # user = self.show(session, _id) # Already in 'content'
1121 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +01001122
tiernocf042d32019-06-13 09:06:40 +00001123 mappings_to_add = []
1124 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +01001125
tiernocf042d32019-06-13 09:06:40 +00001126 # remove
1127 for to_remove in indata.get("remove_project_role_mappings", ()):
1128 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001129 if to_remove["project"] in (
1130 mapping["project"],
1131 mapping["project_name"],
1132 ):
1133 if not to_remove.get("role") or to_remove["role"] in (
1134 mapping["role"],
1135 mapping["role_name"],
1136 ):
tiernocf042d32019-06-13 09:06:40 +00001137 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +01001138
tiernocf042d32019-06-13 09:06:40 +00001139 # add
1140 for to_add in indata.get("add_project_role_mappings", ()):
1141 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001142 if to_add["project"] in (
1143 mapping["project"],
1144 mapping["project_name"],
Mark Beierlc528d882023-01-06 12:56:16 -05001145 ) and to_add["role"] in (
1146 mapping["role"],
1147 mapping["role_name"],
1148 ):
garciadeblas4568a372021-03-24 09:19:48 +01001149 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001150 mappings_to_remove.remove(mapping)
1151 break # do not add, it is already at user
1152 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001153 pid = self.auth.get_project(to_add["project"])["_id"]
1154 rid = self.auth.get_role(to_add["role"])["_id"]
1155 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001156
1157 # set
1158 if indata.get("project_role_mappings"):
1159 for to_set in indata["project_role_mappings"]:
1160 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001161 if to_set["project"] in (
1162 mapping["project"],
1163 mapping["project_name"],
Mark Beierlc528d882023-01-06 12:56:16 -05001164 ) and to_set["role"] in (
1165 mapping["role"],
1166 mapping["role_name"],
1167 ):
garciadeblas4568a372021-03-24 09:19:48 +01001168 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001169 mappings_to_remove.remove(mapping)
1170 break # do not add, it is already at user
1171 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001172 pid = self.auth.get_project(to_set["project"])["_id"]
1173 rid = self.auth.get_role(to_set["role"])["_id"]
1174 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001175 for mapping in original_mapping:
1176 for to_set in indata["project_role_mappings"]:
garciadeblas4568a372021-03-24 09:19:48 +01001177 if to_set["project"] in (
1178 mapping["project"],
1179 mapping["project_name"],
Mark Beierlc528d882023-01-06 12:56:16 -05001180 ) and to_set["role"] in (
1181 mapping["role"],
1182 mapping["role_name"],
1183 ):
tiernocf042d32019-06-13 09:06:40 +00001184 break
1185 else:
1186 # delete
garciadeblas4568a372021-03-24 09:19:48 +01001187 if mapping not in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001188 mappings_to_remove.append(mapping)
1189
garciadeblas4568a372021-03-24 09:19:48 +01001190 self.auth.update_user(
1191 {
1192 "_id": _id,
1193 "username": indata.get("username"),
1194 "password": indata.get("password"),
selvi.ja9a1fc82022-04-04 06:54:30 +00001195 "old_password": indata.get("old_password"),
garciadeblas4568a372021-03-24 09:19:48 +01001196 "add_project_role_mappings": mappings_to_add,
1197 "remove_project_role_mappings": mappings_to_remove,
1198 }
1199 )
1200 data_to_send = {"_id": _id, "changes": indata}
agarwalat53471982020-10-08 13:06:14 +00001201 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +00001202
delacruzramo01b15d32019-07-02 14:37:47 +02001203 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001204 except ValidationError as e:
1205 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1206
tiernoc4e07d02020-08-14 14:25:32 +00001207 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001208 """
1209 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +01001210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001211 :param filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +05301212 :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 +01001213 :return: The list, it can be empty if no one match the filter.
1214 """
delacruzramo029405d2019-09-26 10:52:56 +02001215 user_list = self.auth.get_user_list(filter_q)
1216 if not session["allow_show_user_project_role"]:
1217 # Bug 853 - Default filtering
garciadeblas4568a372021-03-24 09:19:48 +01001218 user_list = [
1219 usr for usr in user_list if usr["username"] == session["username"]
1220 ]
delacruzramo029405d2019-09-26 10:52:56 +02001221 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001222
tiernobee3bad2019-12-05 12:26:01 +00001223 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001224 """
1225 Delete item by its internal _id
1226
tierno65ca36d2019-02-12 19:27:52 +01001227 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001228 :param _id: server internal id
1229 :param force: indicates if deletion must be forced in case of conflict
1230 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001231 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001232 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1233 """
tiernocf042d32019-06-13 09:06:40 +00001234 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001235 user = self.auth.get_user(_id)
1236 uid = user["_id"]
1237 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001238 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001239 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +00001240 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001241 return v
1242 return None
1243
1244
1245class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +01001246 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +00001247 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +01001248 schema_new = project_new_schema
1249 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001250
1251 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001252 ProjectTopic.__init__(self, db, fs, msg, auth)
1253 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001254
tierno65ca36d2019-02-12 19:27:52 +01001255 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001256 """
1257 Check that the data to be inserted is valid
1258
tierno65ca36d2019-02-12 19:27:52 +01001259 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001260 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001261 :return: None or raises EngineException
1262 """
tiernocf042d32019-06-13 09:06:40 +00001263 project_name = indata.get("name")
1264 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001265 raise EngineException(
1266 "project name '{}' cannot have an uuid format".format(project_name),
1267 HTTPStatus.UNPROCESSABLE_ENTITY,
1268 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001269
tiernocf042d32019-06-13 09:06:40 +00001270 project_list = self.auth.get_project_list(filter_q={"name": project_name})
1271
1272 if project_list:
garciadeblas4568a372021-03-24 09:19:48 +01001273 raise EngineException(
1274 "project '{}' exists".format(project_name), HTTPStatus.CONFLICT
1275 )
tiernocf042d32019-06-13 09:06:40 +00001276
1277 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1278 """
1279 Check that the data to be edited/uploaded is valid
1280
1281 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1282 :param final_content: data once modified
1283 :param edit_content: incremental data that contains the modifications to apply
1284 :param _id: internal _id
1285 :return: None or raises EngineException
1286 """
1287
1288 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +02001289 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +00001290 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001291 raise EngineException(
1292 "project name '{}' cannot have an uuid format".format(project_name),
1293 HTTPStatus.UNPROCESSABLE_ENTITY,
1294 )
tiernocf042d32019-06-13 09:06:40 +00001295
delacruzramo01b15d32019-07-02 14:37:47 +02001296 if final_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001297 raise EngineException(
1298 "You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT
1299 )
delacruzramo01b15d32019-07-02 14:37:47 +02001300
tiernocf042d32019-06-13 09:06:40 +00001301 # Check that project name is not used, regardless keystone already checks this
garciadeblas4568a372021-03-24 09:19:48 +01001302 if project_name and self.auth.get_project_list(
1303 filter_q={"name": project_name}
1304 ):
1305 raise EngineException(
1306 "project '{}' is already used".format(project_name),
1307 HTTPStatus.CONFLICT,
1308 )
bravofb995ea22021-02-10 10:57:52 -03001309 return final_content
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001310
tiernob4844ab2019-05-23 08:42:12 +00001311 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001312 """
1313 Check if deletion can be done because of dependencies if it is not force. To override
1314
tierno65ca36d2019-02-12 19:27:52 +01001315 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001316 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001317 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001318 :return: None if ok or raises EngineException with the conflict
1319 """
delacruzramo01b15d32019-07-02 14:37:47 +02001320
1321 def check_rw_projects(topic, title, id_field):
1322 for desc in self.db.get_list(topic):
garciadeblas4568a372021-03-24 09:19:48 +01001323 if (
1324 _id
1325 in desc["_admin"]["projects_read"]
1326 + desc["_admin"]["projects_write"]
1327 ):
1328 raise EngineException(
1329 "Project '{}' ({}) is being used by {} '{}'".format(
1330 db_content["name"], _id, title, desc[id_field]
1331 ),
1332 HTTPStatus.CONFLICT,
1333 )
delacruzramo01b15d32019-07-02 14:37:47 +02001334
1335 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +01001336 raise EngineException(
1337 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
1338 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001339
delacruzramo01b15d32019-07-02 14:37:47 +02001340 if db_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001341 raise EngineException(
1342 "You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT
1343 )
delacruzramo01b15d32019-07-02 14:37:47 +02001344
1345 # If any user is using this project, raise CONFLICT exception
1346 if not session["force"]:
1347 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001348 for prm in user.get("project_role_mappings"):
1349 if prm["project"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001350 raise EngineException(
1351 "Project '{}' ({}) is being used by user '{}'".format(
1352 db_content["name"], _id, user["username"]
1353 ),
1354 HTTPStatus.CONFLICT,
1355 )
delacruzramo01b15d32019-07-02 14:37:47 +02001356
1357 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1358 if not session["force"]:
1359 check_rw_projects("vnfds", "VNF Descriptor", "id")
1360 check_rw_projects("nsds", "NS Descriptor", "id")
1361 check_rw_projects("nsts", "NS Template", "id")
1362 check_rw_projects("pdus", "PDU Descriptor", "name")
1363
tierno65ca36d2019-02-12 19:27:52 +01001364 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001365 """
1366 Creates a new entry into the authentication backend.
1367
1368 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1369
1370 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001371 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001372 :param indata: data to be inserted
1373 :param kwargs: used to override the indata descriptor
1374 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001375 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001376 """
1377 try:
1378 content = BaseTopic._remove_envelop(indata)
1379
1380 # Override descriptor with query string kwargs
1381 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001382 content = self._validate_input_new(content, session["force"])
1383 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001384 self.format_on_new(
1385 content, project_id=session["project_id"], make_public=session["public"]
1386 )
delacruzramo01b15d32019-07-02 14:37:47 +02001387 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001388 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +00001389 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001390 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001391 except ValidationError as e:
1392 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1393
K Sai Kiran57589552021-01-27 21:38:34 +05301394 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001395 """
1396 Get complete information on an topic
1397
tierno65ca36d2019-02-12 19:27:52 +01001398 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001399 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301400 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301401 :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 +01001402 :return: dictionary, raise exception if not found.
1403 """
tiernocf042d32019-06-13 09:06:40 +00001404 # Allow _id to be a name or uuid
1405 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001406 # projects = self.auth.get_project_list(filter_q=filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001407 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001408 if len(projects) == 1:
1409 return projects[0]
1410 elif len(projects) > 1:
1411 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
1412 else:
1413 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
1414
tiernoc4e07d02020-08-14 14:25:32 +00001415 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001416 """
1417 Get a list of the topic that matches a filter
1418
tierno65ca36d2019-02-12 19:27:52 +01001419 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001420 :param filter_q: filter of data to be applied
1421 :return: The list, it can be empty if no one match the filter.
1422 """
delacruzramo029405d2019-09-26 10:52:56 +02001423 project_list = self.auth.get_project_list(filter_q)
1424 if not session["allow_show_user_project_role"]:
1425 # Bug 853 - Default filtering
1426 user = self.auth.get_user(session["username"])
1427 projects = [prm["project"] for prm in user["project_role_mappings"]]
1428 project_list = [proj for proj in project_list if proj["_id"] in projects]
1429 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001430
tiernobee3bad2019-12-05 12:26:01 +00001431 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001432 """
1433 Delete item by its internal _id
1434
tierno65ca36d2019-02-12 19:27:52 +01001435 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001436 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001437 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001438 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001439 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1440 """
tiernocf042d32019-06-13 09:06:40 +00001441 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001442 proj = self.auth.get_project(_id)
1443 pid = proj["_id"]
1444 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001445 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001446 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001447 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001448 return v
1449 return None
1450
tierno4015b472019-06-10 13:57:29 +00001451 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1452 """
1453 Updates a project entry.
1454
1455 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1456 :param _id:
1457 :param indata: data to be inserted
1458 :param kwargs: used to override the indata descriptor
1459 :param content:
1460 :return: _id: identity of the inserted data.
1461 """
1462 indata = self._remove_envelop(indata)
1463
1464 # Override descriptor with query string kwargs
1465 if kwargs:
1466 BaseTopic._update_input_with_kwargs(indata, kwargs)
1467 try:
tierno4015b472019-06-10 13:57:29 +00001468 if not content:
1469 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001470 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001471 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001472 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001473 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001474 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001475 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001476 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1477 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001478 except ValidationError as e:
1479 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1480
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001481
1482class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001483 topic = "roles"
garciadeblas4568a372021-03-24 09:19:48 +01001484 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001485 schema_new = roles_new_schema
1486 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001487 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001488
tierno9e87a7f2020-03-23 09:24:10 +00001489 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001490 BaseTopic.__init__(self, db, fs, msg, auth)
1491 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001492 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001493 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001494
1495 @staticmethod
1496 def validate_role_definition(operations, role_definitions):
1497 """
1498 Validates the role definition against the operations defined in
1499 the resources to operations files.
1500
1501 :param operations: operations list
1502 :param role_definitions: role definition to test
1503 :return: None if ok, raises ValidationError exception on error
1504 """
tierno1f029d82019-06-13 22:37:04 +00001505 if not role_definitions.get("permissions"):
1506 return
1507 ignore_fields = ["admin", "default"]
1508 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001509 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001510 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001511 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001512 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001513
garciadeblas4568a372021-03-24 09:19:48 +01001514 match = next(
1515 (
1516 op
1517 for op in operations
1518 if op == role_def or op.startswith(role_def + ":")
1519 ),
1520 None,
1521 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001522
tierno97639b42020-08-04 12:48:15 +00001523 if not match:
tierno1f029d82019-06-13 22:37:04 +00001524 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001525
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001526 def _validate_input_new(self, input, force=False):
1527 """
1528 Validates input user content for a new entry.
1529
1530 :param input: user input content for the new topic
1531 :param force: may be used for being more tolerant
1532 :return: The same input content, or a changed version of it.
1533 """
1534 if self.schema_new:
1535 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001536 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001537
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001538 return input
1539
Frank Brydendeba68e2020-07-27 13:55:11 +00001540 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001541 """
1542 Validates input user content for updating an entry.
1543
1544 :param input: user input content for the new topic
1545 :param force: may be used for being more tolerant
1546 :return: The same input content, or a changed version of it.
1547 """
1548 if self.schema_edit:
1549 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001550 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001551
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001552 return input
1553
tierno65ca36d2019-02-12 19:27:52 +01001554 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001555 """
1556 Check that the data to be inserted is valid
1557
tierno65ca36d2019-02-12 19:27:52 +01001558 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001559 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001560 :return: None or raises EngineException
1561 """
delacruzramo79e40f42019-10-10 16:36:40 +02001562 # check name is not uuid
1563 role_name = indata.get("name")
1564 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001565 raise EngineException(
1566 "role name '{}' cannot have an uuid format".format(role_name),
1567 HTTPStatus.UNPROCESSABLE_ENTITY,
1568 )
tierno1f029d82019-06-13 22:37:04 +00001569 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001570 name = indata["name"]
1571 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1572 if self.auth.get_role_list({"name": name}):
garciadeblas4568a372021-03-24 09:19:48 +01001573 raise EngineException(
1574 "role name '{}' exists".format(name), HTTPStatus.CONFLICT
1575 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001576
tierno65ca36d2019-02-12 19:27:52 +01001577 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001578 """
1579 Check that the data to be edited/uploaded is valid
1580
tierno65ca36d2019-02-12 19:27:52 +01001581 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001582 :param final_content: data once modified
1583 :param edit_content: incremental data that contains the modifications to apply
1584 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001585 :return: None or raises EngineException
1586 """
tierno1f029d82019-06-13 22:37:04 +00001587 if "default" not in final_content["permissions"]:
1588 final_content["permissions"]["default"] = False
1589 if "admin" not in final_content["permissions"]:
1590 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001591
delacruzramo79e40f42019-10-10 16:36:40 +02001592 # check name is not uuid
1593 role_name = edit_content.get("name")
1594 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001595 raise EngineException(
1596 "role name '{}' cannot have an uuid format".format(role_name),
1597 HTTPStatus.UNPROCESSABLE_ENTITY,
1598 )
delacruzramo79e40f42019-10-10 16:36:40 +02001599
1600 # Check renaming of admin roles
1601 role = self.auth.get_role(_id)
1602 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001603 raise EngineException(
1604 "You cannot rename role '{}'".format(role["name"]),
1605 http_code=HTTPStatus.FORBIDDEN,
1606 )
delacruzramo79e40f42019-10-10 16:36:40 +02001607
tierno1f029d82019-06-13 22:37:04 +00001608 # check name not exists
1609 if "name" in edit_content:
1610 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001611 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1612 roles = self.auth.get_role_list({"name": role_name})
1613 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
garciadeblas4568a372021-03-24 09:19:48 +01001614 raise EngineException(
1615 "role name '{}' exists".format(role_name), HTTPStatus.CONFLICT
1616 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001617
bravofb995ea22021-02-10 10:57:52 -03001618 return final_content
1619
tiernob4844ab2019-05-23 08:42:12 +00001620 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001621 """
1622 Check if deletion can be done because of dependencies if it is not force. To override
1623
tierno65ca36d2019-02-12 19:27:52 +01001624 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001625 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001626 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001627 :return: None if ok or raises EngineException with the conflict
1628 """
delacruzramo01b15d32019-07-02 14:37:47 +02001629 role = self.auth.get_role(_id)
1630 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001631 raise EngineException(
1632 "You cannot delete role '{}'".format(role["name"]),
1633 http_code=HTTPStatus.FORBIDDEN,
1634 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001635
delacruzramo01b15d32019-07-02 14:37:47 +02001636 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001637 if not session["force"]:
1638 for user in self.auth.get_user_list():
1639 for prm in user.get("project_role_mappings"):
1640 if prm["role"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001641 raise EngineException(
1642 "Role '{}' ({}) is being used by user '{}'".format(
1643 role["name"], _id, user["username"]
1644 ),
1645 HTTPStatus.CONFLICT,
1646 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001647
1648 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +01001649 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001650 """
1651 Modifies content descriptor to include _admin
1652
1653 :param content: descriptor to be modified
1654 :param project_id: if included, it add project read/write permissions
1655 :param make_public: if included it is generated as public for reading.
1656 :return: None, but content is modified
1657 """
1658 now = time()
1659 if "_admin" not in content:
1660 content["_admin"] = {}
1661 if not content["_admin"].get("created"):
1662 content["_admin"]["created"] = now
1663 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001664
tierno1f029d82019-06-13 22:37:04 +00001665 if "permissions" not in content:
1666 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001667
tierno1f029d82019-06-13 22:37:04 +00001668 if "default" not in content["permissions"]:
1669 content["permissions"]["default"] = False
1670 if "admin" not in content["permissions"]:
1671 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001672
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001673 @staticmethod
1674 def format_on_edit(final_content, edit_content):
1675 """
1676 Modifies final_content descriptor to include the modified date.
1677
1678 :param final_content: final descriptor generated
1679 :param edit_content: alterations to be include
1680 :return: None, but final_content is modified
1681 """
delacruzramo01b15d32019-07-02 14:37:47 +02001682 if "_admin" in final_content:
1683 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001684
tierno1f029d82019-06-13 22:37:04 +00001685 if "permissions" not in final_content:
1686 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001687
tierno1f029d82019-06-13 22:37:04 +00001688 if "default" not in final_content["permissions"]:
1689 final_content["permissions"]["default"] = False
1690 if "admin" not in final_content["permissions"]:
1691 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001692 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001693
K Sai Kiran57589552021-01-27 21:38:34 +05301694 def show(self, session, _id, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001695 """
1696 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001697
delacruzramo01b15d32019-07-02 14:37:47 +02001698 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1699 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301700 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301701 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001702 :return: dictionary, raise exception if not found.
1703 """
1704 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001705 # roles = self.auth.get_role_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001706 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001707 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001708 raise AuthconnNotFoundException(
1709 "Not found any role with filter {}".format(filter_q)
1710 )
delacruzramo01b15d32019-07-02 14:37:47 +02001711 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001712 raise AuthconnConflictException(
1713 "Found more than one role with filter {}".format(filter_q)
1714 )
delacruzramo01b15d32019-07-02 14:37:47 +02001715 return roles[0]
1716
tiernoc4e07d02020-08-14 14:25:32 +00001717 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001718 """
1719 Get a list of the topic that matches a filter
1720
1721 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1722 :param filter_q: filter of data to be applied
1723 :return: The list, it can be empty if no one match the filter.
1724 """
delacruzramo029405d2019-09-26 10:52:56 +02001725 role_list = self.auth.get_role_list(filter_q)
1726 if not session["allow_show_user_project_role"]:
1727 # Bug 853 - Default filtering
1728 user = self.auth.get_user(session["username"])
1729 roles = [prm["role"] for prm in user["project_role_mappings"]]
1730 role_list = [role for role in role_list if role["_id"] in roles]
1731 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001732
tierno65ca36d2019-02-12 19:27:52 +01001733 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001734 """
1735 Creates a new entry into database.
1736
1737 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001738 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001739 :param indata: data to be inserted
1740 :param kwargs: used to override the indata descriptor
1741 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001742 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001743 """
1744 try:
tierno1f029d82019-06-13 22:37:04 +00001745 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001746
1747 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001748 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001749 content = self._validate_input_new(content, session["force"])
1750 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001751 self.format_on_new(
1752 content, project_id=session["project_id"], make_public=session["public"]
1753 )
delacruzramo01b15d32019-07-02 14:37:47 +02001754 # role_name = content["name"]
1755 rid = self.auth.create_role(content)
1756 content["_id"] = rid
1757 # _id = self.db.create(self.topic, content)
1758 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001759 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001760 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001761 except ValidationError as e:
1762 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1763
tiernobee3bad2019-12-05 12:26:01 +00001764 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001765 """
1766 Delete item by its internal _id
1767
tierno65ca36d2019-02-12 19:27:52 +01001768 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001769 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001770 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001771 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001772 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1773 """
delacruzramo01b15d32019-07-02 14:37:47 +02001774 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1775 roles = self.auth.get_role_list(filter_q)
1776 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001777 raise AuthconnNotFoundException(
1778 "Not found any role with filter {}".format(filter_q)
1779 )
delacruzramo01b15d32019-07-02 14:37:47 +02001780 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001781 raise AuthconnConflictException(
1782 "Found more than one role with filter {}".format(filter_q)
1783 )
delacruzramo01b15d32019-07-02 14:37:47 +02001784 rid = roles[0]["_id"]
1785 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001786 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001787 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001788 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001789 v = self.auth.delete_role(rid)
1790 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001791 return v
1792 return None
1793
tierno65ca36d2019-02-12 19:27:52 +01001794 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001795 """
1796 Updates a role entry.
1797
tierno65ca36d2019-02-12 19:27:52 +01001798 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001799 :param _id:
1800 :param indata: data to be inserted
1801 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001802 :param content:
1803 :return: _id: identity of the inserted data.
1804 """
delacruzramo01b15d32019-07-02 14:37:47 +02001805 if kwargs:
1806 self._update_input_with_kwargs(indata, kwargs)
1807 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001808 if not content:
1809 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001810 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001811 deep_update_rfc7396(content, indata)
bravofb995ea22021-02-10 10:57:52 -03001812 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001813 self.format_on_edit(content, indata)
1814 self.auth.update_role(content)
1815 except ValidationError as e:
1816 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)