blob: b4f89809024be856c2f705842aefae0f04861b4f [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
17from uuid import uuid4
18from hashlib import sha256
19from http import HTTPStatus
Eduardo Sousa5c01e192019-05-08 02:35:47 +010020from time import time
garciadeblas4568a372021-03-24 09:19:48 +010021from osm_nbi.validation import (
22 user_new_schema,
23 user_edit_schema,
24 project_new_schema,
25 project_edit_schema,
26 vim_account_new_schema,
27 vim_account_edit_schema,
28 sdn_new_schema,
29 sdn_edit_schema,
30 wim_account_new_schema,
31 wim_account_edit_schema,
32 roles_new_schema,
33 roles_edit_schema,
34 k8scluster_new_schema,
35 k8scluster_edit_schema,
36 k8srepo_new_schema,
37 k8srepo_edit_schema,
38 vca_new_schema,
39 vca_edit_schema,
40 osmrepo_new_schema,
41 osmrepo_edit_schema,
42 validate_input,
43 ValidationError,
44 is_valid_uuid,
45) # To check that User/Project Names don't look like UUIDs
tierno23acf402019-08-28 13:36:34 +000046from osm_nbi.base_topic import BaseTopic, EngineException
47from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020048from osm_common.dbbase import deep_update_rfc7396
agarwalat53471982020-10-08 13:06:14 +000049import copy
tiernob24258a2018-10-04 18:39:49 +020050
51__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
52
53
54class UserTopic(BaseTopic):
55 topic = "users"
56 topic_msg = "users"
57 schema_new = user_new_schema
58 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010059 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020060
delacruzramo32bab472019-09-13 12:24:22 +020061 def __init__(self, db, fs, msg, auth):
62 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020063
64 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010065 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020066 """
67 Generates a filter dictionary for querying database users.
68 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020070 :return:
71 """
72 if session["admin"]: # allows all
73 return {}
74 else:
75 return {"username": session["username"]}
76
tierno65ca36d2019-02-12 19:27:52 +010077 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020078 # check username not exists
garciadeblas4568a372021-03-24 09:19:48 +010079 if self.db.get_one(
80 self.topic,
81 {"username": indata.get("username")},
82 fail_on_empty=False,
83 fail_on_more=False,
84 ):
85 raise EngineException(
86 "username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT
87 )
tiernob24258a2018-10-04 18:39:49 +020088 # check projects
tierno65ca36d2019-02-12 19:27:52 +010089 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020090 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020091 # To allow project addressing by Name as well as ID
garciadeblas4568a372021-03-24 09:19:48 +010092 if not self.db.get_one(
93 "projects",
94 {BaseTopic.id_field("projects", p): p},
95 fail_on_empty=False,
96 fail_on_more=False,
97 ):
98 raise EngineException(
99 "project '{}' does not exist".format(p), HTTPStatus.CONFLICT
100 )
tiernob24258a2018-10-04 18:39:49 +0200101
tiernob4844ab2019-05-23 08:42:12 +0000102 def check_conflict_on_del(self, session, _id, db_content):
103 """
104 Check if deletion can be done because of dependencies if it is not force. To override
105 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
106 :param _id: internal _id
107 :param db_content: The database content of this item _id
108 :return: None if ok or raises EngineException with the conflict
109 """
tiernob24258a2018-10-04 18:39:49 +0200110 if _id == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100111 raise EngineException(
112 "You cannot delete your own user", http_code=HTTPStatus.CONFLICT
113 )
tiernob24258a2018-10-04 18:39:49 +0200114
115 @staticmethod
116 def format_on_new(content, project_id=None, make_public=False):
117 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +0200118 # Removed so that the UUID is kept, to allow User Name modification
119 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +0200120 salt = uuid4().hex
121 content["_admin"]["salt"] = salt
122 if content.get("password"):
garciadeblas4568a372021-03-24 09:19:48 +0100123 content["password"] = sha256(
124 content["password"].encode("utf-8") + salt.encode("utf-8")
125 ).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +0100126 if content.get("project_role_mappings"):
garciadeblas4568a372021-03-24 09:19:48 +0100127 projects = [
128 mapping["project"] for mapping in content["project_role_mappings"]
129 ]
Eduardo Sousa339ed782019-05-28 14:25:00 +0100130
131 if content.get("projects"):
132 content["projects"] += projects
133 else:
134 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +0200135
136 @staticmethod
137 def format_on_edit(final_content, edit_content):
138 BaseTopic.format_on_edit(final_content, edit_content)
139 if edit_content.get("password"):
140 salt = uuid4().hex
141 final_content["_admin"]["salt"] = salt
garciadeblas4568a372021-03-24 09:19:48 +0100142 final_content["password"] = sha256(
143 edit_content["password"].encode("utf-8") + salt.encode("utf-8")
144 ).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000145 return None
tiernob24258a2018-10-04 18:39:49 +0200146
tierno65ca36d2019-02-12 19:27:52 +0100147 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200148 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100149 raise EngineException(
150 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
151 )
delacruzramoc061f562019-04-05 11:00:02 +0200152 # Names that look like UUIDs are not allowed
153 name = (indata if indata else kwargs).get("username")
154 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100155 raise EngineException(
156 "Usernames that look like UUIDs are not allowed",
157 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
158 )
159 return BaseTopic.edit(
160 self, session, _id, indata=indata, kwargs=kwargs, content=content
161 )
tiernob24258a2018-10-04 18:39:49 +0200162
tierno65ca36d2019-02-12 19:27:52 +0100163 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200164 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100165 raise EngineException(
166 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
167 )
delacruzramoc061f562019-04-05 11:00:02 +0200168 # Names that look like UUIDs are not allowed
169 name = indata["username"] if indata else kwargs["username"]
170 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100171 raise EngineException(
172 "Usernames that look like UUIDs are not allowed",
173 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
174 )
175 return BaseTopic.new(
176 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
177 )
tiernob24258a2018-10-04 18:39:49 +0200178
179
180class ProjectTopic(BaseTopic):
181 topic = "projects"
182 topic_msg = "projects"
183 schema_new = project_new_schema
184 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100185 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200186
delacruzramo32bab472019-09-13 12:24:22 +0200187 def __init__(self, db, fs, msg, auth):
188 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200189
tierno65ca36d2019-02-12 19:27:52 +0100190 @staticmethod
191 def _get_project_filter(session):
192 """
193 Generates a filter dictionary for querying database users.
194 Current policy is admin can show all, non admin, only its own user.
195 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
196 :return:
197 """
198 if session["admin"]: # allows all
199 return {}
200 else:
201 return {"_id.cont": session["project_id"]}
202
203 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200204 if not indata.get("name"):
205 raise EngineException("missing 'name'")
206 # check name not exists
garciadeblas4568a372021-03-24 09:19:48 +0100207 if self.db.get_one(
208 self.topic,
209 {"name": indata.get("name")},
210 fail_on_empty=False,
211 fail_on_more=False,
212 ):
213 raise EngineException(
214 "name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT
215 )
tiernob24258a2018-10-04 18:39:49 +0200216
217 @staticmethod
218 def format_on_new(content, project_id=None, make_public=False):
219 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200220 # Removed so that the UUID is kept, to allow Project Name modification
221 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200222
tiernob4844ab2019-05-23 08:42:12 +0000223 def check_conflict_on_del(self, session, _id, db_content):
224 """
225 Check if deletion can be done because of dependencies if it is not force. To override
226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
227 :param _id: internal _id
228 :param db_content: The database content of this item _id
229 :return: None if ok or raises EngineException with the conflict
230 """
tierno65ca36d2019-02-12 19:27:52 +0100231 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100232 raise EngineException(
233 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
234 )
tierno65ca36d2019-02-12 19:27:52 +0100235 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200236 return
237 _filter = {"projects": _id}
238 if self.db.get_list("users", _filter):
garciadeblas4568a372021-03-24 09:19:48 +0100239 raise EngineException(
240 "There is some USER that contains this project",
241 http_code=HTTPStatus.CONFLICT,
242 )
tiernob24258a2018-10-04 18:39:49 +0200243
tierno65ca36d2019-02-12 19:27:52 +0100244 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200245 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100246 raise EngineException(
247 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
248 )
delacruzramoc061f562019-04-05 11:00:02 +0200249 # Names that look like UUIDs are not allowed
250 name = (indata if indata else kwargs).get("name")
251 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100252 raise EngineException(
253 "Project names that look like UUIDs are not allowed",
254 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
255 )
256 return BaseTopic.edit(
257 self, session, _id, indata=indata, kwargs=kwargs, content=content
258 )
tiernob24258a2018-10-04 18:39:49 +0200259
tierno65ca36d2019-02-12 19:27:52 +0100260 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200261 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100262 raise EngineException(
263 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
264 )
delacruzramoc061f562019-04-05 11:00:02 +0200265 # Names that look like UUIDs are not allowed
266 name = indata["name"] if indata else kwargs["name"]
267 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100268 raise EngineException(
269 "Project names that look like UUIDs are not allowed",
270 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
271 )
272 return BaseTopic.new(
273 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
274 )
tiernob24258a2018-10-04 18:39:49 +0200275
276
tiernobdebce92019-07-01 15:36:49 +0000277class CommonVimWimSdn(BaseTopic):
278 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
garciadeblas4568a372021-03-24 09:19:48 +0100279
280 config_to_encrypt = (
281 {}
282 ) # what keys at config must be encrypted because contains passwords
283 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200284
tiernobdebce92019-07-01 15:36:49 +0000285 @staticmethod
286 def _create_operation(op_type, params=None):
287 """
288 Creates a dictionary with the information to an operation, similar to ns-lcm-op
289 :param op_type: can be create, edit, delete
290 :param params: operation input parameters
291 :return: new dictionary with
292 """
293 now = time()
294 return {
295 "lcmOperationType": op_type,
296 "operationState": "PROCESSING",
297 "startTime": now,
298 "statusEnteredTime": now,
299 "detailed-status": "",
300 "operationParams": params,
301 }
tiernob24258a2018-10-04 18:39:49 +0200302
tierno65ca36d2019-02-12 19:27:52 +0100303 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000304 """
305 Check that the data to be inserted is valid. It is checked that name is unique
306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
307 :param indata: data to be inserted
308 :return: None or raises EngineException
309 """
tiernob24258a2018-10-04 18:39:49 +0200310 self.check_unique_name(session, indata["name"], _id=None)
311
tierno65ca36d2019-02-12 19:27:52 +0100312 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000313 """
314 Check that the data to be edited/uploaded is valid. It is checked that name is unique
315 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
316 :param final_content: data once modified. This method may change it.
317 :param edit_content: incremental data that contains the modifications to apply
318 :param _id: internal _id
319 :return: None or raises EngineException
320 """
tierno65ca36d2019-02-12 19:27:52 +0100321 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200322 self.check_unique_name(session, edit_content["name"], _id=_id)
323
bravofb995ea22021-02-10 10:57:52 -0300324 return final_content
325
tiernobdebce92019-07-01 15:36:49 +0000326 def format_on_edit(self, final_content, edit_content):
327 """
328 Modifies final_content inserting admin information upon edition
329 :param final_content: final content to be stored at database
330 :param edit_content: user requested update content
331 :return: operation id
332 """
delacruzramofe598fe2019-10-23 18:25:11 +0200333 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000334
tierno92c1c7d2018-11-12 15:22:37 +0100335 # encrypt passwords
336 schema_version = final_content.get("schema_version")
337 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000338 if edit_content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100339 final_content[self.password_to_encrypt] = self.db.encrypt(
340 edit_content[self.password_to_encrypt],
341 schema_version=schema_version,
342 salt=final_content["_id"],
343 )
344 config_to_encrypt_keys = self.config_to_encrypt.get(
345 schema_version
346 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000347 if edit_content.get("config") and config_to_encrypt_keys:
tierno468aa242019-08-01 16:35:04 +0000348 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100349 if edit_content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100350 final_content["config"][p] = self.db.encrypt(
351 edit_content["config"][p],
352 schema_version=schema_version,
353 salt=final_content["_id"],
354 )
yshah93909d22024-08-12 09:13:28 +0000355 if edit_content.get("config", {}).get("credentials"):
356 cloud_credentials = edit_content["config"]["credentials"]
357 if cloud_credentials.get("clientSecret"):
358 edit_content["config"]["credentials"][
359 "clientSecret"
360 ] = self.db.encrypt(
361 edit_content["config"]["credentials"]["clientSecret"],
362 schema_version=schema_version,
363 salt=edit_content["_id"],
364 )
365 elif cloud_credentials.get("SecretAccessKey"):
366 edit_content["config"]["credentials"][
367 "SecretAccessKey"
368 ] = self.db.encrypt(
369 edit_content["config"]["credentials"]["SecretAccessKey"],
370 schema_version=schema_version,
371 salt=edit_content["_id"],
372 )
tiernobdebce92019-07-01 15:36:49 +0000373
374 # create edit operation
375 final_content["_admin"]["operations"].append(self._create_operation("edit"))
garciadeblas4568a372021-03-24 09:19:48 +0100376 return "{}:{}".format(
377 final_content["_id"], len(final_content["_admin"]["operations"]) - 1
378 )
tierno92c1c7d2018-11-12 15:22:37 +0100379
380 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000381 """
382 Modifies content descriptor to include _admin and insert create operation
383 :param content: descriptor to be modified
384 :param project_id: if included, it add project read/write permissions. Can be None or a list
385 :param make_public: if included it is generated as public for reading.
386 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
387 """
388 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000389 content["schema_version"] = schema_version = "1.11"
yshah53cc9eb2024-07-05 13:06:31 +0000390 content["key"] = "registered"
tierno92c1c7d2018-11-12 15:22:37 +0100391
392 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000393 if content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100394 content[self.password_to_encrypt] = self.db.encrypt(
395 content[self.password_to_encrypt],
396 schema_version=schema_version,
397 salt=content["_id"],
398 )
399 config_to_encrypt_keys = self.config_to_encrypt.get(
400 schema_version
401 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000402 if content.get("config") and config_to_encrypt_keys:
403 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100404 if content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100405 content["config"][p] = self.db.encrypt(
406 content["config"][p],
407 schema_version=schema_version,
408 salt=content["_id"],
409 )
yshah93909d22024-08-12 09:13:28 +0000410 if content.get("config", {}).get("credentials"):
411 cloud_credentials = content["config"]["credentials"]
412 if cloud_credentials.get("clientSecret"):
413 content["config"]["credentials"]["clientSecret"] = self.db.encrypt(
414 content["config"]["credentials"]["clientSecret"],
415 schema_version=schema_version,
416 salt=content["_id"],
417 )
418 elif cloud_credentials.get("SecretAccessKey"):
419 content["config"]["credentials"]["SecretAccessKey"] = self.db.encrypt(
420 content["config"]["credentials"]["SecretAccessKey"],
421 schema_version=schema_version,
422 salt=content["_id"],
423 )
tierno92c1c7d2018-11-12 15:22:37 +0100424
tiernob24258a2018-10-04 18:39:49 +0200425 content["_admin"]["operationalState"] = "PROCESSING"
426
tiernobdebce92019-07-01 15:36:49 +0000427 # create operation
428 content["_admin"]["operations"] = [self._create_operation("create")]
429 content["_admin"]["current_operation"] = None
vijay.rd1eaf982021-05-14 11:54:59 +0000430 # create Resource in Openstack based VIM
431 if content.get("vim_type"):
432 if content["vim_type"] == "openstack":
433 compute = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100434 "ram": {"total": None, "used": None},
435 "vcpus": {"total": None, "used": None},
436 "instances": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000437 }
438 storage = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100439 "volumes": {"total": None, "used": None},
440 "snapshots": {"total": None, "used": None},
441 "storage": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000442 }
443 network = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100444 "networks": {"total": None, "used": None},
445 "subnets": {"total": None, "used": None},
446 "floating_ips": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000447 }
garciadeblasf2af4a12023-01-24 16:56:54 +0100448 content["resources"] = {
449 "compute": compute,
450 "storage": storage,
451 "network": network,
452 }
vijay.rd1eaf982021-05-14 11:54:59 +0000453
tiernobdebce92019-07-01 15:36:49 +0000454 return "{}:0".format(content["_id"])
455
tiernobee3bad2019-12-05 12:26:01 +0000456 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200457 """
458 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100459 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200460 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200461 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000462 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000463 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200464 """
tiernobdebce92019-07-01 15:36:49 +0000465
466 filter_q = self._get_project_filter(session)
467 filter_q["_id"] = _id
468 db_content = self.db.get_one(self.topic, filter_q)
469
470 self.check_conflict_on_del(session, _id, db_content)
471 if dry_run:
472 return None
473
tiernof5f2e3f2020-03-23 14:42:10 +0000474 # remove reference from project_read if there are more projects referencing it. If it last one,
475 # do not remove reference, but order via kafka to delete it
selvi.ja5e05112023-04-28 11:00:21 +0000476 if session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100477 other_projects_referencing = next(
478 (
479 p
480 for p in db_content["_admin"]["projects_read"]
481 if p not in session["project_id"] and p != "ANY"
482 ),
483 None,
484 )
tiernobdebce92019-07-01 15:36:49 +0000485
tiernof5f2e3f2020-03-23 14:42:10 +0000486 # check if there are projects referencing it (apart from ANY, that means, public)....
487 if other_projects_referencing:
488 # remove references but not delete
garciadeblas4568a372021-03-24 09:19:48 +0100489 update_dict_pull = {
490 "_admin.projects_read": session["project_id"],
491 "_admin.projects_write": session["project_id"],
492 }
493 self.db.set_one(
494 self.topic, filter_q, update_dict=None, pull_list=update_dict_pull
495 )
tiernof5f2e3f2020-03-23 14:42:10 +0000496 return None
497 else:
garciadeblas4568a372021-03-24 09:19:48 +0100498 can_write = next(
499 (
500 p
501 for p in db_content["_admin"]["projects_write"]
502 if p == "ANY" or p in session["project_id"]
503 ),
504 None,
505 )
tiernof5f2e3f2020-03-23 14:42:10 +0000506 if not can_write:
garciadeblas4568a372021-03-24 09:19:48 +0100507 raise EngineException(
508 "You have not write permission to delete it",
509 http_code=HTTPStatus.UNAUTHORIZED,
510 )
tiernobdebce92019-07-01 15:36:49 +0000511
512 # It must be deleted
513 if session["force"]:
514 self.db.del_one(self.topic, {"_id": _id})
515 op_id = None
garciadeblas4568a372021-03-24 09:19:48 +0100516 self._send_msg(
517 "deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
518 )
tiernobdebce92019-07-01 15:36:49 +0000519 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000520 update_dict = {"_admin.to_delete": True}
garciadeblas4568a372021-03-24 09:19:48 +0100521 self.db.set_one(
522 self.topic,
523 {"_id": _id},
524 update_dict=update_dict,
525 push={"_admin.operations": self._create_operation("delete")},
526 )
tiernobdebce92019-07-01 15:36:49 +0000527 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
528 # so the -1 is not needed
garciadeblas4568a372021-03-24 09:19:48 +0100529 op_id = "{}:{}".format(
530 db_content["_id"], len(db_content["_admin"]["operations"])
531 )
532 self._send_msg(
533 "delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
534 )
tiernobdebce92019-07-01 15:36:49 +0000535 return op_id
tiernob24258a2018-10-04 18:39:49 +0200536
537
tiernobdebce92019-07-01 15:36:49 +0000538class VimAccountTopic(CommonVimWimSdn):
539 topic = "vim_accounts"
540 topic_msg = "vim_account"
541 schema_new = vim_account_new_schema
542 schema_edit = vim_account_edit_schema
543 multiproject = True
544 password_to_encrypt = "vim_password"
garciadeblas4568a372021-03-24 09:19:48 +0100545 config_to_encrypt = {
546 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
547 "default": (
548 "admin_password",
549 "nsx_password",
550 "vcenter_password",
551 "vrops_password",
552 ),
553 }
tiernobdebce92019-07-01 15:36:49 +0000554
delacruzramo35c998b2019-11-21 11:09:16 +0100555 def check_conflict_on_del(self, session, _id, db_content):
556 """
557 Check if deletion can be done because of dependencies if it is not force. To override
558 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
559 :param _id: internal _id
560 :param db_content: The database content of this item _id
561 :return: None if ok or raises EngineException with the conflict
562 """
563 if session["force"]:
564 return
565 # check if used by VNF
566 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
garciadeblas4568a372021-03-24 09:19:48 +0100567 raise EngineException(
568 "There is at least one VNF using this VIM account",
569 http_code=HTTPStatus.CONFLICT,
570 )
delacruzramo35c998b2019-11-21 11:09:16 +0100571 super().check_conflict_on_del(session, _id, db_content)
572
tiernobdebce92019-07-01 15:36:49 +0000573
574class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000575 topic = "wim_accounts"
576 topic_msg = "wim_account"
577 schema_new = wim_account_new_schema
578 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100579 multiproject = True
gifrerenom44f5ec12022-03-07 16:57:25 +0000580 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000581 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000582
583
tiernobdebce92019-07-01 15:36:49 +0000584class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200585 topic = "sdns"
586 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000587 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200588 schema_new = sdn_new_schema
589 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100590 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000591 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000592 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100593
tierno7adaeb02019-12-17 16:46:12 +0000594 def _obtain_url(self, input, create):
595 if input.get("ip") or input.get("port"):
garciadeblas4568a372021-03-24 09:19:48 +0100596 if not input.get("ip") or not input.get("port") or input.get("url"):
597 raise ValidationError(
598 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
599 )
600 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
tierno7adaeb02019-12-17 16:46:12 +0000601 del input["ip"]
602 del input["port"]
garciadeblas4568a372021-03-24 09:19:48 +0100603 elif create and not input.get("url"):
tierno7adaeb02019-12-17 16:46:12 +0000604 raise ValidationError("You must provide 'url'")
605 return input
606
607 def _validate_input_new(self, input, force=False):
608 input = super()._validate_input_new(input, force)
609 return self._obtain_url(input, True)
610
Frank Brydendeba68e2020-07-27 13:55:11 +0000611 def _validate_input_edit(self, input, content, force=False):
612 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000613 return self._obtain_url(input, False)
614
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100615
delacruzramofe598fe2019-10-23 18:25:11 +0200616class K8sClusterTopic(CommonVimWimSdn):
617 topic = "k8sclusters"
618 topic_msg = "k8scluster"
619 schema_new = k8scluster_new_schema
620 schema_edit = k8scluster_edit_schema
621 multiproject = True
622 password_to_encrypt = None
623 config_to_encrypt = {}
624
625 def format_on_new(self, content, project_id=None, make_public=False):
626 oid = super().format_on_new(content, project_id, make_public)
garciadeblas4568a372021-03-24 09:19:48 +0100627 self.db.encrypt_decrypt_fields(
628 content["credentials"],
629 "encrypt",
630 ["password", "secret"],
631 schema_version=content["schema_version"],
632 salt=content["_id"],
633 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000634 # Add Helm/Juju Repo lists
635 repos = {"helm-chart": [], "juju-bundle": []}
636 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100637 if proj != "ANY":
638 for repo in self.db.get_list(
639 "k8srepos", {"_admin.projects_read": proj}
640 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000641 if repo["_id"] not in repos[repo["type"]]:
642 repos[repo["type"]].append(repo["_id"])
643 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100644 content["_admin"][k.replace("-", "_") + "_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200645 return oid
646
647 def format_on_edit(self, final_content, edit_content):
648 if final_content.get("schema_version") and edit_content.get("credentials"):
garciadeblas4568a372021-03-24 09:19:48 +0100649 self.db.encrypt_decrypt_fields(
650 edit_content["credentials"],
651 "encrypt",
652 ["password", "secret"],
653 schema_version=final_content["schema_version"],
654 salt=final_content["_id"],
655 )
656 deep_update_rfc7396(
657 final_content["credentials"], edit_content["credentials"]
658 )
delacruzramofe598fe2019-10-23 18:25:11 +0200659 oid = super().format_on_edit(final_content, edit_content)
660 return oid
661
delacruzramoc2d5fc62020-02-05 11:50:21 +0000662 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
garciadeblas4568a372021-03-24 09:19:48 +0100663 final_content = super(CommonVimWimSdn, self).check_conflict_on_edit(
664 session, final_content, edit_content, _id
665 )
666 final_content = super().check_conflict_on_edit(
667 session, final_content, edit_content, _id
668 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000669 # Update Helm/Juju Repo lists
670 repos = {"helm-chart": [], "juju-bundle": []}
671 for proj in session.get("set_project", []):
garciadeblas4568a372021-03-24 09:19:48 +0100672 if proj != "ANY":
673 for repo in self.db.get_list(
674 "k8srepos", {"_admin.projects_read": proj}
675 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000676 if repo["_id"] not in repos[repo["type"]]:
677 repos[repo["type"]].append(repo["_id"])
678 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100679 rlist = k.replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000680 if rlist not in final_content["_admin"]:
681 final_content["_admin"][rlist] = []
682 final_content["_admin"][rlist] += repos[k]
bravofb995ea22021-02-10 10:57:52 -0300683 return final_content
delacruzramoc2d5fc62020-02-05 11:50:21 +0000684
tiernoe19707b2020-04-21 13:08:04 +0000685 def check_conflict_on_del(self, session, _id, db_content):
686 """
687 Check if deletion can be done because of dependencies if it is not force. To override
688 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
689 :param _id: internal _id
690 :param db_content: The database content of this item _id
691 :return: None if ok or raises EngineException with the conflict
692 """
693 if session["force"]:
694 return
695 # check if used by VNF
696 filter_q = {"kdur.k8s-cluster.id": _id}
697 if session["project_id"]:
698 filter_q["_admin.projects_read.cont"] = session["project_id"]
699 if self.db.get_list("vnfrs", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100700 raise EngineException(
701 "There is at least one VNF using this k8scluster",
702 http_code=HTTPStatus.CONFLICT,
703 )
tiernoe19707b2020-04-21 13:08:04 +0000704 super().check_conflict_on_del(session, _id, db_content)
705
delacruzramofe598fe2019-10-23 18:25:11 +0200706
David Garciaecb41322021-03-31 19:10:46 +0200707class VcaTopic(CommonVimWimSdn):
708 topic = "vca"
709 topic_msg = "vca"
710 schema_new = vca_new_schema
711 schema_edit = vca_edit_schema
712 multiproject = True
713 password_to_encrypt = None
714
715 def format_on_new(self, content, project_id=None, make_public=False):
716 oid = super().format_on_new(content, project_id, make_public)
717 content["schema_version"] = schema_version = "1.11"
718 for key in ["secret", "cacert"]:
719 content[key] = self.db.encrypt(
garciadeblas4568a372021-03-24 09:19:48 +0100720 content[key], schema_version=schema_version, salt=content["_id"]
David Garciaecb41322021-03-31 19:10:46 +0200721 )
722 return oid
723
724 def format_on_edit(self, final_content, edit_content):
725 oid = super().format_on_edit(final_content, edit_content)
726 schema_version = final_content.get("schema_version")
727 for key in ["secret", "cacert"]:
728 if key in edit_content:
729 final_content[key] = self.db.encrypt(
730 edit_content[key],
731 schema_version=schema_version,
garciadeblas4568a372021-03-24 09:19:48 +0100732 salt=final_content["_id"],
David Garciaecb41322021-03-31 19:10:46 +0200733 )
734 return oid
735
736 def check_conflict_on_del(self, session, _id, db_content):
737 """
738 Check if deletion can be done because of dependencies if it is not force. To override
739 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
740 :param _id: internal _id
741 :param db_content: The database content of this item _id
742 :return: None if ok or raises EngineException with the conflict
743 """
744 if session["force"]:
745 return
746 # check if used by VNF
747 filter_q = {"vca": _id}
748 if session["project_id"]:
749 filter_q["_admin.projects_read.cont"] = session["project_id"]
750 if self.db.get_list("vim_accounts", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100751 raise EngineException(
752 "There is at least one VIM account using this vca",
753 http_code=HTTPStatus.CONFLICT,
754 )
David Garciaecb41322021-03-31 19:10:46 +0200755 super().check_conflict_on_del(session, _id, db_content)
756
757
delacruzramofe598fe2019-10-23 18:25:11 +0200758class K8sRepoTopic(CommonVimWimSdn):
759 topic = "k8srepos"
760 topic_msg = "k8srepo"
761 schema_new = k8srepo_new_schema
762 schema_edit = k8srepo_edit_schema
763 multiproject = True
764 password_to_encrypt = None
765 config_to_encrypt = {}
766
delacruzramoc2d5fc62020-02-05 11:50:21 +0000767 def format_on_new(self, content, project_id=None, make_public=False):
768 oid = super().format_on_new(content, project_id, make_public)
769 # Update Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100770 repo_list = content["type"].replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000771 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100772 if proj != "ANY":
773 self.db.set_list(
774 "k8sclusters",
775 {
776 "_admin.projects_read": proj,
777 "_admin." + repo_list + ".ne": content["_id"],
778 },
779 {},
780 push={"_admin." + repo_list: content["_id"]},
781 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000782 return oid
783
784 def delete(self, session, _id, dry_run=False, not_send_msg=None):
785 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
786 oid = super().delete(session, _id, dry_run, not_send_msg)
787 if oid:
788 # Remove from Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100789 repo_list = type.replace("-", "_") + "_repos"
790 self.db.set_list(
791 "k8sclusters",
792 {"_admin." + repo_list: _id},
793 {},
794 pull={"_admin." + repo_list: _id},
795 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000796 return oid
797
delacruzramofe598fe2019-10-23 18:25:11 +0200798
Felipe Vicensb66b0412020-05-06 10:11:00 +0200799class OsmRepoTopic(BaseTopic):
800 topic = "osmrepos"
801 topic_msg = "osmrepos"
802 schema_new = osmrepo_new_schema
803 schema_edit = osmrepo_edit_schema
804 multiproject = True
805 # TODO: Implement user/password
806
807
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100808class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100809 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000810 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100811 schema_new = user_new_schema
812 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100813
814 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200815 UserTopic.__init__(self, db, fs, msg, auth)
816 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100817
tierno65ca36d2019-02-12 19:27:52 +0100818 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100819 """
820 Check that the data to be inserted is valid
821
tierno65ca36d2019-02-12 19:27:52 +0100822 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100823 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100824 :return: None or raises EngineException
825 """
826 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000827 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100828 raise EngineException(
829 "username '{}' cannot have a uuid format".format(username),
830 HTTPStatus.UNPROCESSABLE_ENTITY,
831 )
tiernocf042d32019-06-13 09:06:40 +0000832
833 # Check that username is not used, regardless keystone already checks this
834 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100835 raise EngineException(
836 "username '{}' is already used".format(username), HTTPStatus.CONFLICT
837 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100838
Eduardo Sousa339ed782019-05-28 14:25:00 +0100839 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000840 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200841 role = self.auth.get_role_list({"name": "project_admin"})
842 if not role:
843 role = self.auth.get_role_list()
844 if not role:
garciadeblas4568a372021-03-24 09:19:48 +0100845 raise AuthconnNotFoundException(
846 "Can't find default role for user '{}'".format(username)
847 )
delacruzramo01b15d32019-07-02 14:37:47 +0200848 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000849 if not indata.get("project_role_mappings"):
850 indata["project_role_mappings"] = []
851 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200852 pid = self.auth.get_project(project)["_id"]
853 prm = {"project": pid, "role": rid}
854 if prm not in indata["project_role_mappings"]:
855 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000856 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
857 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100858
tierno65ca36d2019-02-12 19:27:52 +0100859 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100860 """
861 Check that the data to be edited/uploaded is valid
862
tierno65ca36d2019-02-12 19:27:52 +0100863 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100864 :param final_content: data once modified
865 :param edit_content: incremental data that contains the modifications to apply
866 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100867 :return: None or raises EngineException
868 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100869
tiernocf042d32019-06-13 09:06:40 +0000870 if "username" in edit_content:
871 username = edit_content.get("username")
872 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100873 raise EngineException(
874 "username '{}' cannot have an uuid format".format(username),
875 HTTPStatus.UNPROCESSABLE_ENTITY,
876 )
tiernocf042d32019-06-13 09:06:40 +0000877
878 # Check that username is not used, regardless keystone already checks this
879 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100880 raise EngineException(
881 "username '{}' is already used".format(username),
882 HTTPStatus.CONFLICT,
883 )
tiernocf042d32019-06-13 09:06:40 +0000884
885 if final_content["username"] == "admin":
886 for mapping in edit_content.get("remove_project_role_mappings", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100887 if mapping["project"] == "admin" and mapping.get("role") in (
888 None,
889 "system_admin",
890 ):
tiernocf042d32019-06-13 09:06:40 +0000891 # TODO make this also available for project id and role id
garciadeblas4568a372021-03-24 09:19:48 +0100892 raise EngineException(
893 "You cannot remove system_admin role from admin user",
894 http_code=HTTPStatus.FORBIDDEN,
895 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100896
bravofb995ea22021-02-10 10:57:52 -0300897 return final_content
898
tiernob4844ab2019-05-23 08:42:12 +0000899 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100900 """
901 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100902 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100903 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000904 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100905 :return: None if ok or raises EngineException with the conflict
906 """
tiernocf042d32019-06-13 09:06:40 +0000907 if db_content["username"] == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100908 raise EngineException(
909 "You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT
910 )
delacruzramo01b15d32019-07-02 14:37:47 +0200911 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100912
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100913 @staticmethod
914 def format_on_show(content):
915 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100916 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100917 metadata from the role definition.
918 """
919 project_role_mappings = []
920
delacruzramo01b15d32019-07-02 14:37:47 +0200921 if "projects" in content:
922 for project in content["projects"]:
923 for role in project["roles"]:
garciadeblas4568a372021-03-24 09:19:48 +0100924 project_role_mappings.append(
925 {
926 "project": project["_id"],
927 "project_name": project["name"],
928 "role": role["_id"],
929 "role_name": role["name"],
930 }
931 )
delacruzramo01b15d32019-07-02 14:37:47 +0200932 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100933 content["project_role_mappings"] = project_role_mappings
934
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100935 return content
936
tierno65ca36d2019-02-12 19:27:52 +0100937 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100938 """
939 Creates a new entry into the authentication backend.
940
941 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
942
943 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100944 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100945 :param indata: data to be inserted
946 :param kwargs: used to override the indata descriptor
947 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200948 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100949 """
950 try:
951 content = BaseTopic._remove_envelop(indata)
952
953 # Override descriptor with query string kwargs
954 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100955 content = self._validate_input_new(content, session["force"])
956 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000957 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200958 now = time()
959 content["_admin"] = {"created": now, "modified": now}
960 prms = []
961 for prm in content.get("project_role_mappings", []):
962 proj = self.auth.get_project(prm["project"], not session["force"])
963 role = self.auth.get_role(prm["role"], not session["force"])
964 pid = proj["_id"] if proj else None
965 rid = role["_id"] if role else None
966 prl = {"project": pid, "role": rid}
967 if prl not in prms:
968 prms.append(prl)
969 content["project_role_mappings"] = prms
970 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
971 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100972
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100973 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000974 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +0000975 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200976 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100977 except ValidationError as e:
978 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
979
K Sai Kiran57589552021-01-27 21:38:34 +0530980 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100981 """
982 Get complete information on an topic
983
tierno65ca36d2019-02-12 19:27:52 +0100984 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +0000985 :param _id: server internal id or username
K Sai Kiran57589552021-01-27 21:38:34 +0530986 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +0530987 :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 +0100988 :return: dictionary, raise exception if not found.
989 """
tiernocf042d32019-06-13 09:06:40 +0000990 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000991 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200992 # users = self.auth.get_user_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +0100993 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100994 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000995 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100996 elif len(users) > 1:
garciadeblas4568a372021-03-24 09:19:48 +0100997 raise EngineException(
998 "Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT
999 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001000 else:
garciadeblas4568a372021-03-24 09:19:48 +01001001 raise EngineException(
1002 "User '{}' not found".format(_id), HTTPStatus.NOT_FOUND
1003 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001004
tierno65ca36d2019-02-12 19:27:52 +01001005 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001006 """
1007 Updates an user entry.
1008
tierno65ca36d2019-02-12 19:27:52 +01001009 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001010 :param _id:
1011 :param indata: data to be inserted
1012 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001013 :param content:
1014 :return: _id: identity of the inserted data.
1015 """
1016 indata = self._remove_envelop(indata)
1017
1018 # Override descriptor with query string kwargs
1019 if kwargs:
1020 BaseTopic._update_input_with_kwargs(indata, kwargs)
1021 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001022 if not content:
1023 content = self.show(session, _id)
yshah53cc9eb2024-07-05 13:06:31 +00001024
Frank Brydendeba68e2020-07-27 13:55:11 +00001025 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001026 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +00001027 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001028
garciadeblas4568a372021-03-24 09:19:48 +01001029 if not (
1030 "password" in indata
1031 or "username" in indata
1032 or indata.get("remove_project_role_mappings")
1033 or indata.get("add_project_role_mappings")
1034 or indata.get("project_role_mappings")
1035 or indata.get("projects")
1036 or indata.get("add_projects")
garciadeblas6d83f8f2023-06-19 22:34:49 +02001037 or indata.get("unlock")
1038 or indata.get("renew")
jeganbe1a3df2024-06-04 12:05:19 +00001039 or indata.get("email_id")
garciadeblas4568a372021-03-24 09:19:48 +01001040 ):
tiernocf042d32019-06-13 09:06:40 +00001041 return _id
garciadeblas4568a372021-03-24 09:19:48 +01001042 if indata.get("project_role_mappings") and (
1043 indata.get("remove_project_role_mappings")
1044 or indata.get("add_project_role_mappings")
1045 ):
1046 raise EngineException(
1047 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1048 "' or 'remove_project_role_mappings'",
1049 http_code=HTTPStatus.BAD_REQUEST,
1050 )
Eduardo Sousa44603902019-06-04 08:10:32 +01001051
delacruzramo01b15d32019-07-02 14:37:47 +02001052 if indata.get("projects") or indata.get("add_projects"):
1053 role = self.auth.get_role_list({"name": "project_admin"})
1054 if not role:
1055 role = self.auth.get_role_list()
1056 if not role:
garciadeblas4568a372021-03-24 09:19:48 +01001057 raise AuthconnNotFoundException(
1058 "Can't find a default role for user '{}'".format(
1059 content["username"]
1060 )
1061 )
delacruzramo01b15d32019-07-02 14:37:47 +02001062 rid = role[0]["_id"]
1063 if "add_project_role_mappings" not in indata:
1064 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +00001065 if "remove_project_role_mappings" not in indata:
1066 indata["remove_project_role_mappings"] = []
1067 if isinstance(indata.get("projects"), dict):
1068 # backward compatible
1069 for k, v in indata["projects"].items():
1070 if k.startswith("$") and v is None:
garciadeblas4568a372021-03-24 09:19:48 +01001071 indata["remove_project_role_mappings"].append(
1072 {"project": k[1:]}
1073 )
tierno1546f2a2019-08-20 15:38:11 +00001074 elif k.startswith("$+"):
garciadeblas4568a372021-03-24 09:19:48 +01001075 indata["add_project_role_mappings"].append(
1076 {"project": v, "role": rid}
1077 )
tierno1546f2a2019-08-20 15:38:11 +00001078 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +02001079 for proj in indata.get("projects", []) + indata.get("add_projects", []):
garciadeblas4568a372021-03-24 09:19:48 +01001080 indata["add_project_role_mappings"].append(
1081 {"project": proj, "role": rid}
1082 )
Adurti76d4b762024-05-07 06:04:37 +00001083 if (
1084 indata.get("remove_project_role_mappings")
1085 or indata.get("add_project_role_mappings")
1086 or indata.get("project_role_mappings")
1087 ):
1088 user_details = self.db.get_one("users", {"_id": session.get("user_id")})
1089 edit_role = False
1090 for pr in user_details["project_role_mappings"]:
1091 role_id = pr.get("role")
1092 role_details = self.db.get_one("roles", {"_id": role_id})
1093 if role_details["permissions"].get("default"):
1094 if "roles" not in role_details["permissions"] or role_details[
1095 "permissions"
1096 ].get("roles"):
1097 edit_role = True
1098 elif role_details["permissions"].get("roles"):
1099 edit_role = True
1100 if not edit_role:
1101 raise EngineException(
1102 "User {} has no privileges to edit or delete project-role mappings".format(
1103 session.get("username")
1104 ),
1105 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1106 )
delacruzramo01b15d32019-07-02 14:37:47 +02001107
37177091c0322024-11-01 08:55:59 +00001108 # password change
1109 if indata.get("password"):
1110 if not session.get("admin_show"):
1111 if not indata.get("system_admin_id"):
1112 if _id != session["user_id"]:
1113 raise EngineException(
1114 "You are not allowed to change other users password",
1115 http_code=HTTPStatus.BAD_REQUEST,
1116 )
1117 if not indata.get("old_password"):
1118 raise EngineException(
1119 "Password change requires old password or admin ID",
1120 http_code=HTTPStatus.BAD_REQUEST,
1121 )
1122
delacruzramo01b15d32019-07-02 14:37:47 +02001123 # user = self.show(session, _id) # Already in 'content'
1124 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +01001125
tiernocf042d32019-06-13 09:06:40 +00001126 mappings_to_add = []
1127 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +01001128
tiernocf042d32019-06-13 09:06:40 +00001129 # remove
1130 for to_remove in indata.get("remove_project_role_mappings", ()):
1131 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001132 if to_remove["project"] in (
1133 mapping["project"],
1134 mapping["project_name"],
1135 ):
1136 if not to_remove.get("role") or to_remove["role"] in (
1137 mapping["role"],
1138 mapping["role_name"],
1139 ):
tiernocf042d32019-06-13 09:06:40 +00001140 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +01001141
tiernocf042d32019-06-13 09:06:40 +00001142 # add
1143 for to_add in indata.get("add_project_role_mappings", ()):
1144 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001145 if to_add["project"] in (
1146 mapping["project"],
1147 mapping["project_name"],
1148 ) and to_add["role"] in (
1149 mapping["role"],
1150 mapping["role_name"],
1151 ):
garciadeblas4568a372021-03-24 09:19:48 +01001152 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001153 mappings_to_remove.remove(mapping)
1154 break # do not add, it is already at user
1155 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001156 pid = self.auth.get_project(to_add["project"])["_id"]
1157 rid = self.auth.get_role(to_add["role"])["_id"]
1158 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001159
1160 # set
1161 if indata.get("project_role_mappings"):
Adurti16e6edd2024-03-25 08:21:36 +00001162 duplicates = []
1163 for pr in indata.get("project_role_mappings"):
1164 if pr not in duplicates:
1165 duplicates.append(pr)
1166 if len(indata.get("project_role_mappings")) > len(duplicates):
1167 raise EngineException(
1168 "Project-role combination should not be repeated",
1169 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1170 )
tiernocf042d32019-06-13 09:06:40 +00001171 for to_set in indata["project_role_mappings"]:
1172 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001173 if to_set["project"] in (
1174 mapping["project"],
1175 mapping["project_name"],
1176 ) and to_set["role"] in (
1177 mapping["role"],
1178 mapping["role_name"],
1179 ):
1180 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001181 mappings_to_remove.remove(mapping)
1182 break # do not add, it is already at user
1183 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001184 pid = self.auth.get_project(to_set["project"])["_id"]
1185 rid = self.auth.get_role(to_set["role"])["_id"]
1186 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001187 for mapping in original_mapping:
1188 for to_set in indata["project_role_mappings"]:
garciadeblas4568a372021-03-24 09:19:48 +01001189 if to_set["project"] in (
1190 mapping["project"],
1191 mapping["project_name"],
1192 ) and to_set["role"] in (
1193 mapping["role"],
1194 mapping["role_name"],
1195 ):
tiernocf042d32019-06-13 09:06:40 +00001196 break
1197 else:
1198 # delete
garciadeblas4568a372021-03-24 09:19:48 +01001199 if mapping not in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001200 mappings_to_remove.append(mapping)
1201
garciadeblas4568a372021-03-24 09:19:48 +01001202 self.auth.update_user(
1203 {
1204 "_id": _id,
1205 "username": indata.get("username"),
1206 "password": indata.get("password"),
selvi.ja9a1fc82022-04-04 06:54:30 +00001207 "old_password": indata.get("old_password"),
garciadeblas4568a372021-03-24 09:19:48 +01001208 "add_project_role_mappings": mappings_to_add,
1209 "remove_project_role_mappings": mappings_to_remove,
garciadeblas6d83f8f2023-06-19 22:34:49 +02001210 "system_admin_id": indata.get("system_admin_id"),
1211 "unlock": indata.get("unlock"),
1212 "renew": indata.get("renew"),
garciadeblasf53612b2024-07-12 14:44:37 +02001213 "session_user": session.get("username"),
jeganbe1a3df2024-06-04 12:05:19 +00001214 "email_id": indata.get("email_id"),
garciadeblas4568a372021-03-24 09:19:48 +01001215 }
1216 )
1217 data_to_send = {"_id": _id, "changes": indata}
agarwalat53471982020-10-08 13:06:14 +00001218 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +00001219
delacruzramo01b15d32019-07-02 14:37:47 +02001220 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001221 except ValidationError as e:
1222 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1223
tiernoc4e07d02020-08-14 14:25:32 +00001224 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001225 """
1226 Get a list of the topic that matches a filter
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 filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +05301229 :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 +01001230 :return: The list, it can be empty if no one match the filter.
1231 """
delacruzramo029405d2019-09-26 10:52:56 +02001232 user_list = self.auth.get_user_list(filter_q)
1233 if not session["allow_show_user_project_role"]:
1234 # Bug 853 - Default filtering
garciadeblas4568a372021-03-24 09:19:48 +01001235 user_list = [
1236 usr for usr in user_list if usr["username"] == session["username"]
1237 ]
delacruzramo029405d2019-09-26 10:52:56 +02001238 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001239
tiernobee3bad2019-12-05 12:26:01 +00001240 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001241 """
1242 Delete item by its internal _id
1243
tierno65ca36d2019-02-12 19:27:52 +01001244 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001245 :param _id: server internal id
1246 :param force: indicates if deletion must be forced in case of conflict
1247 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001248 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001249 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1250 """
tiernocf042d32019-06-13 09:06:40 +00001251 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001252 user = self.auth.get_user(_id)
1253 uid = user["_id"]
1254 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001255 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001256 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +00001257 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001258 return v
1259 return None
1260
1261
1262class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +01001263 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +00001264 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +01001265 schema_new = project_new_schema
1266 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001267
1268 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001269 ProjectTopic.__init__(self, db, fs, msg, auth)
1270 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001271
tierno65ca36d2019-02-12 19:27:52 +01001272 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001273 """
1274 Check that the data to be inserted is valid
1275
tierno65ca36d2019-02-12 19:27:52 +01001276 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001277 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001278 :return: None or raises EngineException
1279 """
tiernocf042d32019-06-13 09:06:40 +00001280 project_name = indata.get("name")
1281 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001282 raise EngineException(
1283 "project name '{}' cannot have an uuid format".format(project_name),
1284 HTTPStatus.UNPROCESSABLE_ENTITY,
1285 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001286
tiernocf042d32019-06-13 09:06:40 +00001287 project_list = self.auth.get_project_list(filter_q={"name": project_name})
1288
1289 if project_list:
garciadeblas4568a372021-03-24 09:19:48 +01001290 raise EngineException(
1291 "project '{}' exists".format(project_name), HTTPStatus.CONFLICT
1292 )
tiernocf042d32019-06-13 09:06:40 +00001293
1294 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1295 """
1296 Check that the data to be edited/uploaded is valid
1297
1298 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1299 :param final_content: data once modified
1300 :param edit_content: incremental data that contains the modifications to apply
1301 :param _id: internal _id
1302 :return: None or raises EngineException
1303 """
1304
1305 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +02001306 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +00001307 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001308 raise EngineException(
1309 "project name '{}' cannot have an uuid format".format(project_name),
1310 HTTPStatus.UNPROCESSABLE_ENTITY,
1311 )
tiernocf042d32019-06-13 09:06:40 +00001312
delacruzramo01b15d32019-07-02 14:37:47 +02001313 if final_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001314 raise EngineException(
1315 "You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT
1316 )
delacruzramo01b15d32019-07-02 14:37:47 +02001317
tiernocf042d32019-06-13 09:06:40 +00001318 # Check that project name is not used, regardless keystone already checks this
garciadeblas4568a372021-03-24 09:19:48 +01001319 if project_name and self.auth.get_project_list(
1320 filter_q={"name": project_name}
1321 ):
1322 raise EngineException(
1323 "project '{}' is already used".format(project_name),
1324 HTTPStatus.CONFLICT,
1325 )
bravofb995ea22021-02-10 10:57:52 -03001326 return final_content
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001327
tiernob4844ab2019-05-23 08:42:12 +00001328 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001329 """
1330 Check if deletion can be done because of dependencies if it is not force. To override
1331
tierno65ca36d2019-02-12 19:27:52 +01001332 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001333 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001334 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001335 :return: None if ok or raises EngineException with the conflict
1336 """
delacruzramo01b15d32019-07-02 14:37:47 +02001337
1338 def check_rw_projects(topic, title, id_field):
1339 for desc in self.db.get_list(topic):
garciadeblas4568a372021-03-24 09:19:48 +01001340 if (
1341 _id
1342 in desc["_admin"]["projects_read"]
1343 + desc["_admin"]["projects_write"]
1344 ):
1345 raise EngineException(
1346 "Project '{}' ({}) is being used by {} '{}'".format(
1347 db_content["name"], _id, title, desc[id_field]
1348 ),
1349 HTTPStatus.CONFLICT,
1350 )
delacruzramo01b15d32019-07-02 14:37:47 +02001351
1352 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +01001353 raise EngineException(
1354 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
1355 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001356
delacruzramo01b15d32019-07-02 14:37:47 +02001357 if db_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001358 raise EngineException(
1359 "You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT
1360 )
delacruzramo01b15d32019-07-02 14:37:47 +02001361
1362 # If any user is using this project, raise CONFLICT exception
1363 if not session["force"]:
1364 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001365 for prm in user.get("project_role_mappings"):
1366 if prm["project"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001367 raise EngineException(
1368 "Project '{}' ({}) is being used by user '{}'".format(
1369 db_content["name"], _id, user["username"]
1370 ),
1371 HTTPStatus.CONFLICT,
1372 )
delacruzramo01b15d32019-07-02 14:37:47 +02001373
1374 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1375 if not session["force"]:
1376 check_rw_projects("vnfds", "VNF Descriptor", "id")
1377 check_rw_projects("nsds", "NS Descriptor", "id")
1378 check_rw_projects("nsts", "NS Template", "id")
1379 check_rw_projects("pdus", "PDU Descriptor", "name")
1380
tierno65ca36d2019-02-12 19:27:52 +01001381 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001382 """
1383 Creates a new entry into the authentication backend.
1384
1385 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1386
1387 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001388 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001389 :param indata: data to be inserted
1390 :param kwargs: used to override the indata descriptor
1391 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001392 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001393 """
1394 try:
1395 content = BaseTopic._remove_envelop(indata)
1396
1397 # Override descriptor with query string kwargs
1398 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001399 content = self._validate_input_new(content, session["force"])
1400 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001401 self.format_on_new(
1402 content, project_id=session["project_id"], make_public=session["public"]
1403 )
garciadeblasb6025472024-08-15 09:50:55 +02001404 self.create_gitname(content, session)
delacruzramo01b15d32019-07-02 14:37:47 +02001405 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001406 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +00001407 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001408 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001409 except ValidationError as e:
1410 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1411
K Sai Kiran57589552021-01-27 21:38:34 +05301412 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001413 """
1414 Get complete information on an topic
1415
tierno65ca36d2019-02-12 19:27:52 +01001416 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001417 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301418 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301419 :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 +01001420 :return: dictionary, raise exception if not found.
1421 """
tiernocf042d32019-06-13 09:06:40 +00001422 # Allow _id to be a name or uuid
1423 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001424 # projects = self.auth.get_project_list(filter_q=filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001425 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001426 if len(projects) == 1:
1427 return projects[0]
1428 elif len(projects) > 1:
1429 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
1430 else:
1431 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
1432
tiernoc4e07d02020-08-14 14:25:32 +00001433 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001434 """
1435 Get a list of the topic that matches a filter
1436
tierno65ca36d2019-02-12 19:27:52 +01001437 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001438 :param filter_q: filter of data to be applied
1439 :return: The list, it can be empty if no one match the filter.
1440 """
delacruzramo029405d2019-09-26 10:52:56 +02001441 project_list = self.auth.get_project_list(filter_q)
1442 if not session["allow_show_user_project_role"]:
1443 # Bug 853 - Default filtering
1444 user = self.auth.get_user(session["username"])
1445 projects = [prm["project"] for prm in user["project_role_mappings"]]
1446 project_list = [proj for proj in project_list if proj["_id"] in projects]
1447 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001448
tiernobee3bad2019-12-05 12:26:01 +00001449 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001450 """
1451 Delete item by its internal _id
1452
tierno65ca36d2019-02-12 19:27:52 +01001453 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001454 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001455 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001456 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001457 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1458 """
tiernocf042d32019-06-13 09:06:40 +00001459 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001460 proj = self.auth.get_project(_id)
1461 pid = proj["_id"]
1462 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001463 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001464 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001465 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001466 return v
1467 return None
1468
tierno4015b472019-06-10 13:57:29 +00001469 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1470 """
1471 Updates a project entry.
1472
1473 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1474 :param _id:
1475 :param indata: data to be inserted
1476 :param kwargs: used to override the indata descriptor
1477 :param content:
1478 :return: _id: identity of the inserted data.
1479 """
1480 indata = self._remove_envelop(indata)
1481
1482 # Override descriptor with query string kwargs
1483 if kwargs:
1484 BaseTopic._update_input_with_kwargs(indata, kwargs)
1485 try:
tierno4015b472019-06-10 13:57:29 +00001486 if not content:
1487 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001488 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001489 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001490 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001491 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001492 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001493 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001494 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1495 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001496 except ValidationError as e:
1497 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1498
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001499
1500class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001501 topic = "roles"
garciadeblas4568a372021-03-24 09:19:48 +01001502 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001503 schema_new = roles_new_schema
1504 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001505 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001506
tierno9e87a7f2020-03-23 09:24:10 +00001507 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001508 BaseTopic.__init__(self, db, fs, msg, auth)
1509 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001510 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001511 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001512
1513 @staticmethod
1514 def validate_role_definition(operations, role_definitions):
1515 """
1516 Validates the role definition against the operations defined in
1517 the resources to operations files.
1518
1519 :param operations: operations list
1520 :param role_definitions: role definition to test
1521 :return: None if ok, raises ValidationError exception on error
1522 """
tierno1f029d82019-06-13 22:37:04 +00001523 if not role_definitions.get("permissions"):
1524 return
1525 ignore_fields = ["admin", "default"]
1526 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001527 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001528 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001529 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001530 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001531
garciadeblas4568a372021-03-24 09:19:48 +01001532 match = next(
1533 (
1534 op
1535 for op in operations
1536 if op == role_def or op.startswith(role_def + ":")
1537 ),
1538 None,
1539 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001540
tierno97639b42020-08-04 12:48:15 +00001541 if not match:
tierno1f029d82019-06-13 22:37:04 +00001542 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001543
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001544 def _validate_input_new(self, input, force=False):
1545 """
1546 Validates input user content for a new entry.
1547
1548 :param input: user input content for the new topic
1549 :param force: may be used for being more tolerant
1550 :return: The same input content, or a changed version of it.
1551 """
1552 if self.schema_new:
1553 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001554 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001555
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001556 return input
1557
Frank Brydendeba68e2020-07-27 13:55:11 +00001558 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001559 """
1560 Validates input user content for updating an entry.
1561
1562 :param input: user input content for the new topic
1563 :param force: may be used for being more tolerant
1564 :return: The same input content, or a changed version of it.
1565 """
1566 if self.schema_edit:
1567 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001568 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001569
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001570 return input
1571
tierno65ca36d2019-02-12 19:27:52 +01001572 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001573 """
1574 Check that the data to be inserted is valid
1575
tierno65ca36d2019-02-12 19:27:52 +01001576 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001577 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001578 :return: None or raises EngineException
1579 """
delacruzramo79e40f42019-10-10 16:36:40 +02001580 # check name is not uuid
1581 role_name = indata.get("name")
1582 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001583 raise EngineException(
1584 "role name '{}' cannot have an uuid format".format(role_name),
1585 HTTPStatus.UNPROCESSABLE_ENTITY,
1586 )
tierno1f029d82019-06-13 22:37:04 +00001587 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001588 name = indata["name"]
1589 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1590 if self.auth.get_role_list({"name": name}):
garciadeblas4568a372021-03-24 09:19:48 +01001591 raise EngineException(
1592 "role name '{}' exists".format(name), HTTPStatus.CONFLICT
1593 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001594
tierno65ca36d2019-02-12 19:27:52 +01001595 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001596 """
1597 Check that the data to be edited/uploaded is valid
1598
tierno65ca36d2019-02-12 19:27:52 +01001599 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001600 :param final_content: data once modified
1601 :param edit_content: incremental data that contains the modifications to apply
1602 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001603 :return: None or raises EngineException
1604 """
tierno1f029d82019-06-13 22:37:04 +00001605 if "default" not in final_content["permissions"]:
1606 final_content["permissions"]["default"] = False
1607 if "admin" not in final_content["permissions"]:
1608 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001609
delacruzramo79e40f42019-10-10 16:36:40 +02001610 # check name is not uuid
1611 role_name = edit_content.get("name")
1612 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001613 raise EngineException(
1614 "role name '{}' cannot have an uuid format".format(role_name),
1615 HTTPStatus.UNPROCESSABLE_ENTITY,
1616 )
delacruzramo79e40f42019-10-10 16:36:40 +02001617
1618 # Check renaming of admin roles
1619 role = self.auth.get_role(_id)
1620 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001621 raise EngineException(
1622 "You cannot rename role '{}'".format(role["name"]),
1623 http_code=HTTPStatus.FORBIDDEN,
1624 )
delacruzramo79e40f42019-10-10 16:36:40 +02001625
tierno1f029d82019-06-13 22:37:04 +00001626 # check name not exists
1627 if "name" in edit_content:
1628 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001629 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1630 roles = self.auth.get_role_list({"name": role_name})
1631 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
garciadeblas4568a372021-03-24 09:19:48 +01001632 raise EngineException(
1633 "role name '{}' exists".format(role_name), HTTPStatus.CONFLICT
1634 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001635
bravofb995ea22021-02-10 10:57:52 -03001636 return final_content
1637
tiernob4844ab2019-05-23 08:42:12 +00001638 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001639 """
1640 Check if deletion can be done because of dependencies if it is not force. To override
1641
tierno65ca36d2019-02-12 19:27:52 +01001642 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001643 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001644 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001645 :return: None if ok or raises EngineException with the conflict
1646 """
delacruzramo01b15d32019-07-02 14:37:47 +02001647 role = self.auth.get_role(_id)
1648 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001649 raise EngineException(
1650 "You cannot delete role '{}'".format(role["name"]),
1651 http_code=HTTPStatus.FORBIDDEN,
1652 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001653
delacruzramo01b15d32019-07-02 14:37:47 +02001654 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001655 if not session["force"]:
1656 for user in self.auth.get_user_list():
1657 for prm in user.get("project_role_mappings"):
1658 if prm["role"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001659 raise EngineException(
1660 "Role '{}' ({}) is being used by user '{}'".format(
1661 role["name"], _id, user["username"]
1662 ),
1663 HTTPStatus.CONFLICT,
1664 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001665
1666 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +01001667 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001668 """
1669 Modifies content descriptor to include _admin
1670
1671 :param content: descriptor to be modified
1672 :param project_id: if included, it add project read/write permissions
1673 :param make_public: if included it is generated as public for reading.
1674 :return: None, but content is modified
1675 """
1676 now = time()
1677 if "_admin" not in content:
1678 content["_admin"] = {}
1679 if not content["_admin"].get("created"):
1680 content["_admin"]["created"] = now
1681 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001682
tierno1f029d82019-06-13 22:37:04 +00001683 if "permissions" not in content:
1684 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001685
tierno1f029d82019-06-13 22:37:04 +00001686 if "default" not in content["permissions"]:
1687 content["permissions"]["default"] = False
1688 if "admin" not in content["permissions"]:
1689 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001690
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001691 @staticmethod
1692 def format_on_edit(final_content, edit_content):
1693 """
1694 Modifies final_content descriptor to include the modified date.
1695
1696 :param final_content: final descriptor generated
1697 :param edit_content: alterations to be include
1698 :return: None, but final_content is modified
1699 """
delacruzramo01b15d32019-07-02 14:37:47 +02001700 if "_admin" in final_content:
1701 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001702
tierno1f029d82019-06-13 22:37:04 +00001703 if "permissions" not in final_content:
1704 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001705
tierno1f029d82019-06-13 22:37:04 +00001706 if "default" not in final_content["permissions"]:
1707 final_content["permissions"]["default"] = False
1708 if "admin" not in final_content["permissions"]:
1709 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001710 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001711
K Sai Kiran57589552021-01-27 21:38:34 +05301712 def show(self, session, _id, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001713 """
1714 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001715
delacruzramo01b15d32019-07-02 14:37:47 +02001716 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1717 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301718 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301719 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001720 :return: dictionary, raise exception if not found.
1721 """
1722 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001723 # roles = self.auth.get_role_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001724 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001725 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001726 raise AuthconnNotFoundException(
1727 "Not found any role with filter {}".format(filter_q)
1728 )
delacruzramo01b15d32019-07-02 14:37:47 +02001729 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001730 raise AuthconnConflictException(
1731 "Found more than one role with filter {}".format(filter_q)
1732 )
delacruzramo01b15d32019-07-02 14:37:47 +02001733 return roles[0]
1734
tiernoc4e07d02020-08-14 14:25:32 +00001735 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001736 """
1737 Get a list of the topic that matches a filter
1738
1739 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1740 :param filter_q: filter of data to be applied
1741 :return: The list, it can be empty if no one match the filter.
1742 """
delacruzramo029405d2019-09-26 10:52:56 +02001743 role_list = self.auth.get_role_list(filter_q)
1744 if not session["allow_show_user_project_role"]:
1745 # Bug 853 - Default filtering
1746 user = self.auth.get_user(session["username"])
1747 roles = [prm["role"] for prm in user["project_role_mappings"]]
1748 role_list = [role for role in role_list if role["_id"] in roles]
1749 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001750
tierno65ca36d2019-02-12 19:27:52 +01001751 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001752 """
1753 Creates a new entry into database.
1754
1755 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001756 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001757 :param indata: data to be inserted
1758 :param kwargs: used to override the indata descriptor
1759 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001760 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001761 """
1762 try:
tierno1f029d82019-06-13 22:37:04 +00001763 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001764
1765 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001766 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001767 content = self._validate_input_new(content, session["force"])
1768 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001769 self.format_on_new(
1770 content, project_id=session["project_id"], make_public=session["public"]
1771 )
delacruzramo01b15d32019-07-02 14:37:47 +02001772 # role_name = content["name"]
1773 rid = self.auth.create_role(content)
1774 content["_id"] = rid
1775 # _id = self.db.create(self.topic, content)
1776 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001777 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001778 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001779 except ValidationError as e:
1780 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1781
tiernobee3bad2019-12-05 12:26:01 +00001782 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001783 """
1784 Delete item by its internal _id
1785
tierno65ca36d2019-02-12 19:27:52 +01001786 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001787 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001788 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001789 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001790 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1791 """
delacruzramo01b15d32019-07-02 14:37:47 +02001792 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1793 roles = self.auth.get_role_list(filter_q)
1794 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001795 raise AuthconnNotFoundException(
1796 "Not found any role with filter {}".format(filter_q)
1797 )
delacruzramo01b15d32019-07-02 14:37:47 +02001798 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001799 raise AuthconnConflictException(
1800 "Found more than one role with filter {}".format(filter_q)
1801 )
delacruzramo01b15d32019-07-02 14:37:47 +02001802 rid = roles[0]["_id"]
1803 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001804 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001805 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001806 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001807 v = self.auth.delete_role(rid)
1808 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001809 return v
1810 return None
1811
tierno65ca36d2019-02-12 19:27:52 +01001812 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001813 """
1814 Updates a role entry.
1815
tierno65ca36d2019-02-12 19:27:52 +01001816 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001817 :param _id:
1818 :param indata: data to be inserted
1819 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001820 :param content:
1821 :return: _id: identity of the inserted data.
1822 """
delacruzramo01b15d32019-07-02 14:37:47 +02001823 if kwargs:
1824 self._update_input_with_kwargs(indata, kwargs)
1825 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001826 if not content:
1827 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001828 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001829 deep_update_rfc7396(content, indata)
bravofb995ea22021-02-10 10:57:52 -03001830 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001831 self.format_on_edit(content, indata)
1832 self.auth.update_role(content)
1833 except ValidationError as e:
1834 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)