Fixed scale validation for sol006
[osm/NBI.git] / 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 from uuid import uuid4
18 from hashlib import sha256
19 from http import HTTPStatus
20 from time import time
21 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 from osm_nbi.base_topic import BaseTopic, EngineException
28 from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
29 from osm_common.dbbase import deep_update_rfc7396
30 import copy
31
32 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
33
34
35 class UserTopic(BaseTopic):
36 topic = "users"
37 topic_msg = "users"
38 schema_new = user_new_schema
39 schema_edit = user_edit_schema
40 multiproject = False
41
42 def __init__(self, db, fs, msg, auth):
43 BaseTopic.__init__(self, db, fs, msg, auth)
44
45 @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 if session["admin"]: # allows all
54 return {}
55 else:
56 return {"username": session["username"]}
57
58 def check_conflict_on_new(self, session, indata):
59 # check username not exists
60 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
61 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
62 # check projects
63 if not session["force"]:
64 for p in indata.get("projects") or []:
65 # To allow project addressing by Name as well as ID
66 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
67 fail_on_more=False):
68 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
69
70 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 if _id == session["username"]:
79 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
80
81 @staticmethod
82 def format_on_new(content, project_id=None, make_public=False):
83 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 salt = uuid4().hex
87 content["_admin"]["salt"] = salt
88 if content.get("password"):
89 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
90 if content.get("project_role_mappings"):
91 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
92
93 if content.get("projects"):
94 content["projects"] += projects
95 else:
96 content["projects"] = projects
97
98 @staticmethod
99 def format_on_edit(final_content, edit_content):
100 BaseTopic.format_on_edit(final_content, edit_content)
101 if edit_content.get("password"):
102 salt = uuid4().hex
103 final_content["_admin"]["salt"] = salt
104 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
105 salt.encode('utf-8')).hexdigest()
106 return None
107
108 def edit(self, session, _id, indata=None, kwargs=None, content=None):
109 if not session["admin"]:
110 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
111 # Names that look like UUIDs are not allowed
112 name = (indata if indata else kwargs).get("username")
113 if is_valid_uuid(name):
114 raise EngineException("Usernames that look like UUIDs are not allowed",
115 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
116 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
117
118 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
119 if not session["admin"]:
120 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
121 # Names that look like UUIDs are not allowed
122 name = indata["username"] if indata else kwargs["username"]
123 if is_valid_uuid(name):
124 raise EngineException("Usernames that look like UUIDs are not allowed",
125 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
126 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
127
128
129 class ProjectTopic(BaseTopic):
130 topic = "projects"
131 topic_msg = "projects"
132 schema_new = project_new_schema
133 schema_edit = project_edit_schema
134 multiproject = False
135
136 def __init__(self, db, fs, msg, auth):
137 BaseTopic.__init__(self, db, fs, msg, auth)
138
139 @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 if session["admin"]: # allows all
148 return {}
149 else:
150 return {"_id.cont": session["project_id"]}
151
152 def check_conflict_on_new(self, session, indata):
153 if not indata.get("name"):
154 raise EngineException("missing 'name'")
155 # check name not exists
156 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
157 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
158
159 @staticmethod
160 def format_on_new(content, project_id=None, make_public=False):
161 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 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 if _id in session["project_id"]:
174 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
175 if session["force"]:
176 return
177 _filter = {"projects": _id}
178 if self.db.get_list("users", _filter):
179 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
180
181 def edit(self, session, _id, indata=None, kwargs=None, content=None):
182 if not session["admin"]:
183 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
184 # Names that look like UUIDs are not allowed
185 name = (indata if indata else kwargs).get("name")
186 if is_valid_uuid(name):
187 raise EngineException("Project names that look like UUIDs are not allowed",
188 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
189 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
190
191 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
192 if not session["admin"]:
193 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
194 # Names that look like UUIDs are not allowed
195 name = indata["name"] if indata else kwargs["name"]
196 if is_valid_uuid(name):
197 raise EngineException("Project names that look like UUIDs are not allowed",
198 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
199 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
200
201
202 class CommonVimWimSdn(BaseTopic):
203 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
204 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
205 password_to_encrypt = "" # key that contains a password
206
207 @staticmethod
208 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 now = time()
216 return {
217 "lcmOperationType": op_type,
218 "operationState": "PROCESSING",
219 "startTime": now,
220 "statusEnteredTime": now,
221 "detailed-status": "",
222 "operationParams": params,
223 }
224
225 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 self.check_unique_name(session, indata["name"], _id=None)
233
234 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 if not session["force"] and edit_content.get("name"):
244 self.check_unique_name(session, edit_content["name"], _id=_id)
245
246 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 super().format_on_edit(final_content, edit_content)
254
255 # encrypt passwords
256 schema_version = final_content.get("schema_version")
257 if schema_version:
258 if edit_content.get(self.password_to_encrypt):
259 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 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
263 if edit_content.get("config") and config_to_encrypt_keys:
264
265 for p in config_to_encrypt_keys:
266 if edit_content["config"].get(p):
267 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 final_content["_admin"]["operations"].append(self._create_operation("edit"))
273 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
274
275 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 super().format_on_new(content, project_id=project_id, make_public=make_public)
284 content["schema_version"] = schema_version = "1.11"
285
286 # encrypt passwords
287 if content.get(self.password_to_encrypt):
288 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
289 schema_version=schema_version,
290 salt=content["_id"])
291 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
292 if content.get("config") and config_to_encrypt_keys:
293 for p in config_to_encrypt_keys:
294 if content["config"].get(p):
295 content["config"][p] = self.db.encrypt(content["config"][p],
296 schema_version=schema_version,
297 salt=content["_id"])
298
299 content["_admin"]["operationalState"] = "PROCESSING"
300
301 # create operation
302 content["_admin"]["operations"] = [self._create_operation("create")]
303 content["_admin"]["current_operation"] = None
304
305 return "{}:0".format(content["_id"])
306
307 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 filter_q = self._get_project_filter(session)
318 filter_q["_id"] = _id
319 db_content = self.db.get_one(self.topic, filter_q)
320
321 self.check_conflict_on_del(session, _id, db_content)
322 if dry_run:
323 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 if session["project_id"] and session["project_id"]:
328 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 if other_projects_referencing:
333 # remove references but not delete
334 update_dict_pull = {"_admin.projects_read": session["project_id"],
335 "_admin.projects_write": session["project_id"]}
336 self.db.set_one(self.topic, filter_q, update_dict=None, pull_list=update_dict_pull)
337 return None
338 else:
339 can_write = next((p for p in db_content["_admin"]["projects_write"] if p == "ANY" or
340 p in session["project_id"]), None)
341 if not can_write:
342 raise EngineException("You have not write permission to delete it",
343 http_code=HTTPStatus.UNAUTHORIZED)
344
345 # It must be deleted
346 if session["force"]:
347 self.db.del_one(self.topic, {"_id": _id})
348 op_id = None
349 self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
350 else:
351 update_dict = {"_admin.to_delete": True}
352 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 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
359 self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
360 return op_id
361
362
363 class VimAccountTopic(CommonVimWimSdn):
364 topic = "vim_accounts"
365 topic_msg = "vim_account"
366 schema_new = vim_account_new_schema
367 schema_edit = vim_account_edit_schema
368 multiproject = True
369 password_to_encrypt = "vim_password"
370 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
371 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
372
373 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 if session["force"]:
382 return
383 # check if used by VNF
384 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
385 raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
386 super().check_conflict_on_del(session, _id, db_content)
387
388
389 class WimAccountTopic(CommonVimWimSdn):
390 topic = "wim_accounts"
391 topic_msg = "wim_account"
392 schema_new = wim_account_new_schema
393 schema_edit = wim_account_edit_schema
394 multiproject = True
395 password_to_encrypt = "wim_password"
396 config_to_encrypt = {}
397
398
399 class SdnTopic(CommonVimWimSdn):
400 topic = "sdns"
401 topic_msg = "sdn"
402 quota_name = "sdn_controllers"
403 schema_new = sdn_new_schema
404 schema_edit = sdn_edit_schema
405 multiproject = True
406 password_to_encrypt = "password"
407 config_to_encrypt = {}
408
409 def _obtain_url(self, input, create):
410 if input.get("ip") or input.get("port"):
411 if not input.get("ip") or not input.get("port") or input.get('url'):
412 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
413 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
414 del input["ip"]
415 del input["port"]
416 elif create and not input.get('url'):
417 raise ValidationError("You must provide 'url'")
418 return input
419
420 def _validate_input_new(self, input, force=False):
421 input = super()._validate_input_new(input, force)
422 return self._obtain_url(input, True)
423
424 def _validate_input_edit(self, input, content, force=False):
425 input = super()._validate_input_edit(input, content, force)
426 return self._obtain_url(input, False)
427
428
429 class K8sClusterTopic(CommonVimWimSdn):
430 topic = "k8sclusters"
431 topic_msg = "k8scluster"
432 schema_new = k8scluster_new_schema
433 schema_edit = k8scluster_edit_schema
434 multiproject = True
435 password_to_encrypt = None
436 config_to_encrypt = {}
437
438 def format_on_new(self, content, project_id=None, make_public=False):
439 oid = super().format_on_new(content, project_id, make_public)
440 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 repos = {"helm-chart": [], "juju-bundle": []}
444 for proj in content["_admin"]["projects_read"]:
445 if proj != 'ANY':
446 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
447 if repo["_id"] not in repos[repo["type"]]:
448 repos[repo["type"]].append(repo["_id"])
449 for k in repos:
450 content["_admin"][k.replace('-', '_')+"_repos"] = repos[k]
451 return oid
452
453 def format_on_edit(self, final_content, edit_content):
454 if final_content.get("schema_version") and edit_content.get("credentials"):
455 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
456 schema_version=final_content["schema_version"], salt=final_content["_id"])
457 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
458 oid = super().format_on_edit(final_content, edit_content)
459 return oid
460
461 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
462 super(CommonVimWimSdn, self).check_conflict_on_edit(session, final_content, edit_content, _id)
463 super().check_conflict_on_edit(session, final_content, edit_content, _id)
464 # Update Helm/Juju Repo lists
465 repos = {"helm-chart": [], "juju-bundle": []}
466 for proj in session.get("set_project", []):
467 if proj != 'ANY':
468 for repo in self.db.get_list("k8srepos", {"_admin.projects_read": proj}):
469 if repo["_id"] not in repos[repo["type"]]:
470 repos[repo["type"]].append(repo["_id"])
471 for k in repos:
472 rlist = k.replace('-', '_') + "_repos"
473 if rlist not in final_content["_admin"]:
474 final_content["_admin"][rlist] = []
475 final_content["_admin"][rlist] += repos[k]
476
477 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 if session["force"]:
486 return
487 # check if used by VNF
488 filter_q = {"kdur.k8s-cluster.id": _id}
489 if session["project_id"]:
490 filter_q["_admin.projects_read.cont"] = session["project_id"]
491 if self.db.get_list("vnfrs", filter_q):
492 raise EngineException("There is at least one VNF using this k8scluster", http_code=HTTPStatus.CONFLICT)
493 super().check_conflict_on_del(session, _id, db_content)
494
495
496 class K8sRepoTopic(CommonVimWimSdn):
497 topic = "k8srepos"
498 topic_msg = "k8srepo"
499 schema_new = k8srepo_new_schema
500 schema_edit = k8srepo_edit_schema
501 multiproject = True
502 password_to_encrypt = None
503 config_to_encrypt = {}
504
505 def format_on_new(self, content, project_id=None, make_public=False):
506 oid = super().format_on_new(content, project_id, make_public)
507 # Update Helm/Juju Repo lists
508 repo_list = content["type"].replace('-', '_')+"_repos"
509 for proj in content["_admin"]["projects_read"]:
510 if proj != 'ANY':
511 self.db.set_list("k8sclusters",
512 {"_admin.projects_read": proj, "_admin."+repo_list+".ne": content["_id"]}, {},
513 push={"_admin."+repo_list: content["_id"]})
514 return oid
515
516 def delete(self, session, _id, dry_run=False, not_send_msg=None):
517 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
518 oid = super().delete(session, _id, dry_run, not_send_msg)
519 if oid:
520 # Remove from Helm/Juju Repo lists
521 repo_list = type.replace('-', '_') + "_repos"
522 self.db.set_list("k8sclusters", {"_admin."+repo_list: _id}, {}, pull={"_admin."+repo_list: _id})
523 return oid
524
525
526 class OsmRepoTopic(BaseTopic):
527 topic = "osmrepos"
528 topic_msg = "osmrepos"
529 schema_new = osmrepo_new_schema
530 schema_edit = osmrepo_edit_schema
531 multiproject = True
532 # TODO: Implement user/password
533
534
535 class UserTopicAuth(UserTopic):
536 # topic = "users"
537 topic_msg = "users"
538 schema_new = user_new_schema
539 schema_edit = user_edit_schema
540
541 def __init__(self, db, fs, msg, auth):
542 UserTopic.__init__(self, db, fs, msg, auth)
543 # self.auth = auth
544
545 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 username = indata.get("username")
554 if is_valid_uuid(username):
555 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 if self.auth.get_user_list(filter_q={"name": username}):
560 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
561
562 if "projects" in indata.keys():
563 # convert to new format project_role_mappings
564 role = self.auth.get_role_list({"name": "project_admin"})
565 if not role:
566 role = self.auth.get_role_list()
567 if not role:
568 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
569 rid = role[0]["_id"]
570 if not indata.get("project_role_mappings"):
571 indata["project_role_mappings"] = []
572 for project in indata["projects"]:
573 pid = self.auth.get_project(project)["_id"]
574 prm = {"project": pid, "role": rid}
575 if prm not in indata["project_role_mappings"]:
576 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 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 if "username" in edit_content:
592 username = edit_content.get("username")
593 if is_valid_uuid(username):
594 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 if self.auth.get_user_list(filter_q={"name": username}):
599 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
600
601 if final_content["username"] == "admin":
602 for mapping in edit_content.get("remove_project_role_mappings", ()):
603 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 raise EngineException("You cannot remove system_admin role from admin user",
606 http_code=HTTPStatus.FORBIDDEN)
607
608 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 if db_content["username"] == session["username"]:
617 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 @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 project_role_mappings = []
627
628 if "projects" in content:
629 for project in content["projects"]:
630 for role in project["roles"]:
631 project_role_mappings.append({"project": project["_id"],
632 "project_name": project["name"],
633 "role": role["_id"],
634 "role_name": role["name"]})
635 del content["projects"]
636 content["project_role_mappings"] = project_role_mappings
637
638 return content
639
640 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 try:
654 content = BaseTopic._remove_envelop(indata)
655
656 # Override descriptor with query string kwargs
657 BaseTopic._update_input_with_kwargs(content, kwargs)
658 content = self._validate_input_new(content, session["force"])
659 self.check_conflict_on_new(session, content)
660 # self.format_on_new(content, session["project_id"], make_public=session["public"])
661 now = time()
662 content["_admin"] = {"created": now, "modified": now}
663 prms = []
664 for prm in content.get("project_role_mappings", []):
665 proj = self.auth.get_project(prm["project"], not session["force"])
666 role = self.auth.get_role(prm["role"], not session["force"])
667 pid = proj["_id"] if proj else None
668 rid = role["_id"] if role else None
669 prl = {"project": pid, "role": rid}
670 if prl not in prms:
671 prms.append(prl)
672 content["project_role_mappings"] = prms
673 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
674 _id = self.auth.create_user(content)["_id"]
675
676 rollback.append({"topic": self.topic, "_id": _id})
677 # del content["password"]
678 self._send_msg("created", content, not_send_msg=None)
679 return _id, None
680 except ValidationError as e:
681 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
682
683 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 filter_q = {"username": _id}
694 # users = self.auth.get_user_list(filter_q)
695 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
696 if len(users) == 1:
697 return users[0]
698 elif len(users) > 1:
699 raise EngineException("Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT)
700 else:
701 raise EngineException("User '{}' not found".format(_id), HTTPStatus.NOT_FOUND)
702
703 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 indata = self._remove_envelop(indata)
715
716 # Override descriptor with query string kwargs
717 if kwargs:
718 BaseTopic._update_input_with_kwargs(indata, kwargs)
719 try:
720 if not content:
721 content = self.show(session, _id)
722 indata = self._validate_input_edit(indata, content, force=session["force"])
723 self.check_conflict_on_edit(session, content, indata, _id=_id)
724 # self.format_on_edit(content, indata)
725
726 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 return _id
730 if indata.get("project_role_mappings") \
731 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
732 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 if indata.get("projects") or indata.get("add_projects"):
736 role = self.auth.get_role_list({"name": "project_admin"})
737 if not role:
738 role = self.auth.get_role_list()
739 if not role:
740 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
741 .format(content["username"]))
742 rid = role[0]["_id"]
743 if "add_project_role_mappings" not in indata:
744 indata["add_project_role_mappings"] = []
745 if "remove_project_role_mappings" not in indata:
746 indata["remove_project_role_mappings"] = []
747 if isinstance(indata.get("projects"), dict):
748 # backward compatible
749 for k, v in indata["projects"].items():
750 if k.startswith("$") and v is None:
751 indata["remove_project_role_mappings"].append({"project": k[1:]})
752 elif k.startswith("$+"):
753 indata["add_project_role_mappings"].append({"project": v, "role": rid})
754 del indata["projects"]
755 for proj in indata.get("projects", []) + indata.get("add_projects", []):
756 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
757
758 # user = self.show(session, _id) # Already in 'content'
759 original_mapping = content["project_role_mappings"]
760
761 mappings_to_add = []
762 mappings_to_remove = []
763
764 # remove
765 for to_remove in indata.get("remove_project_role_mappings", ()):
766 for mapping in original_mapping:
767 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
768 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
769 mappings_to_remove.append(mapping)
770
771 # add
772 for to_add in indata.get("add_project_role_mappings", ()):
773 for mapping in original_mapping:
774 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
775 to_add["role"] in (mapping["role"], mapping["role_name"]):
776
777 if mapping in mappings_to_remove: # do not remove
778 mappings_to_remove.remove(mapping)
779 break # do not add, it is already at user
780 else:
781 pid = self.auth.get_project(to_add["project"])["_id"]
782 rid = self.auth.get_role(to_add["role"])["_id"]
783 mappings_to_add.append({"project": pid, "role": rid})
784
785 # set
786 if indata.get("project_role_mappings"):
787 for to_set in indata["project_role_mappings"]:
788 for mapping in original_mapping:
789 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
790 to_set["role"] in (mapping["role"], mapping["role_name"]):
791 if mapping in mappings_to_remove: # do not remove
792 mappings_to_remove.remove(mapping)
793 break # do not add, it is already at user
794 else:
795 pid = self.auth.get_project(to_set["project"])["_id"]
796 rid = self.auth.get_role(to_set["role"])["_id"]
797 mappings_to_add.append({"project": pid, "role": rid})
798 for mapping in original_mapping:
799 for to_set in indata["project_role_mappings"]:
800 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
801 to_set["role"] in (mapping["role"], mapping["role_name"]):
802 break
803 else:
804 # delete
805 if mapping not in mappings_to_remove: # do not remove
806 mappings_to_remove.append(mapping)
807
808 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 data_to_send = {'_id': _id, "changes": indata}
813 self._send_msg("edited", data_to_send, not_send_msg=None)
814
815 # return _id
816 except ValidationError as e:
817 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
818
819 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 user_list = self.auth.get_user_list(filter_q)
828 if not session["allow_show_user_project_role"]:
829 # Bug 853 - Default filtering
830 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
831 return user_list
832
833 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 user = self.auth.get_user(_id)
846 uid = user["_id"]
847 self.check_conflict_on_del(session, uid, user)
848 if not dry_run:
849 v = self.auth.delete_user(uid)
850 self._send_msg("deleted", user, not_send_msg=not_send_msg)
851 return v
852 return None
853
854
855 class ProjectTopicAuth(ProjectTopic):
856 # topic = "projects"
857 topic_msg = "project"
858 schema_new = project_new_schema
859 schema_edit = project_edit_schema
860
861 def __init__(self, db, fs, msg, auth):
862 ProjectTopic.__init__(self, db, fs, msg, auth)
863 # self.auth = auth
864
865 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 project_name = indata.get("name")
874 if is_valid_uuid(project_name):
875 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
876 HTTPStatus.UNPROCESSABLE_ENTITY)
877
878 project_list = self.auth.get_project_list(filter_q={"name": project_name})
879
880 if project_list:
881 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
882
883 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 project_name = edit_content.get("name")
895 if project_name != final_content["name"]: # It is a true renaming
896 if is_valid_uuid(project_name):
897 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
898 HTTPStatus.UNPROCESSABLE_ENTITY)
899
900 if final_content["name"] == "admin":
901 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 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
905 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
906
907 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 def check_rw_projects(topic, title, id_field):
918 for desc in self.db.get_list(topic):
919 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
920 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
921 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
922
923 if _id in session["project_id"]:
924 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
925
926 if db_content["name"] == "admin":
927 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
928
929 # If any user is using this project, raise CONFLICT exception
930 if not session["force"]:
931 for user in self.auth.get_user_list():
932 for prm in user.get("project_role_mappings"):
933 if prm["project"] == _id:
934 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 if not session["force"]:
939 check_rw_projects("vnfds", "VNF Descriptor", "id")
940 check_rw_projects("nsds", "NS Descriptor", "id")
941 check_rw_projects("nsts", "NS Template", "id")
942 check_rw_projects("pdus", "PDU Descriptor", "name")
943
944 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 try:
958 content = BaseTopic._remove_envelop(indata)
959
960 # Override descriptor with query string kwargs
961 BaseTopic._update_input_with_kwargs(content, kwargs)
962 content = self._validate_input_new(content, session["force"])
963 self.check_conflict_on_new(session, content)
964 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
965 _id = self.auth.create_project(content)
966 rollback.append({"topic": self.topic, "_id": _id})
967 self._send_msg("created", content, not_send_msg=None)
968 return _id, None
969 except ValidationError as e:
970 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
971
972 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 filter_q = {self.id_field(self.topic, _id): _id}
983 # projects = self.auth.get_project_list(filter_q=filter_q)
984 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
985 if len(projects) == 1:
986 return projects[0]
987 elif len(projects) > 1:
988 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
989 else:
990 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
991
992 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 project_list = self.auth.get_project_list(filter_q)
1001 if not session["allow_show_user_project_role"]:
1002 # Bug 853 - Default filtering
1003 user = self.auth.get_user(session["username"])
1004 projects = [prm["project"] for prm in user["project_role_mappings"]]
1005 project_list = [proj for proj in project_list if proj["_id"] in projects]
1006 return project_list
1007
1008 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 proj = self.auth.get_project(_id)
1020 pid = proj["_id"]
1021 self.check_conflict_on_del(session, pid, proj)
1022 if not dry_run:
1023 v = self.auth.delete_project(pid)
1024 self._send_msg("deleted", proj, not_send_msg=None)
1025 return v
1026 return None
1027
1028 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 indata = self._remove_envelop(indata)
1040
1041 # Override descriptor with query string kwargs
1042 if kwargs:
1043 BaseTopic._update_input_with_kwargs(indata, kwargs)
1044 try:
1045 if not content:
1046 content = self.show(session, _id)
1047 indata = self._validate_input_edit(indata, content, force=session["force"])
1048 self.check_conflict_on_edit(session, content, indata, _id=_id)
1049 self.format_on_edit(content, indata)
1050 content_original = copy.deepcopy(content)
1051 deep_update_rfc7396(content, indata)
1052 self.auth.update_project(content["_id"], content)
1053 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1054 self._send_msg("edited", proj_data, not_send_msg=None)
1055 except ValidationError as e:
1056 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1057
1058
1059 class RoleTopicAuth(BaseTopic):
1060 topic = "roles"
1061 topic_msg = None # "roles"
1062 schema_new = roles_new_schema
1063 schema_edit = roles_edit_schema
1064 multiproject = False
1065
1066 def __init__(self, db, fs, msg, auth):
1067 BaseTopic.__init__(self, db, fs, msg, auth)
1068 # self.auth = auth
1069 self.operations = auth.role_permissions
1070 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1071
1072 @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 if not role_definitions.get("permissions"):
1083 return
1084 ignore_fields = ["admin", "default"]
1085 for role_def in role_definitions["permissions"].keys():
1086 if role_def in ignore_fields:
1087 continue
1088 if role_def[-1] == ":":
1089 raise ValidationError("Operation cannot end with ':'")
1090
1091 match = next((op for op in operations if op == role_def or op.startswith(role_def + ":")), None)
1092
1093 if not match:
1094 raise ValidationError("Invalid permission '{}'".format(role_def))
1095
1096 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 if self.schema_new:
1105 validate_input(input, self.schema_new)
1106 self.validate_role_definition(self.operations, input)
1107
1108 return input
1109
1110 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 if self.schema_edit:
1119 validate_input(input, self.schema_edit)
1120 self.validate_role_definition(self.operations, input)
1121
1122 return input
1123
1124 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 role_name = indata.get("name")
1134 if is_valid_uuid(role_name):
1135 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1136 HTTPStatus.UNPROCESSABLE_ENTITY)
1137 # check name not exists
1138 name = indata["name"]
1139 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1140 if self.auth.get_role_list({"name": name}):
1141 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
1142
1143 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 if "default" not in final_content["permissions"]:
1154 final_content["permissions"]["default"] = False
1155 if "admin" not in final_content["permissions"]:
1156 final_content["permissions"]["admin"] = False
1157
1158 # check name is not uuid
1159 role_name = edit_content.get("name")
1160 if is_valid_uuid(role_name):
1161 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1162 HTTPStatus.UNPROCESSABLE_ENTITY)
1163
1164 # Check renaming of admin roles
1165 role = self.auth.get_role(_id)
1166 if role["name"] in ["system_admin", "project_admin"]:
1167 raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1168
1169 # check name not exists
1170 if "name" in edit_content:
1171 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 roles = self.auth.get_role_list({"name": role_name})
1174 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
1175 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
1176
1177 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 role = self.auth.get_role(_id)
1187 if role["name"] in ["system_admin", "project_admin"]:
1188 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 if not session["force"]:
1192 for user in self.auth.get_user_list():
1193 for prm in user.get("project_role_mappings"):
1194 if prm["role"] == _id:
1195 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1196 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
1197
1198 @staticmethod
1199 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 now = time()
1209 if "_admin" not in content:
1210 content["_admin"] = {}
1211 if not content["_admin"].get("created"):
1212 content["_admin"]["created"] = now
1213 content["_admin"]["modified"] = now
1214
1215 if "permissions" not in content:
1216 content["permissions"] = {}
1217
1218 if "default" not in content["permissions"]:
1219 content["permissions"]["default"] = False
1220 if "admin" not in content["permissions"]:
1221 content["permissions"]["admin"] = False
1222
1223 @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 if "_admin" in final_content:
1233 final_content["_admin"]["modified"] = time()
1234
1235 if "permissions" not in final_content:
1236 final_content["permissions"] = {}
1237
1238 if "default" not in final_content["permissions"]:
1239 final_content["permissions"]["default"] = False
1240 if "admin" not in final_content["permissions"]:
1241 final_content["permissions"]["admin"] = False
1242 return None
1243
1244 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 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1254 # roles = self.auth.get_role_list(filter_q)
1255 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
1256 if not roles:
1257 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1258 elif len(roles) > 1:
1259 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1260 return roles[0]
1261
1262 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 role_list = self.auth.get_role_list(filter_q)
1271 if not session["allow_show_user_project_role"]:
1272 # Bug 853 - Default filtering
1273 user = self.auth.get_user(session["username"])
1274 roles = [prm["role"] for prm in user["project_role_mappings"]]
1275 role_list = [role for role in role_list if role["_id"] in roles]
1276 return role_list
1277
1278 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 try:
1290 content = self._remove_envelop(indata)
1291
1292 # Override descriptor with query string kwargs
1293 self._update_input_with_kwargs(content, kwargs)
1294 content = self._validate_input_new(content, session["force"])
1295 self.check_conflict_on_new(session, content)
1296 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
1297 # role_name = content["name"]
1298 rid = self.auth.create_role(content)
1299 content["_id"] = rid
1300 # _id = self.db.create(self.topic, content)
1301 rollback.append({"topic": self.topic, "_id": rid})
1302 # self._send_msg("created", content, not_send_msg=not_send_msg)
1303 return rid, None
1304 except ValidationError as e:
1305 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1306
1307 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 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1318 roles = self.auth.get_role_list(filter_q)
1319 if not roles:
1320 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1321 elif len(roles) > 1:
1322 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1323 rid = roles[0]["_id"]
1324 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 if not dry_run:
1328 v = self.auth.delete_role(rid)
1329 # v = self.db.del_one(self.topic, filter_q)
1330 return v
1331 return None
1332
1333 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 if kwargs:
1345 self._update_input_with_kwargs(indata, kwargs)
1346 try:
1347 if not content:
1348 content = self.show(session, _id)
1349 indata = self._validate_input_edit(indata, content, force=session["force"])
1350 deep_update_rfc7396(content, indata)
1351 self.check_conflict_on_edit(session, content, indata, _id=_id)
1352 self.format_on_edit(content, indata)
1353 self.auth.update_role(content)
1354 except ValidationError as e:
1355 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)