Code Coverage

Cobertura Coverage Report > osm_nbi >

admin_topics.py

Trend

Classes100%
 
Lines69%
   
Conditionals100%
 

File Coverage summary

NameClassesLinesConditionals
admin_topics.py
100%
1/1
69%
481/697
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
admin_topics.py
69%
481/697
N/A

Source

osm_nbi/admin_topics.py
1 # -*- coding: utf-8 -*-
2
3 # 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
16 # import logging
17 1 from uuid import uuid4
18 1 from hashlib import sha256
19 1 from http import HTTPStatus
20 1 from time import time
21 1 from 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, \
24     k8scluster_new_schema, k8scluster_edit_schema, k8srepo_new_schema, k8srepo_edit_schema, \
25     osmrepo_new_schema, osmrepo_edit_schema, \
26     validate_input, ValidationError, is_valid_uuid  # To check that User/Project Names don't look like UUIDs
27 1 from osm_nbi.base_topic import BaseTopic, EngineException
28 1 from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
29 1 from osm_common.dbbase import deep_update_rfc7396
30 1 import copy
31
32 1 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
33
34
35 1 class UserTopic(BaseTopic):
36 1     topic = "users"
37 1     topic_msg = "users"
38 1     schema_new = user_new_schema
39 1     schema_edit = user_edit_schema
40 1     multiproject = False
41
42 1     def __init__(self, db, fs, msg, auth):
43 1         BaseTopic.__init__(self, db, fs, msg, auth)
44
45 1     @staticmethod
46     def _get_project_filter(session):
47         """
48         Generates a filter dictionary for querying database users.
49         Current policy is admin can show all, non admin, only its own user.
50         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
51         :return:
52         """
53 0         if session["admin"]:  # allows all
54 0             return {}
55         else:
56 0             return {"username": session["username"]}
57
58 1     def check_conflict_on_new(self, session, indata):
59         # check username not exists
60 0         if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
61 0             raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
62         # check projects
63 0         if not session["force"]:
64 0             for p in indata.get("projects") or []:
65                 # To allow project addressing by Name as well as ID
66 0                 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
67                                        fail_on_more=False):
68 0                     raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
69
70 1     def check_conflict_on_del(self, session, _id, db_content):
71         """
72         Check if deletion can be done because of dependencies if it is not force. To override
73         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74         :param _id: internal _id
75         :param db_content: The database content of this item _id
76         :return: None if ok or raises EngineException with the conflict
77         """
78 0         if _id == session["username"]:
79 0             raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
80
81 1     @staticmethod
82 1     def format_on_new(content, project_id=None, make_public=False):
83 0         BaseTopic.format_on_new(content, make_public=False)
84         # Removed so that the UUID is kept, to allow User Name modification
85         # content["_id"] = content["username"]
86 0         salt = uuid4().hex
87 0         content["_admin"]["salt"] = salt
88 0         if content.get("password"):
89 0             content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
90 0         if content.get("project_role_mappings"):
91 0             projects = [mapping["project"] for mapping in content["project_role_mappings"]]
92
93 0             if content.get("projects"):
94 0                 content["projects"] += projects
95             else:
96 0                 content["projects"] = projects
97
98 1     @staticmethod
99     def format_on_edit(final_content, edit_content):
100 0         BaseTopic.format_on_edit(final_content, edit_content)
101 0         if edit_content.get("password"):
102 0             salt = uuid4().hex
103 0             final_content["_admin"]["salt"] = salt
104 0             final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
105                                                salt.encode('utf-8')).hexdigest()
106 0         return None
107
108 1     def edit(self, session, _id, indata=None, kwargs=None, content=None):
109 0         if not session["admin"]:
110 0             raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
111         # Names that look like UUIDs are not allowed
112 0         name = (indata if indata else kwargs).get("username")
113 0         if is_valid_uuid(name):
114 0             raise EngineException("Usernames that look like UUIDs are not allowed",
115                                   http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
116 0         return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
117
118 1     def new(self, rollback, session, indata=None, kwargs=None, headers=None):
119 0         if not session["admin"]:
120 0             raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
121         # Names that look like UUIDs are not allowed
122 0         name = indata["username"] if indata else kwargs["username"]
123 0         if is_valid_uuid(name):
124 0             raise EngineException("Usernames that look like UUIDs are not allowed",
125                                   http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
126 0         return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
127
128
129 1 class ProjectTopic(BaseTopic):
130 1     topic = "projects"
131 1     topic_msg = "projects"
132 1     schema_new = project_new_schema
133 1     schema_edit = project_edit_schema
134 1     multiproject = False
135
136 1     def __init__(self, db, fs, msg, auth):
137 1         BaseTopic.__init__(self, db, fs, msg, auth)
138
139 1     @staticmethod
140     def _get_project_filter(session):
141         """
142         Generates a filter dictionary for querying database users.
143         Current policy is admin can show all, non admin, only its own user.
144         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
145         :return:
146         """
147 0         if session["admin"]:  # allows all
148 0             return {}
149         else:
150 0             return {"_id.cont": session["project_id"]}
151
152 1     def check_conflict_on_new(self, session, indata):
153 0         if not indata.get("name"):
154 0             raise EngineException("missing 'name'")
155         # check name not exists
156 0         if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
157 0             raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
158
159 1     @staticmethod
160 1     def format_on_new(content, project_id=None, make_public=False):
161 1         BaseTopic.format_on_new(content, None)
162         # Removed so that the UUID is kept, to allow Project Name modification
163         # content["_id"] = content["name"]
164
165 1     def check_conflict_on_del(self, session, _id, db_content):
166         """
167         Check if deletion can be done because of dependencies if it is not force. To override
168         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
169         :param _id: internal _id
170         :param db_content: The database content of this item _id
171         :return: None if ok or raises EngineException with the conflict
172         """
173 0         if _id in session["project_id"]:
174 0             raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
175 0         if session["force"]:
176 0             return
177 0         _filter = {"projects": _id}
178 0         if self.db.get_list("users", _filter):
179 0             raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
180
181 1     def edit(self, session, _id, indata=None, kwargs=None, content=None):
182 0         if not session["admin"]:
183 0             raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
184         # Names that look like UUIDs are not allowed
185 0         name = (indata if indata else kwargs).get("name")
186 0         if is_valid_uuid(name):
187 0             raise EngineException("Project names that look like UUIDs are not allowed",
188                                   http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
189 0         return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
190
191 1     def new(self, rollback, session, indata=None, kwargs=None, headers=None):
192 0         if not session["admin"]:
193 0             raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
194         # Names that look like UUIDs are not allowed
195 0         name = indata["name"] if indata else kwargs["name"]
196 0         if is_valid_uuid(name):
197 0             raise EngineException("Project names that look like UUIDs are not allowed",
198                                   http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
199 0         return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
200
201
202 1 class CommonVimWimSdn(BaseTopic):
203     """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
204 1     config_to_encrypt = {}     # what keys at config must be encrypted because contains passwords
205 1     password_to_encrypt = ""   # key that contains a password
206
207 1     @staticmethod
208 1     def _create_operation(op_type, params=None):
209         """
210         Creates a dictionary with the information to an operation, similar to ns-lcm-op
211         :param op_type: can be create, edit, delete
212         :param params: operation input parameters
213         :return: new dictionary with
214         """
215 1         now = time()
216 1         return {
217             "lcmOperationType": op_type,
218             "operationState": "PROCESSING",
219             "startTime": now,
220             "statusEnteredTime": now,
221             "detailed-status": "",
222             "operationParams": params,
223         }
224
225 1     def check_conflict_on_new(self, session, indata):
226         """
227         Check that the data to be inserted is valid. It is checked that name is unique
228         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
229         :param indata: data to be inserted
230         :return: None or raises EngineException
231         """
232 1         self.check_unique_name(session, indata["name"], _id=None)
233
234 1     def check_conflict_on_edit(self, session, final_content, edit_content, _id):
235         """
236         Check that the data to be edited/uploaded is valid. It is checked that name is unique
237         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
238         :param final_content: data once modified. This method may change it.
239         :param edit_content: incremental data that contains the modifications to apply
240         :param _id: internal _id
241         :return: None or raises EngineException
242         """
243 1         if not session["force"] and edit_content.get("name"):
244 1             self.check_unique_name(session, edit_content["name"], _id=_id)
245
246 1     def format_on_edit(self, final_content, edit_content):
247         """
248         Modifies final_content inserting admin information upon edition
249         :param final_content: final content to be stored at database
250         :param edit_content: user requested update content
251         :return: operation id
252         """
253 1         super().format_on_edit(final_content, edit_content)
254
255         # encrypt passwords
256 1         schema_version = final_content.get("schema_version")
257 1         if schema_version:
258 0             if edit_content.get(self.password_to_encrypt):
259 0                 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
260                                                                           schema_version=schema_version,
261                                                                           salt=final_content["_id"])
262 0             config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
263 0             if edit_content.get("config") and config_to_encrypt_keys:
264
265 0                 for p in config_to_encrypt_keys:
266 0                     if edit_content["config"].get(p):
267 0                         final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
268                                                                      schema_version=schema_version,
269                                                                      salt=final_content["_id"])
270
271         # create edit operation
272 1         final_content["_admin"]["operations"].append(self._create_operation("edit"))
273 1         return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
274
275 1     def format_on_new(self, content, project_id=None, make_public=False):
276         """
277         Modifies content descriptor to include _admin and insert create operation
278         :param content: descriptor to be modified
279         :param project_id: if included, it add project read/write permissions. Can be None or a list
280         :param make_public: if included it is generated as public for reading.
281         :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
282         """
283 1         super().format_on_new(content, project_id=project_id, make_public=make_public)
284 1         content["schema_version"] = schema_version = "1.11"
285
286         # encrypt passwords
287 1         if content.get(self.password_to_encrypt):
288 0             content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
289                                                                 schema_version=schema_version,
290                                                                 salt=content["_id"])
291 1         config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
292 1         if content.get("config") and config_to_encrypt_keys:
293 0             for p in config_to_encrypt_keys:
294 0                 if content["config"].get(p):
295 0                     content["config"][p] = self.db.encrypt(content["config"][p],
296                                                            schema_version=schema_version,
297                                                            salt=content["_id"])
298
299 1         content["_admin"]["operationalState"] = "PROCESSING"
300
301         # create operation
302 1         content["_admin"]["operations"] = [self._create_operation("create")]
303 1         content["_admin"]["current_operation"] = None
304
305 1         return "{}:0".format(content["_id"])
306
307 1     def delete(self, session, _id, dry_run=False, not_send_msg=None):
308         """
309         Delete item by its internal _id
310         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
311         :param _id: server internal id
312         :param dry_run: make checking but do not delete
313         :param not_send_msg: To not send message (False) or store content (list) instead
314         :return: operation id if it is ordered to delete. None otherwise
315         """
316
317 1         filter_q = self._get_project_filter(session)
318 1         filter_q["_id"] = _id
319 1         db_content = self.db.get_one(self.topic, filter_q)
320
321 1         self.check_conflict_on_del(session, _id, db_content)
322 1         if dry_run:
323 0             return None
324
325         # remove reference from project_read if there are more projects referencing it. If it last one,
326         # do not remove reference, but order via kafka to delete it
327 1         if session["project_id"] and session["project_id"]:
328 1             other_projects_referencing = next((p for p in db_content["_admin"]["projects_read"]
329                                                if p not in session["project_id"] and p != "ANY"), None)
330
331             # check if there are projects referencing it (apart from ANY, that means, public)....
332 1             if other_projects_referencing:
333                 # remove references but not delete
334 1                 update_dict_pull = {"_admin.projects_read": session["project_id"],
335                                     "_admin.projects_write": session["project_id"]}
336 1                 self.db.set_one(self.topic, filter_q, update_dict=None, pull_list=update_dict_pull)
337 1                 return None
338             else:
339 1                 can_write = next((p for p in db_content["_admin"]["projects_write"] if p == "ANY" or
340                                   p in session["project_id"]), None)
341 1                 if not can_write:
342 0                     raise EngineException("You have not write permission to delete it",
343                                           http_code=HTTPStatus.UNAUTHORIZED)
344
345         # It must be deleted
346 1         if session["force"]:
347 1             self.db.del_one(self.topic, {"_id": _id})
348 1             op_id = None
349 1             self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
350         else:
351 1             update_dict = {"_admin.to_delete": True}
352 1             self.db.set_one(self.topic, {"_id": _id},
353                             update_dict=update_dict,
354                             push={"_admin.operations": self._create_operation("delete")}
355                             )
356             # the number of operations is the operation_id. db_content does not contains the new operation inserted,
357             # so the -1 is not needed
358 1             op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
359 1             self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
360 1         return op_id
361
362
363 1 class VimAccountTopic(CommonVimWimSdn):
364 1     topic = "vim_accounts"
365 1     topic_msg = "vim_account"
366 1     schema_new = vim_account_new_schema
367 1     schema_edit = vim_account_edit_schema
368 1     multiproject = True
369 1     password_to_encrypt = "vim_password"
370 1     config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
371                          "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
372
373 1     def check_conflict_on_del(self, session, _id, db_content):
374         """
375         Check if deletion can be done because of dependencies if it is not force. To override
376         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
377         :param _id: internal _id
378         :param db_content: The database content of this item _id
379         :return: None if ok or raises EngineException with the conflict
380         """
381 0         if session["force"]:
382 0             return
383         # check if used by VNF
384 0         if self.db.get_list("vnfrs", {"vim-account-id": _id}):
385 0             raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
386 0         super().check_conflict_on_del(session, _id, db_content)
387
388
389 1 class WimAccountTopic(CommonVimWimSdn):
390 1     topic = "wim_accounts"
391 1     topic_msg = "wim_account"
392 1     schema_new = wim_account_new_schema
393 1     schema_edit = wim_account_edit_schema
394 1     multiproject = True
395 1     password_to_encrypt = "wim_password"
396 1     config_to_encrypt = {}
397
398
399 1 class SdnTopic(CommonVimWimSdn):
400 1     topic = "sdns"
401 1     topic_msg = "sdn"
402 1     quota_name = "sdn_controllers"
403 1     schema_new = sdn_new_schema
404 1     schema_edit = sdn_edit_schema
405 1     multiproject = True
406 1     password_to_encrypt = "password"
407 1     config_to_encrypt = {}
408
409 1     def _obtain_url(self, input, create):
410 0         if input.get("ip") or input.get("port"):
411 0             if not input.get("ip") or not input.get("port") or input.get('url'):
412 0                 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
413 0             input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
414 0             del input["ip"]
415 0             del input["port"]
416 0         elif create and not input.get('url'):
417 0             raise ValidationError("You must provide 'url'")
418 0         return input
419
420 1     def _validate_input_new(self, input, force=False):
421 0         input = super()._validate_input_new(input, force)
422 0         return self._obtain_url(input, True)
423
424 1     def _validate_input_edit(self, input, content, force=False):
425 0         input = super()._validate_input_edit(input, content, force)
426 0         return self._obtain_url(input, False)
427
428
429 1 class K8sClusterTopic(CommonVimWimSdn):
430 1     topic = "k8sclusters"
431 1     topic_msg = "k8scluster"
432 1     schema_new = k8scluster_new_schema
433 1     schema_edit = k8scluster_edit_schema
434 1     multiproject = True
435 1     password_to_encrypt = None
436 1     config_to_encrypt = {}
437
438 1     def format_on_new(self, content, project_id=None, make_public=False):
439 0         oid = super().format_on_new(content, project_id, make_public)
440 0         self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
441                                        schema_version=content["schema_version"], salt=content["_id"])
442         # Add Helm/Juju Repo lists
443 0         repos = {"helm-chart": [], "juju-bundle": []}
444 0         for proj in content["_admin"]["projects_read"]:
445 0             if proj != 'ANY':
446 0                 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
447 0                     if repo["_id"] not in repos[repo["type"]]:
448 0                         repos[repo["type"]].append(repo["_id"])
449 0         for k in repos:
450 0             content["_admin"][k.replace('-', '_')+"_repos"] = repos[k]
451 0         return oid
452
453 1     def format_on_edit(self, final_content, edit_content):
454 0         if final_content.get("schema_version") and edit_content.get("credentials"):
455 0             self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
456                                            schema_version=final_content["schema_version"], salt=final_content["_id"])
457 0             deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
458 0         oid = super().format_on_edit(final_content, edit_content)
459 0         return oid
460
461 1     def check_conflict_on_edit(self, session, final_content, edit_content, _id):
462 0         super(CommonVimWimSdn, self).check_conflict_on_edit(session, final_content, edit_content, _id)
463 0         super().check_conflict_on_edit(session, final_content, edit_content, _id)
464         # Update Helm/Juju Repo lists
465 0         repos = {"helm-chart": [], "juju-bundle": []}
466 0         for proj in session.get("set_project", []):
467 0             if proj != 'ANY':
468 0                 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
469 0                     if repo["_id"] not in repos[repo["type"]]:
470 0                         repos[repo["type"]].append(repo["_id"])
471 0         for k in repos:
472 0             rlist = k.replace('-', '_') + "_repos"
473 0             if rlist not in final_content["_admin"]:
474 0                 final_content["_admin"][rlist] = []
475 0             final_content["_admin"][rlist] += repos[k]
476
477 1     def check_conflict_on_del(self, session, _id, db_content):
478         """
479         Check if deletion can be done because of dependencies if it is not force. To override
480         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
481         :param _id: internal _id
482         :param db_content: The database content of this item _id
483         :return: None if ok or raises EngineException with the conflict
484         """
485 0         if session["force"]:
486 0             return
487         # check if used by VNF
488 0         filter_q = {"kdur.k8s-cluster.id": _id}
489 0         if session["project_id"]:
490 0             filter_q["_admin.projects_read.cont"] = session["project_id"]
491 0         if self.db.get_list("vnfrs", filter_q):
492 0             raise EngineException("There is at least one VNF using this k8scluster", http_code=HTTPStatus.CONFLICT)
493 0         super().check_conflict_on_del(session, _id, db_content)
494
495
496 1 class K8sRepoTopic(CommonVimWimSdn):
497 1     topic = "k8srepos"
498 1     topic_msg = "k8srepo"
499 1     schema_new = k8srepo_new_schema
500 1     schema_edit = k8srepo_edit_schema
501 1     multiproject = True
502 1     password_to_encrypt = None
503 1     config_to_encrypt = {}
504
505 1     def format_on_new(self, content, project_id=None, make_public=False):
506 0         oid = super().format_on_new(content, project_id, make_public)
507         # Update Helm/Juju Repo lists
508 0         repo_list = content["type"].replace('-', '_')+"_repos"
509 0         for proj in content["_admin"]["projects_read"]:
510 0             if proj != 'ANY':
511 0                 self.db.set_list("k8sclusters",
512                                  {"_admin.projects_read": proj, "_admin."+repo_list+".ne": content["_id"]}, {},
513                                  push={"_admin."+repo_list: content["_id"]})
514 0         return oid
515
516 1     def delete(self, session, _id, dry_run=False, not_send_msg=None):
517 0         type = self.db.get_one("k8srepos", {"_id": _id})["type"]
518 0         oid = super().delete(session, _id, dry_run, not_send_msg)
519 0         if oid:
520             # Remove from Helm/Juju Repo lists
521 0             repo_list = type.replace('-', '_') + "_repos"
522 0             self.db.set_list("k8sclusters", {"_admin."+repo_list: _id}, {}, pull={"_admin."+repo_list: _id})
523 0         return oid
524
525
526 1 class OsmRepoTopic(BaseTopic):
527 1     topic = "osmrepos"
528 1     topic_msg = "osmrepos"
529 1     schema_new = osmrepo_new_schema
530 1     schema_edit = osmrepo_edit_schema
531 1     multiproject = True
532     # TODO: Implement user/password
533
534
535 1 class UserTopicAuth(UserTopic):
536     # topic = "users"
537 1     topic_msg = "users"
538 1     schema_new = user_new_schema
539 1     schema_edit = user_edit_schema
540
541 1     def __init__(self, db, fs, msg, auth):
542 1         UserTopic.__init__(self, db, fs, msg, auth)
543         # self.auth = auth
544
545 1     def check_conflict_on_new(self, session, indata):
546         """
547         Check that the data to be inserted is valid
548
549         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
550         :param indata: data to be inserted
551         :return: None or raises EngineException
552         """
553 1         username = indata.get("username")
554 1         if is_valid_uuid(username):
555 1             raise EngineException("username '{}' cannot have a uuid format".format(username),
556                                   HTTPStatus.UNPROCESSABLE_ENTITY)
557
558         # Check that username is not used, regardless keystone already checks this
559 1         if self.auth.get_user_list(filter_q={"name": username}):
560 1             raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
561
562 1         if "projects" in indata.keys():
563             # convert to new format project_role_mappings
564 1             role = self.auth.get_role_list({"name": "project_admin"})
565 1             if not role:
566 1                 role = self.auth.get_role_list()
567 1             if not role:
568 1                 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
569 1             rid = role[0]["_id"]
570 1             if not indata.get("project_role_mappings"):
571 1                 indata["project_role_mappings"] = []
572 1             for project in indata["projects"]:
573 1                 pid = self.auth.get_project(project)["_id"]
574 1                 prm = {"project": pid, "role": rid}
575 1                 if prm not in indata["project_role_mappings"]:
576 1                     indata["project_role_mappings"].append(prm)
577             # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
578             #                       HTTPStatus.BAD_REQUEST)
579
580 1     def check_conflict_on_edit(self, session, final_content, edit_content, _id):
581         """
582         Check that the data to be edited/uploaded is valid
583
584         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
585         :param final_content: data once modified
586         :param edit_content: incremental data that contains the modifications to apply
587         :param _id: internal _id
588         :return: None or raises EngineException
589         """
590
591 1         if "username" in edit_content:
592 1             username = edit_content.get("username")
593 1             if is_valid_uuid(username):
594 1                 raise EngineException("username '{}' cannot have an uuid format".format(username),
595                                       HTTPStatus.UNPROCESSABLE_ENTITY)
596
597             # Check that username is not used, regardless keystone already checks this
598 1             if self.auth.get_user_list(filter_q={"name": username}):
599 1                 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
600
601 1         if final_content["username"] == "admin":
602 1             for mapping in edit_content.get("remove_project_role_mappings", ()):
603 1                 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
604                     # TODO make this also available for project id and role id
605 1                     raise EngineException("You cannot remove system_admin role from admin user",
606                                           http_code=HTTPStatus.FORBIDDEN)
607
608 1     def check_conflict_on_del(self, session, _id, db_content):
609         """
610         Check if deletion can be done because of dependencies if it is not force. To override
611         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
612         :param _id: internal _id
613         :param db_content: The database content of this item _id
614         :return: None if ok or raises EngineException with the conflict
615         """
616 1         if db_content["username"] == session["username"]:
617 1             raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
618         # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
619
620 1     @staticmethod
621     def format_on_show(content):
622         """
623         Modifies the content of the role information to separate the role
624         metadata from the role definition.
625         """
626 0         project_role_mappings = []
627
628 0         if "projects" in content:
629 0             for project in content["projects"]:
630 0                 for role in project["roles"]:
631 0                     project_role_mappings.append({"project": project["_id"],
632                                                   "project_name": project["name"],
633                                                   "role": role["_id"],
634                                                   "role_name": role["name"]})
635 0             del content["projects"]
636 0         content["project_role_mappings"] = project_role_mappings
637
638 0         return content
639
640 1     def new(self, rollback, session, indata=None, kwargs=None, headers=None):
641         """
642         Creates a new entry into the authentication backend.
643
644         NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
645
646         :param rollback: list to append created items at database in case a rollback may to be done
647         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
648         :param indata: data to be inserted
649         :param kwargs: used to override the indata descriptor
650         :param headers: http request headers
651         :return: _id: identity of the inserted data, operation _id (None)
652         """
653 1         try:
654 1             content = BaseTopic._remove_envelop(indata)
655
656             # Override descriptor with query string kwargs
657 1             BaseTopic._update_input_with_kwargs(content, kwargs)
658 1             content = self._validate_input_new(content, session["force"])
659 1             self.check_conflict_on_new(session, content)
660             # self.format_on_new(content, session["project_id"], make_public=session["public"])
661 1             now = time()
662 1             content["_admin"] = {"created": now, "modified": now}
663 1             prms = []
664 1             for prm in content.get("project_role_mappings", []):
665 1                 proj = self.auth.get_project(prm["project"], not session["force"])
666 1                 role = self.auth.get_role(prm["role"], not session["force"])
667 1                 pid = proj["_id"] if proj else None
668 1                 rid = role["_id"] if role else None
669 1                 prl = {"project": pid, "role": rid}
670 1                 if prl not in prms:
671 1                     prms.append(prl)
672 1             content["project_role_mappings"] = prms
673             # _id = self.auth.create_user(content["username"], content["password"])["_id"]
674 1             _id = self.auth.create_user(content)["_id"]
675
676 1             rollback.append({"topic": self.topic, "_id": _id})
677             # del content["password"]
678 1             self._send_msg("created", content, not_send_msg=None)
679 1             return _id, None
680 1         except ValidationError as e:
681 1             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
682
683 1     def show(self, session, _id, api_req=False):
684         """
685         Get complete information on an topic
686
687         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
688         :param _id: server internal id or username
689         :param api_req: True if this call is serving an external API request. False if serving internal request.
690         :return: dictionary, raise exception if not found.
691         """
692         # Allow _id to be a name or uuid
693 1         filter_q = {"username": _id}
694         # users = self.auth.get_user_list(filter_q)
695 1         users = self.list(session, filter_q)   # To allow default filtering (Bug 853)
696 1         if len(users) == 1:
697 1             return users[0]
698 0         elif len(users) > 1:
699 0             raise EngineException("Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT)
700         else:
701 0             raise EngineException("User '{}' not found".format(_id), HTTPStatus.NOT_FOUND)
702
703 1     def edit(self, session, _id, indata=None, kwargs=None, content=None):
704         """
705         Updates an user entry.
706
707         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
708         :param _id:
709         :param indata: data to be inserted
710         :param kwargs: used to override the indata descriptor
711         :param content:
712         :return: _id: identity of the inserted data.
713         """
714 1         indata = self._remove_envelop(indata)
715
716         # Override descriptor with query string kwargs
717 1         if kwargs:
718 0             BaseTopic._update_input_with_kwargs(indata, kwargs)
719 1         try:
720 1             if not content:
721 1                 content = self.show(session, _id)
722 1             indata = self._validate_input_edit(indata, content, force=session["force"])
723 1             self.check_conflict_on_edit(session, content, indata, _id=_id)
724             # self.format_on_edit(content, indata)
725
726 1             if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
727                     indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
728                     indata.get("projects") or indata.get("add_projects")):
729 0                 return _id
730 1             if indata.get("project_role_mappings") \
731                     and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
732 0                 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
733                                       "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
734
735 1             if indata.get("projects") or indata.get("add_projects"):
736 1                 role = self.auth.get_role_list({"name": "project_admin"})
737 1                 if not role:
738 1                     role = self.auth.get_role_list()
739 1                 if not role:
740 1                     raise AuthconnNotFoundException("Can't find a default role for user '{}'"
741                                                     .format(content["username"]))
742 0                 rid = role[0]["_id"]
743 0                 if "add_project_role_mappings" not in indata:
744 0                     indata["add_project_role_mappings"] = []
745 0                 if "remove_project_role_mappings" not in indata:
746 0                     indata["remove_project_role_mappings"] = []
747 0                 if isinstance(indata.get("projects"), dict):
748                     # backward compatible
749 0                     for k, v in indata["projects"].items():
750 0                         if k.startswith("$") and v is None:
751 0                             indata["remove_project_role_mappings"].append({"project": k[1:]})
752 0                         elif k.startswith("$+"):
753 0                             indata["add_project_role_mappings"].append({"project": v, "role": rid})
754 0                     del indata["projects"]
755 0                 for proj in indata.get("projects", []) + indata.get("add_projects", []):
756 0                     indata["add_project_role_mappings"].append({"project": proj, "role": rid})
757
758             # user = self.show(session, _id)   # Already in 'content'
759 1             original_mapping = content["project_role_mappings"]
760
761 1             mappings_to_add = []
762 1             mappings_to_remove = []
763
764             # remove
765 1             for to_remove in indata.get("remove_project_role_mappings", ()):
766 1                 for mapping in original_mapping:
767 1                     if to_remove["project"] in (mapping["project"], mapping["project_name"]):
768 1                         if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
769 1                             mappings_to_remove.append(mapping)
770
771             # add
772 1             for to_add in indata.get("add_project_role_mappings", ()):
773 1                 for mapping in original_mapping:
774 1                     if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
775                             to_add["role"] in (mapping["role"], mapping["role_name"]):
776
777 0                         if mapping in mappings_to_remove:   # do not remove
778 0                             mappings_to_remove.remove(mapping)
779 0                         break  # do not add, it is already at user
780                 else:
781 1                     pid = self.auth.get_project(to_add["project"])["_id"]
782 1                     rid = self.auth.get_role(to_add["role"])["_id"]
783 1                     mappings_to_add.append({"project": pid, "role": rid})
784
785             # set
786 1             if indata.get("project_role_mappings"):
787 0                 for to_set in indata["project_role_mappings"]:
788 0                     for mapping in original_mapping:
789 0                         if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
790                                 to_set["role"] in (mapping["role"], mapping["role_name"]):
791 0                             if mapping in mappings_to_remove:   # do not remove
792 0                                 mappings_to_remove.remove(mapping)
793 0                             break  # do not add, it is already at user
794                     else:
795 0                         pid = self.auth.get_project(to_set["project"])["_id"]
796 0                         rid = self.auth.get_role(to_set["role"])["_id"]
797 0                         mappings_to_add.append({"project": pid, "role": rid})
798 0                 for mapping in original_mapping:
799 0                     for to_set in indata["project_role_mappings"]:
800 0                         if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
801                                 to_set["role"] in (mapping["role"], mapping["role_name"]):
802 0                             break
803                     else:
804                         # delete
805 0                         if mapping not in mappings_to_remove:   # do not remove
806 0                             mappings_to_remove.append(mapping)
807
808 1             self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
809                                    "add_project_role_mappings": mappings_to_add,
810                                    "remove_project_role_mappings": mappings_to_remove
811                                    })
812 1             data_to_send = {'_id': _id, "changes": indata}
813 1             self._send_msg("edited", data_to_send, not_send_msg=None)
814
815             # return _id
816 1         except ValidationError as e:
817 1             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
818
819 1     def list(self, session, filter_q=None, api_req=False):
820         """
821         Get a list of the topic that matches a filter
822         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
823         :param filter_q: filter of data to be applied
824         :param api_req: True if this call is serving an external API request. False if serving internal request.
825         :return: The list, it can be empty if no one match the filter.
826         """
827 1         user_list = self.auth.get_user_list(filter_q)
828 1         if not session["allow_show_user_project_role"]:
829             # Bug 853 - Default filtering
830 0             user_list = [usr for usr in user_list if usr["username"] == session["username"]]
831 1         return user_list
832
833 1     def delete(self, session, _id, dry_run=False, not_send_msg=None):
834         """
835         Delete item by its internal _id
836
837         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
838         :param _id: server internal id
839         :param force: indicates if deletion must be forced in case of conflict
840         :param dry_run: make checking but do not delete
841         :param not_send_msg: To not send message (False) or store content (list) instead
842         :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
843         """
844         # Allow _id to be a name or uuid
845 1         user = self.auth.get_user(_id)
846 1         uid = user["_id"]
847 1         self.check_conflict_on_del(session, uid, user)
848 1         if not dry_run:
849 1             v = self.auth.delete_user(uid)
850 1             self._send_msg("deleted", user, not_send_msg=not_send_msg)
851 1             return v
852 0         return None
853
854
855 1 class ProjectTopicAuth(ProjectTopic):
856     # topic = "projects"
857 1     topic_msg = "project"
858 1     schema_new = project_new_schema
859 1     schema_edit = project_edit_schema
860
861 1     def __init__(self, db, fs, msg, auth):
862 1         ProjectTopic.__init__(self, db, fs, msg, auth)
863         # self.auth = auth
864
865 1     def check_conflict_on_new(self, session, indata):
866         """
867         Check that the data to be inserted is valid
868
869         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
870         :param indata: data to be inserted
871         :return: None or raises EngineException
872         """
873 1         project_name = indata.get("name")
874 1         if is_valid_uuid(project_name):
875 1             raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
876                                   HTTPStatus.UNPROCESSABLE_ENTITY)
877
878 1         project_list = self.auth.get_project_list(filter_q={"name": project_name})
879
880 1         if project_list:
881 1             raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
882
883 1     def check_conflict_on_edit(self, session, final_content, edit_content, _id):
884         """
885         Check that the data to be edited/uploaded is valid
886
887         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
888         :param final_content: data once modified
889         :param edit_content: incremental data that contains the modifications to apply
890         :param _id: internal _id
891         :return: None or raises EngineException
892         """
893
894 1         project_name = edit_content.get("name")
895 1         if project_name != final_content["name"]:  # It is a true renaming
896 1             if is_valid_uuid(project_name):
897 1                 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
898                                       HTTPStatus.UNPROCESSABLE_ENTITY)
899
900 1             if final_content["name"] == "admin":
901 1                 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
902
903             # Check that project name is not used, regardless keystone already checks this
904 1             if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
905 1                 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
906
907 1     def check_conflict_on_del(self, session, _id, db_content):
908         """
909         Check if deletion can be done because of dependencies if it is not force. To override
910
911         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
912         :param _id: internal _id
913         :param db_content: The database content of this item _id
914         :return: None if ok or raises EngineException with the conflict
915         """
916
917 1         def check_rw_projects(topic, title, id_field):
918 1             for desc in self.db.get_list(topic):
919 1                 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
920 1                     raise EngineException("Project '{}' ({}) is being used by {} '{}'"
921                                           .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
922
923 1         if _id in session["project_id"]:
924 1             raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
925
926 1         if db_content["name"] == "admin":
927 1             raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
928
929         # If any user is using this project, raise CONFLICT exception
930 1         if not session["force"]:
931 1             for user in self.auth.get_user_list():
932 1                 for prm in user.get("project_role_mappings"):
933 1                     if prm["project"] == _id:
934 1                         raise EngineException("Project '{}' ({}) is being used by user '{}'"
935                                               .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
936
937         # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
938 1         if not session["force"]:
939 1             check_rw_projects("vnfds", "VNF Descriptor", "id")
940 1             check_rw_projects("nsds", "NS Descriptor", "id")
941 1             check_rw_projects("nsts", "NS Template", "id")
942 1             check_rw_projects("pdus", "PDU Descriptor", "name")
943
944 1     def new(self, rollback, session, indata=None, kwargs=None, headers=None):
945         """
946         Creates a new entry into the authentication backend.
947
948         NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
949
950         :param rollback: list to append created items at database in case a rollback may to be done
951         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
952         :param indata: data to be inserted
953         :param kwargs: used to override the indata descriptor
954         :param headers: http request headers
955         :return: _id: identity of the inserted data, operation _id (None)
956         """
957 1         try:
958 1             content = BaseTopic._remove_envelop(indata)
959
960             # Override descriptor with query string kwargs
961 1             BaseTopic._update_input_with_kwargs(content, kwargs)
962 1             content = self._validate_input_new(content, session["force"])
963 1             self.check_conflict_on_new(session, content)
964 1             self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
965 1             _id = self.auth.create_project(content)
966 1             rollback.append({"topic": self.topic, "_id": _id})
967 1             self._send_msg("created", content, not_send_msg=None)
968 1             return _id, None
969 1         except ValidationError as e:
970 1             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
971
972 1     def show(self, session, _id, api_req=False):
973         """
974         Get complete information on an topic
975
976         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
977         :param _id: server internal id
978         :param api_req: True if this call is serving an external API request. False if serving internal request.
979         :return: dictionary, raise exception if not found.
980         """
981         # Allow _id to be a name or uuid
982 1         filter_q = {self.id_field(self.topic, _id): _id}
983         # projects = self.auth.get_project_list(filter_q=filter_q)
984 1         projects = self.list(session, filter_q)   # To allow default filtering (Bug 853)
985 1         if len(projects) == 1:
986 1             return projects[0]
987 0         elif len(projects) > 1:
988 0             raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
989         else:
990 0             raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
991
992 1     def list(self, session, filter_q=None, api_req=False):
993         """
994         Get a list of the topic that matches a filter
995
996         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
997         :param filter_q: filter of data to be applied
998         :return: The list, it can be empty if no one match the filter.
999         """
1000 1         project_list = self.auth.get_project_list(filter_q)
1001 1         if not session["allow_show_user_project_role"]:
1002             # Bug 853 - Default filtering
1003 0             user = self.auth.get_user(session["username"])
1004 0             projects = [prm["project"] for prm in user["project_role_mappings"]]
1005 0             project_list = [proj for proj in project_list if proj["_id"] in projects]
1006 1         return project_list
1007
1008 1     def delete(self, session, _id, dry_run=False, not_send_msg=None):
1009         """
1010         Delete item by its internal _id
1011
1012         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1013         :param _id: server internal id
1014         :param dry_run: make checking but do not delete
1015         :param not_send_msg: To not send message (False) or store content (list) instead
1016         :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1017         """
1018         # Allow _id to be a name or uuid
1019 1         proj = self.auth.get_project(_id)
1020 1         pid = proj["_id"]
1021 1         self.check_conflict_on_del(session, pid, proj)
1022 1         if not dry_run:
1023 1             v = self.auth.delete_project(pid)
1024 1             self._send_msg("deleted", proj, not_send_msg=None)
1025 1             return v
1026 0         return None
1027
1028 1     def edit(self, session, _id, indata=None, kwargs=None, content=None):
1029         """
1030         Updates a project entry.
1031
1032         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1033         :param _id:
1034         :param indata: data to be inserted
1035         :param kwargs: used to override the indata descriptor
1036         :param content:
1037         :return: _id: identity of the inserted data.
1038         """
1039 1         indata = self._remove_envelop(indata)
1040
1041         # Override descriptor with query string kwargs
1042 1         if kwargs:
1043 0             BaseTopic._update_input_with_kwargs(indata, kwargs)
1044 1         try:
1045 1             if not content:
1046 1                 content = self.show(session, _id)
1047 1             indata = self._validate_input_edit(indata, content, force=session["force"])
1048 1             self.check_conflict_on_edit(session, content, indata, _id=_id)
1049 1             self.format_on_edit(content, indata)
1050 1             content_original = copy.deepcopy(content)
1051 1             deep_update_rfc7396(content, indata)
1052 1             self.auth.update_project(content["_id"], content)
1053 1             proj_data = {"_id": _id, "changes": indata, "original": content_original}
1054 1             self._send_msg("edited", proj_data, not_send_msg=None)
1055 1         except ValidationError as e:
1056 1             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1057
1058
1059 1 class RoleTopicAuth(BaseTopic):
1060 1     topic = "roles"
1061 1     topic_msg = None    # "roles"
1062 1     schema_new = roles_new_schema
1063 1     schema_edit = roles_edit_schema
1064 1     multiproject = False
1065
1066 1     def __init__(self, db, fs, msg, auth):
1067 1         BaseTopic.__init__(self, db, fs, msg, auth)
1068         # self.auth = auth
1069 1         self.operations = auth.role_permissions
1070         # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1071
1072 1     @staticmethod
1073     def validate_role_definition(operations, role_definitions):
1074         """
1075         Validates the role definition against the operations defined in
1076         the resources to operations files.
1077
1078         :param operations: operations list
1079         :param role_definitions: role definition to test
1080         :return: None if ok, raises ValidationError exception on error
1081         """
1082 1         if not role_definitions.get("permissions"):
1083 1             return
1084 1         ignore_fields = ["admin", "default"]
1085 1         for role_def in role_definitions["permissions"].keys():
1086 1             if role_def in ignore_fields:
1087 0                 continue
1088 1             if role_def[-1] == ":":
1089 0                 raise ValidationError("Operation cannot end with ':'")
1090
1091 1             match = next((op for op in operations if op == role_def or op.startswith(role_def + ":")), None)
1092
1093 1             if not match:
1094 1                 raise ValidationError("Invalid permission '{}'".format(role_def))
1095
1096 1     def _validate_input_new(self, input, force=False):
1097         """
1098         Validates input user content for a new entry.
1099
1100         :param input: user input content for the new topic
1101         :param force: may be used for being more tolerant
1102         :return: The same input content, or a changed version of it.
1103         """
1104 1         if self.schema_new:
1105 1             validate_input(input, self.schema_new)
1106 1             self.validate_role_definition(self.operations, input)
1107
1108 1         return input
1109
1110 1     def _validate_input_edit(self, input, content, force=False):
1111         """
1112         Validates input user content for updating an entry.
1113
1114         :param input: user input content for the new topic
1115         :param force: may be used for being more tolerant
1116         :return: The same input content, or a changed version of it.
1117         """
1118 1         if self.schema_edit:
1119 1             validate_input(input, self.schema_edit)
1120 1             self.validate_role_definition(self.operations, input)
1121
1122 1         return input
1123
1124 1     def check_conflict_on_new(self, session, indata):
1125         """
1126         Check that the data to be inserted is valid
1127
1128         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1129         :param indata: data to be inserted
1130         :return: None or raises EngineException
1131         """
1132         # check name is not uuid
1133 1         role_name = indata.get("name")
1134 1         if is_valid_uuid(role_name):
1135 1             raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1136                                   HTTPStatus.UNPROCESSABLE_ENTITY)
1137         # check name not exists
1138 1         name = indata["name"]
1139         # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1140 1         if self.auth.get_role_list({"name": name}):
1141 1             raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
1142
1143 1     def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1144         """
1145         Check that the data to be edited/uploaded is valid
1146
1147         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1148         :param final_content: data once modified
1149         :param edit_content: incremental data that contains the modifications to apply
1150         :param _id: internal _id
1151         :return: None or raises EngineException
1152         """
1153 1         if "default" not in final_content["permissions"]:
1154 1             final_content["permissions"]["default"] = False
1155 1         if "admin" not in final_content["permissions"]:
1156 1             final_content["permissions"]["admin"] = False
1157
1158         # check name is not uuid
1159 1         role_name = edit_content.get("name")
1160 1         if is_valid_uuid(role_name):
1161 1             raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1162                                   HTTPStatus.UNPROCESSABLE_ENTITY)
1163
1164         # Check renaming of admin roles
1165 1         role = self.auth.get_role(_id)
1166 1         if role["name"] in ["system_admin", "project_admin"]:
1167 1             raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1168
1169         # check name not exists
1170 1         if "name" in edit_content:
1171 1             role_name = edit_content["name"]
1172             # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1173 1             roles = self.auth.get_role_list({"name": role_name})
1174 1             if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
1175 1                 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
1176
1177 1     def check_conflict_on_del(self, session, _id, db_content):
1178         """
1179         Check if deletion can be done because of dependencies if it is not force. To override
1180
1181         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1182         :param _id: internal _id
1183         :param db_content: The database content of this item _id
1184         :return: None if ok or raises EngineException with the conflict
1185         """
1186 1         role = self.auth.get_role(_id)
1187 1         if role["name"] in ["system_admin", "project_admin"]:
1188 1             raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1189
1190         # If any user is using this role, raise CONFLICT exception
1191 1         if not session["force"]:
1192 1             for user in self.auth.get_user_list():
1193 1                 for prm in user.get("project_role_mappings"):
1194 1                     if prm["role"] == _id:
1195 1                         raise EngineException("Role '{}' ({}) is being used by user '{}'"
1196                                               .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
1197
1198 1     @staticmethod
1199 1     def format_on_new(content, project_id=None, make_public=False):   # TO BE REMOVED ?
1200         """
1201         Modifies content descriptor to include _admin
1202
1203         :param content: descriptor to be modified
1204         :param project_id: if included, it add project read/write permissions
1205         :param make_public: if included it is generated as public for reading.
1206         :return: None, but content is modified
1207         """
1208 1         now = time()
1209 1         if "_admin" not in content:
1210 1             content["_admin"] = {}
1211 1         if not content["_admin"].get("created"):
1212 1             content["_admin"]["created"] = now
1213 1         content["_admin"]["modified"] = now
1214
1215 1         if "permissions" not in content:
1216 0             content["permissions"] = {}
1217
1218 1         if "default" not in content["permissions"]:
1219 1             content["permissions"]["default"] = False
1220 1         if "admin" not in content["permissions"]:
1221 1             content["permissions"]["admin"] = False
1222
1223 1     @staticmethod
1224     def format_on_edit(final_content, edit_content):
1225         """
1226         Modifies final_content descriptor to include the modified date.
1227
1228         :param final_content: final descriptor generated
1229         :param edit_content: alterations to be include
1230         :return: None, but final_content is modified
1231         """
1232 1         if "_admin" in final_content:
1233 1             final_content["_admin"]["modified"] = time()
1234
1235 1         if "permissions" not in final_content:
1236 0             final_content["permissions"] = {}
1237
1238 1         if "default" not in final_content["permissions"]:
1239 0             final_content["permissions"]["default"] = False
1240 1         if "admin" not in final_content["permissions"]:
1241 0             final_content["permissions"]["admin"] = False
1242 1         return None
1243
1244 1     def show(self, session, _id, api_req=False):
1245         """
1246         Get complete information on an topic
1247
1248         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1249         :param _id: server internal id
1250         :param api_req: True if this call is serving an external API request. False if serving internal request.
1251         :return: dictionary, raise exception if not found.
1252         """
1253 1         filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1254         # roles = self.auth.get_role_list(filter_q)
1255 1         roles = self.list(session, filter_q)   # To allow default filtering (Bug 853)
1256 1         if not roles:
1257 0             raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1258 1         elif len(roles) > 1:
1259 0             raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1260 1         return roles[0]
1261
1262 1     def list(self, session, filter_q=None, api_req=False):
1263         """
1264         Get a list of the topic that matches a filter
1265
1266         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1267         :param filter_q: filter of data to be applied
1268         :return: The list, it can be empty if no one match the filter.
1269         """
1270 1         role_list = self.auth.get_role_list(filter_q)
1271 1         if not session["allow_show_user_project_role"]:
1272             # Bug 853 - Default filtering
1273 0             user = self.auth.get_user(session["username"])
1274 0             roles = [prm["role"] for prm in user["project_role_mappings"]]
1275 0             role_list = [role for role in role_list if role["_id"] in roles]
1276 1         return role_list
1277
1278 1     def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1279         """
1280         Creates a new entry into database.
1281
1282         :param rollback: list to append created items at database in case a rollback may to be done
1283         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1284         :param indata: data to be inserted
1285         :param kwargs: used to override the indata descriptor
1286         :param headers: http request headers
1287         :return: _id: identity of the inserted data, operation _id (None)
1288         """
1289 1         try:
1290 1             content = self._remove_envelop(indata)
1291
1292             # Override descriptor with query string kwargs
1293 1             self._update_input_with_kwargs(content, kwargs)
1294 1             content = self._validate_input_new(content, session["force"])
1295 1             self.check_conflict_on_new(session, content)
1296 1             self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
1297             # role_name = content["name"]
1298 1             rid = self.auth.create_role(content)
1299 1             content["_id"] = rid
1300             # _id = self.db.create(self.topic, content)
1301 1             rollback.append({"topic": self.topic, "_id": rid})
1302             # self._send_msg("created", content, not_send_msg=not_send_msg)
1303 1             return rid, None
1304 1         except ValidationError as e:
1305 1             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1306
1307 1     def delete(self, session, _id, dry_run=False, not_send_msg=None):
1308         """
1309         Delete item by its internal _id
1310
1311         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1312         :param _id: server internal id
1313         :param dry_run: make checking but do not delete
1314         :param not_send_msg: To not send message (False) or store content (list) instead
1315         :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1316         """
1317 1         filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1318 1         roles = self.auth.get_role_list(filter_q)
1319 1         if not roles:
1320 0             raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1321 1         elif len(roles) > 1:
1322 0             raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1323 1         rid = roles[0]["_id"]
1324 1         self.check_conflict_on_del(session, rid, None)
1325         # filter_q = {"_id": _id}
1326         # filter_q = {BaseTopic.id_field(self.topic, _id): _id}   # To allow role addressing by name
1327 1         if not dry_run:
1328 1             v = self.auth.delete_role(rid)
1329             # v = self.db.del_one(self.topic, filter_q)
1330 1             return v
1331 0         return None
1332
1333 1     def edit(self, session, _id, indata=None, kwargs=None, content=None):
1334         """
1335         Updates a role entry.
1336
1337         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1338         :param _id:
1339         :param indata: data to be inserted
1340         :param kwargs: used to override the indata descriptor
1341         :param content:
1342         :return: _id: identity of the inserted data.
1343         """
1344 1         if kwargs:
1345 0             self._update_input_with_kwargs(indata, kwargs)
1346 1         try:
1347 1             if not content:
1348 1                 content = self.show(session, _id)
1349 1             indata = self._validate_input_edit(indata, content, force=session["force"])
1350 1             deep_update_rfc7396(content, indata)
1351 1             self.check_conflict_on_edit(session, content, indata, _id=_id)
1352 1             self.format_on_edit(content, indata)
1353 1             self.auth.update_role(content)
1354 1         except ValidationError as e:
1355 1             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)