blob: 9ecb61bde2acba2abb48d611b2beef1fdf3c965e [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
17from uuid import uuid4
18from hashlib import sha256
19from http import HTTPStatus
Eduardo Sousa5c01e192019-05-08 02:35:47 +010020from time import time
tierno23acf402019-08-28 13:36:34 +000021from osm_nbi.validation import user_new_schema, user_edit_schema, project_new_schema, project_edit_schema, \
22 vim_account_new_schema, vim_account_edit_schema, sdn_new_schema, sdn_edit_schema, \
23 wim_account_new_schema, wim_account_edit_schema, roles_new_schema, roles_edit_schema, \
delacruzramofe598fe2019-10-23 18:25:11 +020024 k8scluster_new_schema, k8scluster_edit_schema, k8srepo_new_schema, k8srepo_edit_schema, \
tierno23acf402019-08-28 13:36:34 +000025 validate_input, ValidationError, is_valid_uuid # To check that User/Project Names don't look like UUIDs
26from osm_nbi.base_topic import BaseTopic, EngineException
27from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020028from osm_common.dbbase import deep_update_rfc7396
tiernob24258a2018-10-04 18:39:49 +020029
30__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31
32
33class UserTopic(BaseTopic):
34 topic = "users"
35 topic_msg = "users"
36 schema_new = user_new_schema
37 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010038 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020039
delacruzramo32bab472019-09-13 12:24:22 +020040 def __init__(self, db, fs, msg, auth):
41 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020042
43 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010044 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020045 """
46 Generates a filter dictionary for querying database users.
47 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010048 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020049 :return:
50 """
51 if session["admin"]: # allows all
52 return {}
53 else:
54 return {"username": session["username"]}
55
tierno65ca36d2019-02-12 19:27:52 +010056 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020057 # check username not exists
58 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
59 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
60 # check projects
tierno65ca36d2019-02-12 19:27:52 +010061 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020062 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020063 # To allow project addressing by Name as well as ID
64 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
65 fail_on_more=False):
66 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
tiernob24258a2018-10-04 18:39:49 +020067
tiernob4844ab2019-05-23 08:42:12 +000068 def check_conflict_on_del(self, session, _id, db_content):
69 """
70 Check if deletion can be done because of dependencies if it is not force. To override
71 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
72 :param _id: internal _id
73 :param db_content: The database content of this item _id
74 :return: None if ok or raises EngineException with the conflict
75 """
tiernob24258a2018-10-04 18:39:49 +020076 if _id == session["username"]:
77 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
78
79 @staticmethod
80 def format_on_new(content, project_id=None, make_public=False):
81 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +020082 # Removed so that the UUID is kept, to allow User Name modification
83 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +020084 salt = uuid4().hex
85 content["_admin"]["salt"] = salt
86 if content.get("password"):
87 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +010088 if content.get("project_role_mappings"):
delacruzramo01b15d32019-07-02 14:37:47 +020089 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
Eduardo Sousa339ed782019-05-28 14:25:00 +010090
91 if content.get("projects"):
92 content["projects"] += projects
93 else:
94 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +020095
96 @staticmethod
97 def format_on_edit(final_content, edit_content):
98 BaseTopic.format_on_edit(final_content, edit_content)
99 if edit_content.get("password"):
100 salt = uuid4().hex
101 final_content["_admin"]["salt"] = salt
102 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
103 salt.encode('utf-8')).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000104 return None
tiernob24258a2018-10-04 18:39:49 +0200105
tierno65ca36d2019-02-12 19:27:52 +0100106 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200107 if not session["admin"]:
108 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200109 # Names that look like UUIDs are not allowed
110 name = (indata if indata else kwargs).get("username")
111 if is_valid_uuid(name):
112 raise EngineException("Usernames that look like UUIDs are not allowed",
113 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100114 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200115
tierno65ca36d2019-02-12 19:27:52 +0100116 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200117 if not session["admin"]:
118 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200119 # Names that look like UUIDs are not allowed
120 name = indata["username"] if indata else kwargs["username"]
121 if is_valid_uuid(name):
122 raise EngineException("Usernames that look like UUIDs are not allowed",
123 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100124 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200125
126
127class ProjectTopic(BaseTopic):
128 topic = "projects"
129 topic_msg = "projects"
130 schema_new = project_new_schema
131 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100132 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200133
delacruzramo32bab472019-09-13 12:24:22 +0200134 def __init__(self, db, fs, msg, auth):
135 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200136
tierno65ca36d2019-02-12 19:27:52 +0100137 @staticmethod
138 def _get_project_filter(session):
139 """
140 Generates a filter dictionary for querying database users.
141 Current policy is admin can show all, non admin, only its own user.
142 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
143 :return:
144 """
145 if session["admin"]: # allows all
146 return {}
147 else:
148 return {"_id.cont": session["project_id"]}
149
150 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200151 if not indata.get("name"):
152 raise EngineException("missing 'name'")
153 # check name not exists
154 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
155 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
156
157 @staticmethod
158 def format_on_new(content, project_id=None, make_public=False):
159 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200160 # Removed so that the UUID is kept, to allow Project Name modification
161 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200162
tiernob4844ab2019-05-23 08:42:12 +0000163 def check_conflict_on_del(self, session, _id, db_content):
164 """
165 Check if deletion can be done because of dependencies if it is not force. To override
166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
167 :param _id: internal _id
168 :param db_content: The database content of this item _id
169 :return: None if ok or raises EngineException with the conflict
170 """
tierno65ca36d2019-02-12 19:27:52 +0100171 if _id in session["project_id"]:
tiernob24258a2018-10-04 18:39:49 +0200172 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
tierno65ca36d2019-02-12 19:27:52 +0100173 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200174 return
175 _filter = {"projects": _id}
176 if self.db.get_list("users", _filter):
177 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
178
tierno65ca36d2019-02-12 19:27:52 +0100179 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200180 if not session["admin"]:
181 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200182 # Names that look like UUIDs are not allowed
183 name = (indata if indata else kwargs).get("name")
184 if is_valid_uuid(name):
185 raise EngineException("Project names that look like UUIDs are not allowed",
186 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100187 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200188
tierno65ca36d2019-02-12 19:27:52 +0100189 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200190 if not session["admin"]:
191 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200192 # Names that look like UUIDs are not allowed
193 name = indata["name"] if indata else kwargs["name"]
194 if is_valid_uuid(name):
195 raise EngineException("Project names that look like UUIDs are not allowed",
196 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100197 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200198
199
tiernobdebce92019-07-01 15:36:49 +0000200class CommonVimWimSdn(BaseTopic):
201 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
tierno468aa242019-08-01 16:35:04 +0000202 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
tiernobdebce92019-07-01 15:36:49 +0000203 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200204
tiernobdebce92019-07-01 15:36:49 +0000205 @staticmethod
206 def _create_operation(op_type, params=None):
207 """
208 Creates a dictionary with the information to an operation, similar to ns-lcm-op
209 :param op_type: can be create, edit, delete
210 :param params: operation input parameters
211 :return: new dictionary with
212 """
213 now = time()
214 return {
215 "lcmOperationType": op_type,
216 "operationState": "PROCESSING",
217 "startTime": now,
218 "statusEnteredTime": now,
219 "detailed-status": "",
220 "operationParams": params,
221 }
tiernob24258a2018-10-04 18:39:49 +0200222
tierno65ca36d2019-02-12 19:27:52 +0100223 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000224 """
225 Check that the data to be inserted is valid. It is checked that name is unique
226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
227 :param indata: data to be inserted
228 :return: None or raises EngineException
229 """
tiernob24258a2018-10-04 18:39:49 +0200230 self.check_unique_name(session, indata["name"], _id=None)
231
tierno65ca36d2019-02-12 19:27:52 +0100232 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000233 """
234 Check that the data to be edited/uploaded is valid. It is checked that name is unique
235 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
236 :param final_content: data once modified. This method may change it.
237 :param edit_content: incremental data that contains the modifications to apply
238 :param _id: internal _id
239 :return: None or raises EngineException
240 """
tierno65ca36d2019-02-12 19:27:52 +0100241 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200242 self.check_unique_name(session, edit_content["name"], _id=_id)
243
tiernobdebce92019-07-01 15:36:49 +0000244 def format_on_edit(self, final_content, edit_content):
245 """
246 Modifies final_content inserting admin information upon edition
247 :param final_content: final content to be stored at database
248 :param edit_content: user requested update content
249 :return: operation id
250 """
delacruzramofe598fe2019-10-23 18:25:11 +0200251 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000252
tierno92c1c7d2018-11-12 15:22:37 +0100253 # encrypt passwords
254 schema_version = final_content.get("schema_version")
255 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000256 if edit_content.get(self.password_to_encrypt):
257 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
258 schema_version=schema_version,
259 salt=final_content["_id"])
tierno468aa242019-08-01 16:35:04 +0000260 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
261 if edit_content.get("config") and config_to_encrypt_keys:
262
263 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100264 if edit_content["config"].get(p):
265 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
tiernobdebce92019-07-01 15:36:49 +0000266 schema_version=schema_version,
267 salt=final_content["_id"])
268
269 # create edit operation
270 final_content["_admin"]["operations"].append(self._create_operation("edit"))
271 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
tierno92c1c7d2018-11-12 15:22:37 +0100272
273 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000274 """
275 Modifies content descriptor to include _admin and insert create operation
276 :param content: descriptor to be modified
277 :param project_id: if included, it add project read/write permissions. Can be None or a list
278 :param make_public: if included it is generated as public for reading.
279 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
280 """
281 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000282 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100283
284 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000285 if content.get(self.password_to_encrypt):
286 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
287 schema_version=schema_version,
288 salt=content["_id"])
tierno468aa242019-08-01 16:35:04 +0000289 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
290 if content.get("config") and config_to_encrypt_keys:
291 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100292 if content["config"].get(p):
tiernobdebce92019-07-01 15:36:49 +0000293 content["config"][p] = self.db.encrypt(content["config"][p],
294 schema_version=schema_version,
tierno92c1c7d2018-11-12 15:22:37 +0100295 salt=content["_id"])
296
tiernob24258a2018-10-04 18:39:49 +0200297 content["_admin"]["operationalState"] = "PROCESSING"
298
tiernobdebce92019-07-01 15:36:49 +0000299 # create operation
300 content["_admin"]["operations"] = [self._create_operation("create")]
301 content["_admin"]["current_operation"] = None
302
303 return "{}:0".format(content["_id"])
304
tiernobee3bad2019-12-05 12:26:01 +0000305 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200306 """
307 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100308 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200309 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200310 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000311 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000312 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200313 """
tiernobdebce92019-07-01 15:36:49 +0000314
315 filter_q = self._get_project_filter(session)
316 filter_q["_id"] = _id
317 db_content = self.db.get_one(self.topic, filter_q)
318
319 self.check_conflict_on_del(session, _id, db_content)
320 if dry_run:
321 return None
322
tiernof5f2e3f2020-03-23 14:42:10 +0000323 # remove reference from project_read if there are more projects referencing it. If it last one,
324 # do not remove reference, but order via kafka to delete it
325 if session["project_id"] and session["project_id"]:
326 other_projects_referencing = next((p for p in db_content["_admin"]["projects_read"]
327 if p not in session["project_id"]), None)
tiernobdebce92019-07-01 15:36:49 +0000328
tiernof5f2e3f2020-03-23 14:42:10 +0000329 # check if there are projects referencing it (apart from ANY, that means, public)....
330 if other_projects_referencing:
331 # remove references but not delete
332 update_dict_pull = {"_admin.projects_read.{}".format(p): None for p in session["project_id"]}
333 update_dict_pull.update({"_admin.projects_write.{}".format(p): None for p in session["project_id"]})
334 self.db.set_one(self.topic, filter_q, update_dict=None, pull=update_dict_pull)
335 return None
336 else:
337 can_write = next((p for p in db_content["_admin"]["projects_write"] if p == "ANY" or
338 p in session["project_id"]), None)
339 if not can_write:
340 raise EngineException("You have not write permission to delete it",
341 http_code=HTTPStatus.UNAUTHORIZED)
tiernobdebce92019-07-01 15:36:49 +0000342
343 # It must be deleted
344 if session["force"]:
345 self.db.del_one(self.topic, {"_id": _id})
346 op_id = None
tiernobee3bad2019-12-05 12:26:01 +0000347 self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000348 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000349 update_dict = {"_admin.to_delete": True}
tiernobdebce92019-07-01 15:36:49 +0000350 self.db.set_one(self.topic, {"_id": _id},
351 update_dict=update_dict,
352 push={"_admin.operations": self._create_operation("delete")}
353 )
354 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
355 # so the -1 is not needed
356 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
tiernobee3bad2019-12-05 12:26:01 +0000357 self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000358 return op_id
tiernob24258a2018-10-04 18:39:49 +0200359
360
tiernobdebce92019-07-01 15:36:49 +0000361class VimAccountTopic(CommonVimWimSdn):
362 topic = "vim_accounts"
363 topic_msg = "vim_account"
364 schema_new = vim_account_new_schema
365 schema_edit = vim_account_edit_schema
366 multiproject = True
367 password_to_encrypt = "vim_password"
tierno468aa242019-08-01 16:35:04 +0000368 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
369 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
tiernobdebce92019-07-01 15:36:49 +0000370
delacruzramo35c998b2019-11-21 11:09:16 +0100371 def check_conflict_on_del(self, session, _id, db_content):
372 """
373 Check if deletion can be done because of dependencies if it is not force. To override
374 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
375 :param _id: internal _id
376 :param db_content: The database content of this item _id
377 :return: None if ok or raises EngineException with the conflict
378 """
379 if session["force"]:
380 return
381 # check if used by VNF
382 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
383 raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
384 super().check_conflict_on_del(session, _id, db_content)
385
tiernobdebce92019-07-01 15:36:49 +0000386
387class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000388 topic = "wim_accounts"
389 topic_msg = "wim_account"
390 schema_new = wim_account_new_schema
391 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100392 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000393 password_to_encrypt = "wim_password"
tierno468aa242019-08-01 16:35:04 +0000394 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000395
396
tiernobdebce92019-07-01 15:36:49 +0000397class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200398 topic = "sdns"
399 topic_msg = "sdn"
400 schema_new = sdn_new_schema
401 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100402 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000403 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000404 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100405
tierno7adaeb02019-12-17 16:46:12 +0000406 def _obtain_url(self, input, create):
407 if input.get("ip") or input.get("port"):
408 if not input.get("ip") or not input.get("port") or input.get('url'):
409 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
410 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
411 del input["ip"]
412 del input["port"]
413 elif create and not input.get('url'):
414 raise ValidationError("You must provide 'url'")
415 return input
416
417 def _validate_input_new(self, input, force=False):
418 input = super()._validate_input_new(input, force)
419 return self._obtain_url(input, True)
420
421 def _validate_input_edit(self, input, force=False):
422 input = super()._validate_input_edit(input, force)
423 return self._obtain_url(input, False)
424
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100425
delacruzramofe598fe2019-10-23 18:25:11 +0200426class K8sClusterTopic(CommonVimWimSdn):
427 topic = "k8sclusters"
428 topic_msg = "k8scluster"
429 schema_new = k8scluster_new_schema
430 schema_edit = k8scluster_edit_schema
431 multiproject = True
432 password_to_encrypt = None
433 config_to_encrypt = {}
434
435 def format_on_new(self, content, project_id=None, make_public=False):
436 oid = super().format_on_new(content, project_id, make_public)
437 self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
438 schema_version=content["schema_version"], salt=content["_id"])
delacruzramoc2d5fc62020-02-05 11:50:21 +0000439 # Add Helm/Juju Repo lists
440 repos = {"helm-chart": [], "juju-bundle": []}
441 for proj in content["_admin"]["projects_read"]:
442 if proj != 'ANY':
443 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
444 if repo["_id"] not in repos[repo["type"]]:
445 repos[repo["type"]].append(repo["_id"])
446 for k in repos:
447 content["_admin"][k.replace('-', '_')+"_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200448 return oid
449
450 def format_on_edit(self, final_content, edit_content):
451 if final_content.get("schema_version") and edit_content.get("credentials"):
452 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
453 schema_version=final_content["schema_version"], salt=final_content["_id"])
454 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
455 oid = super().format_on_edit(final_content, edit_content)
456 return oid
457
delacruzramoc2d5fc62020-02-05 11:50:21 +0000458 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
459 super(CommonVimWimSdn, self).check_conflict_on_edit(session, final_content, edit_content, _id)
460 super().check_conflict_on_edit(session, final_content, edit_content, _id)
461 # Update Helm/Juju Repo lists
462 repos = {"helm-chart": [], "juju-bundle": []}
463 for proj in session.get("set_project", []):
464 if proj != 'ANY':
465 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
466 if repo["_id"] not in repos[repo["type"]]:
467 repos[repo["type"]].append(repo["_id"])
468 for k in repos:
469 rlist = k.replace('-', '_') + "_repos"
470 if rlist not in final_content["_admin"]:
471 final_content["_admin"][rlist] = []
472 final_content["_admin"][rlist] += repos[k]
473
delacruzramofe598fe2019-10-23 18:25:11 +0200474
475class K8sRepoTopic(CommonVimWimSdn):
476 topic = "k8srepos"
477 topic_msg = "k8srepo"
478 schema_new = k8srepo_new_schema
479 schema_edit = k8srepo_edit_schema
480 multiproject = True
481 password_to_encrypt = None
482 config_to_encrypt = {}
483
delacruzramoc2d5fc62020-02-05 11:50:21 +0000484 def format_on_new(self, content, project_id=None, make_public=False):
485 oid = super().format_on_new(content, project_id, make_public)
486 # Update Helm/Juju Repo lists
487 repo_list = content["type"].replace('-', '_')+"_repos"
488 for proj in content["_admin"]["projects_read"]:
489 if proj != 'ANY':
490 self.db.set_list("k8sclusters",
491 {"_admin.projects_read": proj, "_admin."+repo_list+".ne": content["_id"]}, {},
492 push={"_admin."+repo_list: content["_id"]})
493 return oid
494
495 def delete(self, session, _id, dry_run=False, not_send_msg=None):
496 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
497 oid = super().delete(session, _id, dry_run, not_send_msg)
498 if oid:
499 # Remove from Helm/Juju Repo lists
500 repo_list = type.replace('-', '_') + "_repos"
501 self.db.set_list("k8sclusters", {"_admin."+repo_list: _id}, {}, pull={"_admin."+repo_list: _id})
502 return oid
503
delacruzramofe598fe2019-10-23 18:25:11 +0200504
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100505class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100506 # topic = "users"
507 # topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100508 schema_new = user_new_schema
509 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100510
511 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200512 UserTopic.__init__(self, db, fs, msg, auth)
513 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100514
tierno65ca36d2019-02-12 19:27:52 +0100515 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100516 """
517 Check that the data to be inserted is valid
518
tierno65ca36d2019-02-12 19:27:52 +0100519 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100520 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100521 :return: None or raises EngineException
522 """
523 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000524 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200525 raise EngineException("username '{}' cannot have a uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000526 HTTPStatus.UNPROCESSABLE_ENTITY)
527
528 # Check that username is not used, regardless keystone already checks this
529 if self.auth.get_user_list(filter_q={"name": username}):
530 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100531
Eduardo Sousa339ed782019-05-28 14:25:00 +0100532 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000533 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200534 role = self.auth.get_role_list({"name": "project_admin"})
535 if not role:
536 role = self.auth.get_role_list()
537 if not role:
538 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
539 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000540 if not indata.get("project_role_mappings"):
541 indata["project_role_mappings"] = []
542 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200543 pid = self.auth.get_project(project)["_id"]
544 prm = {"project": pid, "role": rid}
545 if prm not in indata["project_role_mappings"]:
546 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000547 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
548 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100549
tierno65ca36d2019-02-12 19:27:52 +0100550 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100551 """
552 Check that the data to be edited/uploaded is valid
553
tierno65ca36d2019-02-12 19:27:52 +0100554 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100555 :param final_content: data once modified
556 :param edit_content: incremental data that contains the modifications to apply
557 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100558 :return: None or raises EngineException
559 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100560
tiernocf042d32019-06-13 09:06:40 +0000561 if "username" in edit_content:
562 username = edit_content.get("username")
563 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200564 raise EngineException("username '{}' cannot have an uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000565 HTTPStatus.UNPROCESSABLE_ENTITY)
566
567 # Check that username is not used, regardless keystone already checks this
568 if self.auth.get_user_list(filter_q={"name": username}):
569 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
570
571 if final_content["username"] == "admin":
572 for mapping in edit_content.get("remove_project_role_mappings", ()):
573 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
574 # TODO make this also available for project id and role id
575 raise EngineException("You cannot remove system_admin role from admin user",
576 http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100577
tiernob4844ab2019-05-23 08:42:12 +0000578 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100579 """
580 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100581 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100582 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000583 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100584 :return: None if ok or raises EngineException with the conflict
585 """
tiernocf042d32019-06-13 09:06:40 +0000586 if db_content["username"] == session["username"]:
587 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200588 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100589
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100590 @staticmethod
591 def format_on_show(content):
592 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100593 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100594 metadata from the role definition.
595 """
596 project_role_mappings = []
597
delacruzramo01b15d32019-07-02 14:37:47 +0200598 if "projects" in content:
599 for project in content["projects"]:
600 for role in project["roles"]:
601 project_role_mappings.append({"project": project["_id"],
602 "project_name": project["name"],
603 "role": role["_id"],
604 "role_name": role["name"]})
605 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100606 content["project_role_mappings"] = project_role_mappings
607
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100608 return content
609
tierno65ca36d2019-02-12 19:27:52 +0100610 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100611 """
612 Creates a new entry into the authentication backend.
613
614 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
615
616 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100617 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100618 :param indata: data to be inserted
619 :param kwargs: used to override the indata descriptor
620 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200621 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100622 """
623 try:
624 content = BaseTopic._remove_envelop(indata)
625
626 # Override descriptor with query string kwargs
627 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100628 content = self._validate_input_new(content, session["force"])
629 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000630 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200631 now = time()
632 content["_admin"] = {"created": now, "modified": now}
633 prms = []
634 for prm in content.get("project_role_mappings", []):
635 proj = self.auth.get_project(prm["project"], not session["force"])
636 role = self.auth.get_role(prm["role"], not session["force"])
637 pid = proj["_id"] if proj else None
638 rid = role["_id"] if role else None
639 prl = {"project": pid, "role": rid}
640 if prl not in prms:
641 prms.append(prl)
642 content["project_role_mappings"] = prms
643 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
644 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100645
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100646 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000647 # del content["password"]
tiernobee3bad2019-12-05 12:26:01 +0000648 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +0200649 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100650 except ValidationError as e:
651 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
652
653 def show(self, session, _id):
654 """
655 Get complete information on an topic
656
tierno65ca36d2019-02-12 19:27:52 +0100657 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100658 :param _id: server internal id
659 :return: dictionary, raise exception if not found.
660 """
tiernocf042d32019-06-13 09:06:40 +0000661 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000662 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200663 # users = self.auth.get_user_list(filter_q)
664 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100665 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000666 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100667 elif len(users) > 1:
668 raise EngineException("Too many users found", HTTPStatus.CONFLICT)
669 else:
670 raise EngineException("User not found", HTTPStatus.NOT_FOUND)
671
tierno65ca36d2019-02-12 19:27:52 +0100672 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100673 """
674 Updates an user entry.
675
tierno65ca36d2019-02-12 19:27:52 +0100676 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100677 :param _id:
678 :param indata: data to be inserted
679 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100680 :param content:
681 :return: _id: identity of the inserted data.
682 """
683 indata = self._remove_envelop(indata)
684
685 # Override descriptor with query string kwargs
686 if kwargs:
687 BaseTopic._update_input_with_kwargs(indata, kwargs)
688 try:
tierno65ca36d2019-02-12 19:27:52 +0100689 indata = self._validate_input_edit(indata, force=session["force"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100690
691 if not content:
692 content = self.show(session, _id)
tierno65ca36d2019-02-12 19:27:52 +0100693 self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000694 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100695
delacruzramo01b15d32019-07-02 14:37:47 +0200696 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
697 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
698 indata.get("projects") or indata.get("add_projects")):
tiernocf042d32019-06-13 09:06:40 +0000699 return _id
delacruzramo01b15d32019-07-02 14:37:47 +0200700 if indata.get("project_role_mappings") \
701 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
tiernocf042d32019-06-13 09:06:40 +0000702 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
703 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
Eduardo Sousa44603902019-06-04 08:10:32 +0100704
delacruzramo01b15d32019-07-02 14:37:47 +0200705 if indata.get("projects") or indata.get("add_projects"):
706 role = self.auth.get_role_list({"name": "project_admin"})
707 if not role:
708 role = self.auth.get_role_list()
709 if not role:
710 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
711 .format(content["username"]))
712 rid = role[0]["_id"]
713 if "add_project_role_mappings" not in indata:
714 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +0000715 if "remove_project_role_mappings" not in indata:
716 indata["remove_project_role_mappings"] = []
717 if isinstance(indata.get("projects"), dict):
718 # backward compatible
719 for k, v in indata["projects"].items():
720 if k.startswith("$") and v is None:
721 indata["remove_project_role_mappings"].append({"project": k[1:]})
722 elif k.startswith("$+"):
723 indata["add_project_role_mappings"].append({"project": v, "role": rid})
724 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +0200725 for proj in indata.get("projects", []) + indata.get("add_projects", []):
726 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
727
728 # user = self.show(session, _id) # Already in 'content'
729 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100730
tiernocf042d32019-06-13 09:06:40 +0000731 mappings_to_add = []
732 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +0100733
tiernocf042d32019-06-13 09:06:40 +0000734 # remove
735 for to_remove in indata.get("remove_project_role_mappings", ()):
736 for mapping in original_mapping:
737 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
738 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
739 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +0100740
tiernocf042d32019-06-13 09:06:40 +0000741 # add
742 for to_add in indata.get("add_project_role_mappings", ()):
743 for mapping in original_mapping:
744 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
745 to_add["role"] in (mapping["role"], mapping["role_name"]):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100746
tiernocf042d32019-06-13 09:06:40 +0000747 if mapping in mappings_to_remove: # do not remove
748 mappings_to_remove.remove(mapping)
749 break # do not add, it is already at user
750 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200751 pid = self.auth.get_project(to_add["project"])["_id"]
752 rid = self.auth.get_role(to_add["role"])["_id"]
753 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000754
755 # set
756 if indata.get("project_role_mappings"):
757 for to_set in indata["project_role_mappings"]:
758 for mapping in original_mapping:
759 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
760 to_set["role"] in (mapping["role"], mapping["role_name"]):
tiernocf042d32019-06-13 09:06:40 +0000761 if mapping in mappings_to_remove: # do not remove
762 mappings_to_remove.remove(mapping)
763 break # do not add, it is already at user
764 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200765 pid = self.auth.get_project(to_set["project"])["_id"]
766 rid = self.auth.get_role(to_set["role"])["_id"]
767 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000768 for mapping in original_mapping:
769 for to_set in indata["project_role_mappings"]:
770 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
771 to_set["role"] in (mapping["role"], mapping["role_name"]):
772 break
773 else:
774 # delete
775 if mapping not in mappings_to_remove: # do not remove
776 mappings_to_remove.append(mapping)
777
delacruzramo01b15d32019-07-02 14:37:47 +0200778 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
779 "add_project_role_mappings": mappings_to_add,
780 "remove_project_role_mappings": mappings_to_remove
781 })
tiernocf042d32019-06-13 09:06:40 +0000782
delacruzramo01b15d32019-07-02 14:37:47 +0200783 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100784 except ValidationError as e:
785 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
786
787 def list(self, session, filter_q=None):
788 """
789 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100790 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100791 :param filter_q: filter of data to be applied
792 :return: The list, it can be empty if no one match the filter.
793 """
delacruzramo029405d2019-09-26 10:52:56 +0200794 user_list = self.auth.get_user_list(filter_q)
795 if not session["allow_show_user_project_role"]:
796 # Bug 853 - Default filtering
797 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
798 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100799
tiernobee3bad2019-12-05 12:26:01 +0000800 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100801 """
802 Delete item by its internal _id
803
tierno65ca36d2019-02-12 19:27:52 +0100804 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100805 :param _id: server internal id
806 :param force: indicates if deletion must be forced in case of conflict
807 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000808 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100809 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
810 """
tiernocf042d32019-06-13 09:06:40 +0000811 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200812 user = self.auth.get_user(_id)
813 uid = user["_id"]
814 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100815 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200816 v = self.auth.delete_user(uid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100817 return v
818 return None
819
820
821class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100822 # topic = "projects"
823 # topic_msg = "projects"
Eduardo Sousa44603902019-06-04 08:10:32 +0100824 schema_new = project_new_schema
825 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100826
827 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200828 ProjectTopic.__init__(self, db, fs, msg, auth)
829 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100830
tierno65ca36d2019-02-12 19:27:52 +0100831 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100832 """
833 Check that the data to be inserted is valid
834
tierno65ca36d2019-02-12 19:27:52 +0100835 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100836 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100837 :return: None or raises EngineException
838 """
tiernocf042d32019-06-13 09:06:40 +0000839 project_name = indata.get("name")
840 if is_valid_uuid(project_name):
delacruzramoceb8baf2019-06-21 14:25:38 +0200841 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000842 HTTPStatus.UNPROCESSABLE_ENTITY)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100843
tiernocf042d32019-06-13 09:06:40 +0000844 project_list = self.auth.get_project_list(filter_q={"name": project_name})
845
846 if project_list:
847 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
848
849 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
850 """
851 Check that the data to be edited/uploaded is valid
852
853 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
854 :param final_content: data once modified
855 :param edit_content: incremental data that contains the modifications to apply
856 :param _id: internal _id
857 :return: None or raises EngineException
858 """
859
860 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +0200861 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +0000862 if is_valid_uuid(project_name):
delacruzramo79e40f42019-10-10 16:36:40 +0200863 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000864 HTTPStatus.UNPROCESSABLE_ENTITY)
865
delacruzramo01b15d32019-07-02 14:37:47 +0200866 if final_content["name"] == "admin":
867 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
868
tiernocf042d32019-06-13 09:06:40 +0000869 # Check that project name is not used, regardless keystone already checks this
delacruzramo32bab472019-09-13 12:24:22 +0200870 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
tiernocf042d32019-06-13 09:06:40 +0000871 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100872
tiernob4844ab2019-05-23 08:42:12 +0000873 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100874 """
875 Check if deletion can be done because of dependencies if it is not force. To override
876
tierno65ca36d2019-02-12 19:27:52 +0100877 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100878 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000879 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100880 :return: None if ok or raises EngineException with the conflict
881 """
delacruzramo01b15d32019-07-02 14:37:47 +0200882
883 def check_rw_projects(topic, title, id_field):
884 for desc in self.db.get_list(topic):
885 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
886 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
887 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
888
889 if _id in session["project_id"]:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100890 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
891
delacruzramo01b15d32019-07-02 14:37:47 +0200892 if db_content["name"] == "admin":
893 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
894
895 # If any user is using this project, raise CONFLICT exception
896 if not session["force"]:
897 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +0000898 for prm in user.get("project_role_mappings"):
899 if prm["project"] == _id:
900 raise EngineException("Project '{}' ({}) is being used by user '{}'"
901 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200902
903 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
904 if not session["force"]:
905 check_rw_projects("vnfds", "VNF Descriptor", "id")
906 check_rw_projects("nsds", "NS Descriptor", "id")
907 check_rw_projects("nsts", "NS Template", "id")
908 check_rw_projects("pdus", "PDU Descriptor", "name")
909
tierno65ca36d2019-02-12 19:27:52 +0100910 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100911 """
912 Creates a new entry into the authentication backend.
913
914 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
915
916 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100917 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100918 :param indata: data to be inserted
919 :param kwargs: used to override the indata descriptor
920 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200921 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100922 """
923 try:
924 content = BaseTopic._remove_envelop(indata)
925
926 # Override descriptor with query string kwargs
927 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100928 content = self._validate_input_new(content, session["force"])
929 self.check_conflict_on_new(session, content)
930 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200931 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100932 rollback.append({"topic": self.topic, "_id": _id})
tiernobee3bad2019-12-05 12:26:01 +0000933 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +0200934 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100935 except ValidationError as e:
936 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
937
938 def show(self, session, _id):
939 """
940 Get complete information on an topic
941
tierno65ca36d2019-02-12 19:27:52 +0100942 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100943 :param _id: server internal id
944 :return: dictionary, raise exception if not found.
945 """
tiernocf042d32019-06-13 09:06:40 +0000946 # Allow _id to be a name or uuid
947 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +0200948 # projects = self.auth.get_project_list(filter_q=filter_q)
949 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100950 if len(projects) == 1:
951 return projects[0]
952 elif len(projects) > 1:
953 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
954 else:
955 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
956
957 def list(self, session, filter_q=None):
958 """
959 Get a list of the topic that matches a filter
960
tierno65ca36d2019-02-12 19:27:52 +0100961 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100962 :param filter_q: filter of data to be applied
963 :return: The list, it can be empty if no one match the filter.
964 """
delacruzramo029405d2019-09-26 10:52:56 +0200965 project_list = self.auth.get_project_list(filter_q)
966 if not session["allow_show_user_project_role"]:
967 # Bug 853 - Default filtering
968 user = self.auth.get_user(session["username"])
969 projects = [prm["project"] for prm in user["project_role_mappings"]]
970 project_list = [proj for proj in project_list if proj["_id"] in projects]
971 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100972
tiernobee3bad2019-12-05 12:26:01 +0000973 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100974 """
975 Delete item by its internal _id
976
tierno65ca36d2019-02-12 19:27:52 +0100977 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100978 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100979 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000980 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100981 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
982 """
tiernocf042d32019-06-13 09:06:40 +0000983 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200984 proj = self.auth.get_project(_id)
985 pid = proj["_id"]
986 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100987 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200988 v = self.auth.delete_project(pid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100989 return v
990 return None
991
tierno4015b472019-06-10 13:57:29 +0000992 def edit(self, session, _id, indata=None, kwargs=None, content=None):
993 """
994 Updates a project entry.
995
996 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
997 :param _id:
998 :param indata: data to be inserted
999 :param kwargs: used to override the indata descriptor
1000 :param content:
1001 :return: _id: identity of the inserted data.
1002 """
1003 indata = self._remove_envelop(indata)
1004
1005 # Override descriptor with query string kwargs
1006 if kwargs:
1007 BaseTopic._update_input_with_kwargs(indata, kwargs)
1008 try:
1009 indata = self._validate_input_edit(indata, force=session["force"])
1010
1011 if not content:
1012 content = self.show(session, _id)
1013 self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001014 self.format_on_edit(content, indata)
tierno4015b472019-06-10 13:57:29 +00001015
delacruzramo32bab472019-09-13 12:24:22 +02001016 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001017 self.auth.update_project(content["_id"], content)
tierno4015b472019-06-10 13:57:29 +00001018 except ValidationError as e:
1019 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1020
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001021
1022class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001023 topic = "roles"
1024 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001025 schema_new = roles_new_schema
1026 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001027 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001028
tierno9e87a7f2020-03-23 09:24:10 +00001029 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001030 BaseTopic.__init__(self, db, fs, msg, auth)
1031 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001032 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001033 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001034
1035 @staticmethod
1036 def validate_role_definition(operations, role_definitions):
1037 """
1038 Validates the role definition against the operations defined in
1039 the resources to operations files.
1040
1041 :param operations: operations list
1042 :param role_definitions: role definition to test
1043 :return: None if ok, raises ValidationError exception on error
1044 """
tierno1f029d82019-06-13 22:37:04 +00001045 if not role_definitions.get("permissions"):
1046 return
1047 ignore_fields = ["admin", "default"]
1048 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001049 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001050 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001051 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001052 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001053
delacruzramoc061f562019-04-05 11:00:02 +02001054 role_def_matches = [op for op in operations if op.startswith(role_def)]
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001055
1056 if len(role_def_matches) == 0:
tierno1f029d82019-06-13 22:37:04 +00001057 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001058
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001059 def _validate_input_new(self, input, force=False):
1060 """
1061 Validates input user content for a new entry.
1062
1063 :param input: user input content for the new topic
1064 :param force: may be used for being more tolerant
1065 :return: The same input content, or a changed version of it.
1066 """
1067 if self.schema_new:
1068 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001069 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001070
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001071 return input
1072
1073 def _validate_input_edit(self, input, force=False):
1074 """
1075 Validates input user content for updating an entry.
1076
1077 :param input: user input content for the new topic
1078 :param force: may be used for being more tolerant
1079 :return: The same input content, or a changed version of it.
1080 """
1081 if self.schema_edit:
1082 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001083 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001084
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001085 return input
1086
tierno65ca36d2019-02-12 19:27:52 +01001087 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001088 """
1089 Check that the data to be inserted is valid
1090
tierno65ca36d2019-02-12 19:27:52 +01001091 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001092 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001093 :return: None or raises EngineException
1094 """
delacruzramo79e40f42019-10-10 16:36:40 +02001095 # check name is not uuid
1096 role_name = indata.get("name")
1097 if is_valid_uuid(role_name):
1098 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1099 HTTPStatus.UNPROCESSABLE_ENTITY)
tierno1f029d82019-06-13 22:37:04 +00001100 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001101 name = indata["name"]
1102 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1103 if self.auth.get_role_list({"name": name}):
1104 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001105
tierno65ca36d2019-02-12 19:27:52 +01001106 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001107 """
1108 Check that the data to be edited/uploaded is valid
1109
tierno65ca36d2019-02-12 19:27:52 +01001110 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001111 :param final_content: data once modified
1112 :param edit_content: incremental data that contains the modifications to apply
1113 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001114 :return: None or raises EngineException
1115 """
tierno1f029d82019-06-13 22:37:04 +00001116 if "default" not in final_content["permissions"]:
1117 final_content["permissions"]["default"] = False
1118 if "admin" not in final_content["permissions"]:
1119 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001120
delacruzramo79e40f42019-10-10 16:36:40 +02001121 # check name is not uuid
1122 role_name = edit_content.get("name")
1123 if is_valid_uuid(role_name):
1124 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1125 HTTPStatus.UNPROCESSABLE_ENTITY)
1126
1127 # Check renaming of admin roles
1128 role = self.auth.get_role(_id)
1129 if role["name"] in ["system_admin", "project_admin"]:
1130 raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1131
tierno1f029d82019-06-13 22:37:04 +00001132 # check name not exists
1133 if "name" in edit_content:
1134 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001135 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1136 roles = self.auth.get_role_list({"name": role_name})
1137 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
tierno1f029d82019-06-13 22:37:04 +00001138 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001139
tiernob4844ab2019-05-23 08:42:12 +00001140 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001141 """
1142 Check if deletion can be done because of dependencies if it is not force. To override
1143
tierno65ca36d2019-02-12 19:27:52 +01001144 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001145 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001146 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001147 :return: None if ok or raises EngineException with the conflict
1148 """
delacruzramo01b15d32019-07-02 14:37:47 +02001149 role = self.auth.get_role(_id)
1150 if role["name"] in ["system_admin", "project_admin"]:
1151 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001152
delacruzramo01b15d32019-07-02 14:37:47 +02001153 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001154 if not session["force"]:
1155 for user in self.auth.get_user_list():
1156 for prm in user.get("project_role_mappings"):
1157 if prm["role"] == _id:
1158 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1159 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001160
1161 @staticmethod
delacruzramo01b15d32019-07-02 14:37:47 +02001162 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001163 """
1164 Modifies content descriptor to include _admin
1165
1166 :param content: descriptor to be modified
1167 :param project_id: if included, it add project read/write permissions
1168 :param make_public: if included it is generated as public for reading.
1169 :return: None, but content is modified
1170 """
1171 now = time()
1172 if "_admin" not in content:
1173 content["_admin"] = {}
1174 if not content["_admin"].get("created"):
1175 content["_admin"]["created"] = now
1176 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001177
tierno1f029d82019-06-13 22:37:04 +00001178 if "permissions" not in content:
1179 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001180
tierno1f029d82019-06-13 22:37:04 +00001181 if "default" not in content["permissions"]:
1182 content["permissions"]["default"] = False
1183 if "admin" not in content["permissions"]:
1184 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001185
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001186 @staticmethod
1187 def format_on_edit(final_content, edit_content):
1188 """
1189 Modifies final_content descriptor to include the modified date.
1190
1191 :param final_content: final descriptor generated
1192 :param edit_content: alterations to be include
1193 :return: None, but final_content is modified
1194 """
delacruzramo01b15d32019-07-02 14:37:47 +02001195 if "_admin" in final_content:
1196 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001197
tierno1f029d82019-06-13 22:37:04 +00001198 if "permissions" not in final_content:
1199 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001200
tierno1f029d82019-06-13 22:37:04 +00001201 if "default" not in final_content["permissions"]:
1202 final_content["permissions"]["default"] = False
1203 if "admin" not in final_content["permissions"]:
1204 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001205 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001206
delacruzramo01b15d32019-07-02 14:37:47 +02001207 def show(self, session, _id):
1208 """
1209 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001210
delacruzramo01b15d32019-07-02 14:37:47 +02001211 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1212 :param _id: server internal id
1213 :return: dictionary, raise exception if not found.
1214 """
1215 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001216 # roles = self.auth.get_role_list(filter_q)
1217 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001218 if not roles:
1219 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1220 elif len(roles) > 1:
1221 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1222 return roles[0]
1223
1224 def list(self, session, filter_q=None):
1225 """
1226 Get a list of the topic that matches a filter
1227
1228 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1229 :param filter_q: filter of data to be applied
1230 :return: The list, it can be empty if no one match the filter.
1231 """
delacruzramo029405d2019-09-26 10:52:56 +02001232 role_list = self.auth.get_role_list(filter_q)
1233 if not session["allow_show_user_project_role"]:
1234 # Bug 853 - Default filtering
1235 user = self.auth.get_user(session["username"])
1236 roles = [prm["role"] for prm in user["project_role_mappings"]]
1237 role_list = [role for role in role_list if role["_id"] in roles]
1238 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001239
tierno65ca36d2019-02-12 19:27:52 +01001240 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001241 """
1242 Creates a new entry into database.
1243
1244 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001245 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001246 :param indata: data to be inserted
1247 :param kwargs: used to override the indata descriptor
1248 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001249 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001250 """
1251 try:
tierno1f029d82019-06-13 22:37:04 +00001252 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001253
1254 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001255 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001256 content = self._validate_input_new(content, session["force"])
1257 self.check_conflict_on_new(session, content)
1258 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001259 # role_name = content["name"]
1260 rid = self.auth.create_role(content)
1261 content["_id"] = rid
1262 # _id = self.db.create(self.topic, content)
1263 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001264 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001265 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001266 except ValidationError as e:
1267 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1268
tiernobee3bad2019-12-05 12:26:01 +00001269 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001270 """
1271 Delete item by its internal _id
1272
tierno65ca36d2019-02-12 19:27:52 +01001273 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001274 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001275 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001276 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001277 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1278 """
delacruzramo01b15d32019-07-02 14:37:47 +02001279 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1280 roles = self.auth.get_role_list(filter_q)
1281 if not roles:
1282 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1283 elif len(roles) > 1:
1284 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1285 rid = roles[0]["_id"]
1286 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001287 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001288 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001289 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001290 v = self.auth.delete_role(rid)
1291 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001292 return v
1293 return None
1294
tierno65ca36d2019-02-12 19:27:52 +01001295 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001296 """
1297 Updates a role entry.
1298
tierno65ca36d2019-02-12 19:27:52 +01001299 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001300 :param _id:
1301 :param indata: data to be inserted
1302 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001303 :param content:
1304 :return: _id: identity of the inserted data.
1305 """
delacruzramo01b15d32019-07-02 14:37:47 +02001306 if kwargs:
1307 self._update_input_with_kwargs(indata, kwargs)
1308 try:
1309 indata = self._validate_input_edit(indata, force=session["force"])
1310 if not content:
1311 content = self.show(session, _id)
1312 deep_update_rfc7396(content, indata)
1313 self.check_conflict_on_edit(session, content, indata, _id=_id)
1314 self.format_on_edit(content, indata)
1315 self.auth.update_role(content)
1316 except ValidationError as e:
1317 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)