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