1 # -*- coding: utf-8 -*-
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from uuid
import uuid4
18 from hashlib
import sha256
19 from http
import HTTPStatus
21 from osm_nbi
.validation
import (
26 vim_account_new_schema
,
27 vim_account_edit_schema
,
30 wim_account_new_schema
,
31 wim_account_edit_schema
,
34 k8scluster_new_schema
,
35 k8scluster_edit_schema
,
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
50 from osm_nbi
.temporal
.nbi_temporal
import NbiTemporal
52 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
55 class UserTopic(BaseTopic
):
58 schema_new
= user_new_schema
59 schema_edit
= user_edit_schema
62 def __init__(self
, db
, fs
, msg
, auth
):
63 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
66 def _get_project_filter(session
):
68 Generates a filter dictionary for querying database users.
69 Current policy is admin can show all, non admin, only its own user.
70 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
73 if session
["admin"]: # allows all
76 return {"username": session
["username"]}
78 def check_conflict_on_new(self
, session
, indata
):
79 # check username not exists
82 {"username": indata
.get("username")},
86 raise EngineException(
87 "username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
90 if not session
["force"]:
91 for p
in indata
.get("projects") or []:
92 # To allow project addressing by Name as well as ID
93 if not self
.db
.get_one(
95 {BaseTopic
.id_field("projects", p
): p
},
99 raise EngineException(
100 "project '{}' does not exist".format(p
), HTTPStatus
.CONFLICT
103 def check_conflict_on_del(self
, session
, _id
, db_content
):
105 Check if deletion can be done because of dependencies if it is not force. To override
106 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
107 :param _id: internal _id
108 :param db_content: The database content of this item _id
109 :return: None if ok or raises EngineException with the conflict
111 if _id
== session
["username"]:
112 raise EngineException(
113 "You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
117 def format_on_new(content
, project_id
=None, make_public
=False):
118 BaseTopic
.format_on_new(content
, make_public
=False)
119 # Removed so that the UUID is kept, to allow User Name modification
120 # content["_id"] = content["username"]
122 content
["_admin"]["salt"] = salt
123 if content
.get("password"):
124 content
["password"] = sha256(
125 content
["password"].encode("utf-8") + salt
.encode("utf-8")
127 if content
.get("project_role_mappings"):
129 mapping
["project"] for mapping
in content
["project_role_mappings"]
132 if content
.get("projects"):
133 content
["projects"] += projects
135 content
["projects"] = projects
138 def format_on_edit(final_content
, edit_content
):
139 BaseTopic
.format_on_edit(final_content
, edit_content
)
140 if edit_content
.get("password"):
142 final_content
["_admin"]["salt"] = salt
143 final_content
["password"] = sha256(
144 edit_content
["password"].encode("utf-8") + salt
.encode("utf-8")
148 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
149 if not session
["admin"]:
150 raise EngineException(
151 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
153 # Names that look like UUIDs are not allowed
154 name
= (indata
if indata
else kwargs
).get("username")
155 if is_valid_uuid(name
):
156 raise EngineException(
157 "Usernames that look like UUIDs are not allowed",
158 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
160 return BaseTopic
.edit(
161 self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
164 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
165 if not session
["admin"]:
166 raise EngineException(
167 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
169 # Names that look like UUIDs are not allowed
170 name
= indata
["username"] if indata
else kwargs
["username"]
171 if is_valid_uuid(name
):
172 raise EngineException(
173 "Usernames that look like UUIDs are not allowed",
174 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
176 return BaseTopic
.new(
177 self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
181 class ProjectTopic(BaseTopic
):
183 topic_msg
= "projects"
184 schema_new
= project_new_schema
185 schema_edit
= project_edit_schema
188 def __init__(self
, db
, fs
, msg
, auth
):
189 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
192 def _get_project_filter(session
):
194 Generates a filter dictionary for querying database users.
195 Current policy is admin can show all, non admin, only its own user.
196 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
199 if session
["admin"]: # allows all
202 return {"_id.cont": session
["project_id"]}
204 def check_conflict_on_new(self
, session
, indata
):
205 if not indata
.get("name"):
206 raise EngineException("missing 'name'")
207 # check name not exists
210 {"name": indata
.get("name")},
214 raise EngineException(
215 "name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
219 def format_on_new(content
, project_id
=None, make_public
=False):
220 BaseTopic
.format_on_new(content
, None)
221 # Removed so that the UUID is kept, to allow Project Name modification
222 # content["_id"] = content["name"]
224 def check_conflict_on_del(self
, session
, _id
, db_content
):
226 Check if deletion can be done because of dependencies if it is not force. To override
227 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
228 :param _id: internal _id
229 :param db_content: The database content of this item _id
230 :return: None if ok or raises EngineException with the conflict
232 if _id
in session
["project_id"]:
233 raise EngineException(
234 "You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
238 _filter
= {"projects": _id
}
239 if self
.db
.get_list("users", _filter
):
240 raise EngineException(
241 "There is some USER that contains this project",
242 http_code
=HTTPStatus
.CONFLICT
,
245 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
246 if not session
["admin"]:
247 raise EngineException(
248 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
250 # Names that look like UUIDs are not allowed
251 name
= (indata
if indata
else kwargs
).get("name")
252 if is_valid_uuid(name
):
253 raise EngineException(
254 "Project names that look like UUIDs are not allowed",
255 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
257 return BaseTopic
.edit(
258 self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
261 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
262 if not session
["admin"]:
263 raise EngineException(
264 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
266 # Names that look like UUIDs are not allowed
267 name
= indata
["name"] if indata
else kwargs
["name"]
268 if is_valid_uuid(name
):
269 raise EngineException(
270 "Project names that look like UUIDs are not allowed",
271 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
273 return BaseTopic
.new(
274 self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
278 class CommonVimWimSdn(BaseTopic
):
279 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
281 config_to_encrypt
= (
283 ) # what keys at config must be encrypted because contains passwords
284 password_to_encrypt
= "" # key that contains a password
287 def _create_operation(op_type
, params
=None):
289 Creates a dictionary with the information to an operation, similar to ns-lcm-op
290 :param op_type: can be create, edit, delete
291 :param params: operation input parameters
292 :return: new dictionary with
296 "lcmOperationType": op_type
,
297 "operationState": "PROCESSING",
299 "statusEnteredTime": now
,
300 "detailed-status": "",
301 "operationParams": params
,
304 def check_conflict_on_new(self
, session
, indata
):
306 Check that the data to be inserted is valid. It is checked that name is unique
307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
308 :param indata: data to be inserted
309 :return: None or raises EngineException
311 self
.check_unique_name(session
, indata
["name"], _id
=None)
313 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
315 Check that the data to be edited/uploaded is valid. It is checked that name is unique
316 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
317 :param final_content: data once modified. This method may change it.
318 :param edit_content: incremental data that contains the modifications to apply
319 :param _id: internal _id
320 :return: None or raises EngineException
322 if not session
["force"] and edit_content
.get("name"):
323 self
.check_unique_name(session
, edit_content
["name"], _id
=_id
)
327 def _validate_input_edit(self
, input, content
, force
=False):
329 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
330 :param input: user input content for the new topic
331 :param force: may be used for being more tolerant
332 :return: The same input content, or a changed version of it.
335 if "vim_type" in content
:
336 input["vim_type"] = content
["vim_type"]
337 return super()._validate
_input
_edit
(input, content
, force
)
339 def format_on_edit(self
, final_content
, edit_content
):
341 Modifies final_content inserting admin information upon edition
342 :param final_content: final content to be stored at database
343 :param edit_content: user requested update content
344 :return: operation id
346 super().format_on_edit(final_content
, edit_content
)
349 schema_version
= final_content
.get("schema_version")
351 if edit_content
.get(self
.password_to_encrypt
):
352 final_content
[self
.password_to_encrypt
] = self
.db
.encrypt(
353 edit_content
[self
.password_to_encrypt
],
354 schema_version
=schema_version
,
355 salt
=final_content
["_id"],
357 config_to_encrypt_keys
= self
.config_to_encrypt
.get(
359 ) or self
.config_to_encrypt
.get("default")
360 if edit_content
.get("config") and config_to_encrypt_keys
:
361 for p
in config_to_encrypt_keys
:
362 if edit_content
["config"].get(p
):
363 final_content
["config"][p
] = self
.db
.encrypt(
364 edit_content
["config"][p
],
365 schema_version
=schema_version
,
366 salt
=final_content
["_id"],
369 # create edit operation
370 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
371 return "{}:{}".format(
372 final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1
375 def format_on_new(self
, content
, project_id
=None, make_public
=False):
377 Modifies content descriptor to include _admin and insert create operation
378 :param content: descriptor to be modified
379 :param project_id: if included, it add project read/write permissions. Can be None or a list
380 :param make_public: if included it is generated as public for reading.
381 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
383 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
384 content
["schema_version"] = schema_version
= "1.11"
387 if content
.get(self
.password_to_encrypt
):
388 content
[self
.password_to_encrypt
] = self
.db
.encrypt(
389 content
[self
.password_to_encrypt
],
390 schema_version
=schema_version
,
393 config_to_encrypt_keys
= self
.config_to_encrypt
.get(
395 ) or self
.config_to_encrypt
.get("default")
396 if content
.get("config") and config_to_encrypt_keys
:
397 for p
in config_to_encrypt_keys
:
398 if content
["config"].get(p
):
399 content
["config"][p
] = self
.db
.encrypt(
400 content
["config"][p
],
401 schema_version
=schema_version
,
405 content
["_admin"]["operationalState"] = "PROCESSING"
408 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
409 content
["_admin"]["current_operation"] = None
410 # create Resource in Openstack based VIM
411 if content
.get("vim_type"):
412 if content
["vim_type"] == "openstack":
414 "ram": {"total": None, "used": None},
415 "vcpus": {"total": None, "used": None},
416 "instances": {"total": None, "used": None},
419 "volumes": {"total": None, "used": None},
420 "snapshots": {"total": None, "used": None},
421 "storage": {"total": None, "used": None},
424 "networks": {"total": None, "used": None},
425 "subnets": {"total": None, "used": None},
426 "floating_ips": {"total": None, "used": None},
428 content
["resources"] = {
434 return "{}:0".format(content
["_id"])
436 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
438 Delete item by its internal _id
439 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
440 :param _id: server internal id
441 :param dry_run: make checking but do not delete
442 :param not_send_msg: To not send message (False) or store content (list) instead
443 :return: operation id if it is ordered to delete. None otherwise
446 filter_q
= self
._get
_project
_filter
(session
)
447 filter_q
["_id"] = _id
448 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
450 self
.check_conflict_on_del(session
, _id
, db_content
)
454 # remove reference from project_read if there are more projects referencing it. If it last one,
455 # do not remove reference, but order via kafka to delete it
456 if session
["project_id"] and session
["project_id"]:
457 other_projects_referencing
= next(
460 for p
in db_content
["_admin"]["projects_read"]
461 if p
not in session
["project_id"] and p
!= "ANY"
466 # check if there are projects referencing it (apart from ANY, that means, public)....
467 if other_projects_referencing
:
468 # remove references but not delete
470 "_admin.projects_read": session
["project_id"],
471 "_admin.projects_write": session
["project_id"],
474 self
.topic
, filter_q
, update_dict
=None, pull_list
=update_dict_pull
481 for p
in db_content
["_admin"]["projects_write"]
482 if p
== "ANY" or p
in session
["project_id"]
487 raise EngineException(
488 "You have not write permission to delete it",
489 http_code
=HTTPStatus
.UNAUTHORIZED
,
494 self
.db
.del_one(self
.topic
, {"_id": _id
})
496 message
= {"_id": _id
, "op_id": op_id
}
497 # The vim_type is a temporary hack to shim in temporal workflows in the create
498 if "vim_type" in db_content
:
499 message
["vim_type"] = db_content
["vim_type"]
504 not_send_msg
=not_send_msg
,
507 update_dict
= {"_admin.to_delete": True}
511 update_dict
=update_dict
,
512 push
={"_admin.operations": self
._create
_operation
("delete")},
514 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
515 # so the -1 is not needed
516 op_id
= "{}:{}".format(
517 db_content
["_id"], len(db_content
["_admin"]["operations"])
519 message
= {"_id": _id
, "op_id": op_id
}
520 # The vim_type is a temporary hack to shim in temporal workflows in the create
521 if "vim_type" in db_content
:
522 message
["vim_type"] = db_content
["vim_type"]
527 not_send_msg
=not_send_msg
,
532 class VimAccountTopic(CommonVimWimSdn
):
533 topic
= "vim_accounts"
534 topic_msg
= "vim_account"
535 schema_new
= vim_account_new_schema
536 schema_edit
= vim_account_edit_schema
538 password_to_encrypt
= "vim_password"
539 config_to_encrypt
= {
540 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
548 valid_paas_providers
= ["juju"]
549 temporal
= NbiTemporal()
551 def check_conflict_on_new(self
, session
, indata
):
552 super().check_conflict_on_new(session
, indata
)
553 self
._check
_paas
_account
(indata
)
555 def _is_paas_vim_type(self
, indata
):
556 return indata
.get("vim_type") and indata
["vim_type"] == "paas"
558 def _check_paas_account(self
, indata
):
559 if self
._is
_paas
_vim
_type
(indata
):
560 self
._check
_paas
_provider
_is
_valid
(indata
)
562 def _check_paas_provider_is_valid(self
, indata
):
564 paas_provider
= indata
["config"]["paas_provider"]
565 if paas_provider
in self
.valid_paas_providers
:
569 raise EngineException(
570 "Invalid paas_provider for VIM account '{}'.".format(indata
["name"]),
571 HTTPStatus
.UNPROCESSABLE_ENTITY
,
574 def check_conflict_on_del(self
, session
, _id
, db_content
):
576 Check if deletion can be done because of dependencies if it is not force. To override
577 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
578 :param _id: internal _id
579 :param db_content: The database content of this item _id
580 :return: None if ok or raises EngineException with the conflict
584 # check if used by VNF
585 if self
.db
.get_list("vnfrs", {"vim-account-id": _id
}):
586 raise EngineException(
587 "There is at least one VNF using this VIM account",
588 http_code
=HTTPStatus
.CONFLICT
,
590 super().check_conflict_on_del(session
, _id
, db_content
)
592 def _send_msg(self
, action
, content
, not_send_msg
=None):
593 if self
._is
_paas
_vim
_type
(content
):
594 self
.temporal
.start_vim_workflow(action
, content
)
597 super()._send
_msg
(action
, content
, not_send_msg
)
600 class WimAccountTopic(CommonVimWimSdn
):
601 topic
= "wim_accounts"
602 topic_msg
= "wim_account"
603 schema_new
= wim_account_new_schema
604 schema_edit
= wim_account_edit_schema
606 password_to_encrypt
= "password"
607 config_to_encrypt
= {}
610 class SdnTopic(CommonVimWimSdn
):
613 quota_name
= "sdn_controllers"
614 schema_new
= sdn_new_schema
615 schema_edit
= sdn_edit_schema
617 password_to_encrypt
= "password"
618 config_to_encrypt
= {}
620 def _obtain_url(self
, input, create
):
621 if input.get("ip") or input.get("port"):
622 if not input.get("ip") or not input.get("port") or input.get("url"):
623 raise ValidationError(
624 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
626 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
629 elif create
and not input.get("url"):
630 raise ValidationError("You must provide 'url'")
633 def _validate_input_new(self
, input, force
=False):
634 input = super()._validate
_input
_new
(input, force
)
635 return self
._obtain
_url
(input, True)
637 def _validate_input_edit(self
, input, content
, force
=False):
638 input = super()._validate
_input
_edit
(input, content
, force
)
639 return self
._obtain
_url
(input, False)
642 class K8sClusterTopic(CommonVimWimSdn
):
643 topic
= "k8sclusters"
644 topic_msg
= "k8scluster"
645 schema_new
= k8scluster_new_schema
646 schema_edit
= k8scluster_edit_schema
648 password_to_encrypt
= None
649 config_to_encrypt
= {}
651 def format_on_new(self
, content
, project_id
=None, make_public
=False):
652 oid
= super().format_on_new(content
, project_id
, make_public
)
653 self
.db
.encrypt_decrypt_fields(
654 content
["credentials"],
656 ["password", "secret"],
657 schema_version
=content
["schema_version"],
660 # Add Helm/Juju Repo lists
661 repos
= {"helm-chart": [], "juju-bundle": []}
662 for proj
in content
["_admin"]["projects_read"]:
664 for repo
in self
.db
.get_list(
665 "k8srepos", {"_admin.projects_read": proj
}
667 if repo
["_id"] not in repos
[repo
["type"]]:
668 repos
[repo
["type"]].append(repo
["_id"])
670 content
["_admin"][k
.replace("-", "_") + "_repos"] = repos
[k
]
673 def format_on_edit(self
, final_content
, edit_content
):
674 if final_content
.get("schema_version") and edit_content
.get("credentials"):
675 self
.db
.encrypt_decrypt_fields(
676 edit_content
["credentials"],
678 ["password", "secret"],
679 schema_version
=final_content
["schema_version"],
680 salt
=final_content
["_id"],
683 final_content
["credentials"], edit_content
["credentials"]
685 oid
= super().format_on_edit(final_content
, edit_content
)
688 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
689 final_content
= super(CommonVimWimSdn
, self
).check_conflict_on_edit(
690 session
, final_content
, edit_content
, _id
692 final_content
= super().check_conflict_on_edit(
693 session
, final_content
, edit_content
, _id
695 # Update Helm/Juju Repo lists
696 repos
= {"helm-chart": [], "juju-bundle": []}
697 for proj
in session
.get("set_project", []):
699 for repo
in self
.db
.get_list(
700 "k8srepos", {"_admin.projects_read": proj
}
702 if repo
["_id"] not in repos
[repo
["type"]]:
703 repos
[repo
["type"]].append(repo
["_id"])
705 rlist
= k
.replace("-", "_") + "_repos"
706 if rlist
not in final_content
["_admin"]:
707 final_content
["_admin"][rlist
] = []
708 final_content
["_admin"][rlist
] += repos
[k
]
711 def check_conflict_on_del(self
, session
, _id
, db_content
):
713 Check if deletion can be done because of dependencies if it is not force. To override
714 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
715 :param _id: internal _id
716 :param db_content: The database content of this item _id
717 :return: None if ok or raises EngineException with the conflict
721 # check if used by VNF
722 filter_q
= {"kdur.k8s-cluster.id": _id
}
723 if session
["project_id"]:
724 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
725 if self
.db
.get_list("vnfrs", filter_q
):
726 raise EngineException(
727 "There is at least one VNF using this k8scluster",
728 http_code
=HTTPStatus
.CONFLICT
,
730 super().check_conflict_on_del(session
, _id
, db_content
)
733 class VcaTopic(CommonVimWimSdn
):
736 schema_new
= vca_new_schema
737 schema_edit
= vca_edit_schema
739 password_to_encrypt
= None
741 def format_on_new(self
, content
, project_id
=None, make_public
=False):
742 oid
= super().format_on_new(content
, project_id
, make_public
)
743 content
["schema_version"] = schema_version
= "1.11"
744 for key
in ["secret", "cacert"]:
745 content
[key
] = self
.db
.encrypt(
746 content
[key
], schema_version
=schema_version
, salt
=content
["_id"]
750 def format_on_edit(self
, final_content
, edit_content
):
751 oid
= super().format_on_edit(final_content
, edit_content
)
752 schema_version
= final_content
.get("schema_version")
753 for key
in ["secret", "cacert"]:
754 if key
in edit_content
:
755 final_content
[key
] = self
.db
.encrypt(
757 schema_version
=schema_version
,
758 salt
=final_content
["_id"],
762 def check_conflict_on_del(self
, session
, _id
, db_content
):
764 Check if deletion can be done because of dependencies if it is not force. To override
765 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
766 :param _id: internal _id
767 :param db_content: The database content of this item _id
768 :return: None if ok or raises EngineException with the conflict
772 # check if used by VNF
773 filter_q
= {"vca": _id
}
774 if session
["project_id"]:
775 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
776 if self
.db
.get_list("vim_accounts", filter_q
):
777 raise EngineException(
778 "There is at least one VIM account using this vca",
779 http_code
=HTTPStatus
.CONFLICT
,
781 super().check_conflict_on_del(session
, _id
, db_content
)
784 class K8sRepoTopic(CommonVimWimSdn
):
786 topic_msg
= "k8srepo"
787 schema_new
= k8srepo_new_schema
788 schema_edit
= k8srepo_edit_schema
790 password_to_encrypt
= None
791 config_to_encrypt
= {}
793 def format_on_new(self
, content
, project_id
=None, make_public
=False):
794 oid
= super().format_on_new(content
, project_id
, make_public
)
795 # Update Helm/Juju Repo lists
796 repo_list
= content
["type"].replace("-", "_") + "_repos"
797 for proj
in content
["_admin"]["projects_read"]:
802 "_admin.projects_read": proj
,
803 "_admin." + repo_list
+ ".ne": content
["_id"],
806 push
={"_admin." + repo_list
: content
["_id"]},
810 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
811 type = self
.db
.get_one("k8srepos", {"_id": _id
})["type"]
812 oid
= super().delete(session
, _id
, dry_run
, not_send_msg
)
814 # Remove from Helm/Juju Repo lists
815 repo_list
= type.replace("-", "_") + "_repos"
818 {"_admin." + repo_list
: _id
},
820 pull
={"_admin." + repo_list
: _id
},
825 class OsmRepoTopic(BaseTopic
):
827 topic_msg
= "osmrepos"
828 schema_new
= osmrepo_new_schema
829 schema_edit
= osmrepo_edit_schema
831 # TODO: Implement user/password
834 class UserTopicAuth(UserTopic
):
837 schema_new
= user_new_schema
838 schema_edit
= user_edit_schema
840 def __init__(self
, db
, fs
, msg
, auth
):
841 UserTopic
.__init
__(self
, db
, fs
, msg
, auth
)
844 def check_conflict_on_new(self
, session
, indata
):
846 Check that the data to be inserted is valid
848 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
849 :param indata: data to be inserted
850 :return: None or raises EngineException
852 username
= indata
.get("username")
853 if is_valid_uuid(username
):
854 raise EngineException(
855 "username '{}' cannot have a uuid format".format(username
),
856 HTTPStatus
.UNPROCESSABLE_ENTITY
,
859 # Check that username is not used, regardless keystone already checks this
860 if self
.auth
.get_user_list(filter_q
={"name": username
}):
861 raise EngineException(
862 "username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
865 if "projects" in indata
.keys():
866 # convert to new format project_role_mappings
867 role
= self
.auth
.get_role_list({"name": "project_admin"})
869 role
= self
.auth
.get_role_list()
871 raise AuthconnNotFoundException(
872 "Can't find default role for user '{}'".format(username
)
875 if not indata
.get("project_role_mappings"):
876 indata
["project_role_mappings"] = []
877 for project
in indata
["projects"]:
878 pid
= self
.auth
.get_project(project
)["_id"]
879 prm
= {"project": pid
, "role": rid
}
880 if prm
not in indata
["project_role_mappings"]:
881 indata
["project_role_mappings"].append(prm
)
882 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
883 # HTTPStatus.BAD_REQUEST)
885 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
887 Check that the data to be edited/uploaded is valid
889 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
890 :param final_content: data once modified
891 :param edit_content: incremental data that contains the modifications to apply
892 :param _id: internal _id
893 :return: None or raises EngineException
896 if "username" in edit_content
:
897 username
= edit_content
.get("username")
898 if is_valid_uuid(username
):
899 raise EngineException(
900 "username '{}' cannot have an uuid format".format(username
),
901 HTTPStatus
.UNPROCESSABLE_ENTITY
,
904 # Check that username is not used, regardless keystone already checks this
905 if self
.auth
.get_user_list(filter_q
={"name": username
}):
906 raise EngineException(
907 "username '{}' is already used".format(username
),
911 if final_content
["username"] == "admin":
912 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
913 if mapping
["project"] == "admin" and mapping
.get("role") in (
917 # TODO make this also available for project id and role id
918 raise EngineException(
919 "You cannot remove system_admin role from admin user",
920 http_code
=HTTPStatus
.FORBIDDEN
,
925 def check_conflict_on_del(self
, session
, _id
, db_content
):
927 Check if deletion can be done because of dependencies if it is not force. To override
928 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
929 :param _id: internal _id
930 :param db_content: The database content of this item _id
931 :return: None if ok or raises EngineException with the conflict
933 if db_content
["username"] == session
["username"]:
934 raise EngineException(
935 "You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
937 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
940 def format_on_show(content
):
942 Modifies the content of the role information to separate the role
943 metadata from the role definition.
945 project_role_mappings
= []
947 if "projects" in content
:
948 for project
in content
["projects"]:
949 for role
in project
["roles"]:
950 project_role_mappings
.append(
952 "project": project
["_id"],
953 "project_name": project
["name"],
955 "role_name": role
["name"],
958 del content
["projects"]
959 content
["project_role_mappings"] = project_role_mappings
963 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
965 Creates a new entry into the authentication backend.
967 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
969 :param rollback: list to append created items at database in case a rollback may to be done
970 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
971 :param indata: data to be inserted
972 :param kwargs: used to override the indata descriptor
973 :param headers: http request headers
974 :return: _id: identity of the inserted data, operation _id (None)
977 content
= BaseTopic
._remove
_envelop
(indata
)
979 # Override descriptor with query string kwargs
980 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
981 content
= self
._validate
_input
_new
(content
, session
["force"])
982 self
.check_conflict_on_new(session
, content
)
983 # self.format_on_new(content, session["project_id"], make_public=session["public"])
985 content
["_admin"] = {"created": now
, "modified": now
}
987 for prm
in content
.get("project_role_mappings", []):
988 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
989 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
990 pid
= proj
["_id"] if proj
else None
991 rid
= role
["_id"] if role
else None
992 prl
= {"project": pid
, "role": rid
}
995 content
["project_role_mappings"] = prms
996 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
997 _id
= self
.auth
.create_user(content
)["_id"]
999 rollback
.append({"topic": self
.topic
, "_id": _id
})
1000 # del content["password"]
1001 self
._send
_msg
("created", content
, not_send_msg
=None)
1003 except ValidationError
as e
:
1004 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1006 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1008 Get complete information on an topic
1010 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1011 :param _id: server internal id or username
1012 :param filter_q: dict: query parameter
1013 :param api_req: True if this call is serving an external API request. False if serving internal request.
1014 :return: dictionary, raise exception if not found.
1016 # Allow _id to be a name or uuid
1017 filter_q
= {"username": _id
}
1018 # users = self.auth.get_user_list(filter_q)
1019 users
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1022 elif len(users
) > 1:
1023 raise EngineException(
1024 "Too many users found for '{}'".format(_id
), HTTPStatus
.CONFLICT
1027 raise EngineException(
1028 "User '{}' not found".format(_id
), HTTPStatus
.NOT_FOUND
1031 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1033 Updates an user entry.
1035 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1037 :param indata: data to be inserted
1038 :param kwargs: used to override the indata descriptor
1040 :return: _id: identity of the inserted data.
1042 indata
= self
._remove
_envelop
(indata
)
1044 # Override descriptor with query string kwargs
1046 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
1049 content
= self
.show(session
, _id
)
1050 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1051 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1052 # self.format_on_edit(content, indata)
1055 "password" in indata
1056 or "username" in indata
1057 or indata
.get("remove_project_role_mappings")
1058 or indata
.get("add_project_role_mappings")
1059 or indata
.get("project_role_mappings")
1060 or indata
.get("projects")
1061 or indata
.get("add_projects")
1064 if indata
.get("project_role_mappings") and (
1065 indata
.get("remove_project_role_mappings")
1066 or indata
.get("add_project_role_mappings")
1068 raise EngineException(
1069 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1070 "' or 'remove_project_role_mappings'",
1071 http_code
=HTTPStatus
.BAD_REQUEST
,
1074 if indata
.get("projects") or indata
.get("add_projects"):
1075 role
= self
.auth
.get_role_list({"name": "project_admin"})
1077 role
= self
.auth
.get_role_list()
1079 raise AuthconnNotFoundException(
1080 "Can't find a default role for user '{}'".format(
1084 rid
= role
[0]["_id"]
1085 if "add_project_role_mappings" not in indata
:
1086 indata
["add_project_role_mappings"] = []
1087 if "remove_project_role_mappings" not in indata
:
1088 indata
["remove_project_role_mappings"] = []
1089 if isinstance(indata
.get("projects"), dict):
1090 # backward compatible
1091 for k
, v
in indata
["projects"].items():
1092 if k
.startswith("$") and v
is None:
1093 indata
["remove_project_role_mappings"].append(
1096 elif k
.startswith("$+"):
1097 indata
["add_project_role_mappings"].append(
1098 {"project": v
, "role": rid
}
1100 del indata
["projects"]
1101 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
1102 indata
["add_project_role_mappings"].append(
1103 {"project": proj
, "role": rid
}
1106 # user = self.show(session, _id) # Already in 'content'
1107 original_mapping
= content
["project_role_mappings"]
1109 mappings_to_add
= []
1110 mappings_to_remove
= []
1113 for to_remove
in indata
.get("remove_project_role_mappings", ()):
1114 for mapping
in original_mapping
:
1115 if to_remove
["project"] in (
1117 mapping
["project_name"],
1119 if not to_remove
.get("role") or to_remove
["role"] in (
1121 mapping
["role_name"],
1123 mappings_to_remove
.append(mapping
)
1126 for to_add
in indata
.get("add_project_role_mappings", ()):
1127 for mapping
in original_mapping
:
1128 if to_add
["project"] in (
1130 mapping
["project_name"],
1131 ) and to_add
["role"] in (
1133 mapping
["role_name"],
1135 if mapping
in mappings_to_remove
: # do not remove
1136 mappings_to_remove
.remove(mapping
)
1137 break # do not add, it is already at user
1139 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
1140 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
1141 mappings_to_add
.append({"project": pid
, "role": rid
})
1144 if indata
.get("project_role_mappings"):
1145 for to_set
in indata
["project_role_mappings"]:
1146 for mapping
in original_mapping
:
1147 if to_set
["project"] in (
1149 mapping
["project_name"],
1150 ) and to_set
["role"] in (
1152 mapping
["role_name"],
1154 if mapping
in mappings_to_remove
: # do not remove
1155 mappings_to_remove
.remove(mapping
)
1156 break # do not add, it is already at user
1158 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
1159 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
1160 mappings_to_add
.append({"project": pid
, "role": rid
})
1161 for mapping
in original_mapping
:
1162 for to_set
in indata
["project_role_mappings"]:
1163 if to_set
["project"] in (
1165 mapping
["project_name"],
1166 ) and to_set
["role"] in (
1168 mapping
["role_name"],
1173 if mapping
not in mappings_to_remove
: # do not remove
1174 mappings_to_remove
.append(mapping
)
1176 self
.auth
.update_user(
1179 "username": indata
.get("username"),
1180 "password": indata
.get("password"),
1181 "old_password": indata
.get("old_password"),
1182 "add_project_role_mappings": mappings_to_add
,
1183 "remove_project_role_mappings": mappings_to_remove
,
1186 data_to_send
= {"_id": _id
, "changes": indata
}
1187 self
._send
_msg
("edited", data_to_send
, not_send_msg
=None)
1190 except ValidationError
as e
:
1191 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1193 def list(self
, session
, filter_q
=None, api_req
=False):
1195 Get a list of the topic that matches a filter
1196 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1197 :param filter_q: filter of data to be applied
1198 :param api_req: True if this call is serving an external API request. False if serving internal request.
1199 :return: The list, it can be empty if no one match the filter.
1201 user_list
= self
.auth
.get_user_list(filter_q
)
1202 if not session
["allow_show_user_project_role"]:
1203 # Bug 853 - Default filtering
1205 usr
for usr
in user_list
if usr
["username"] == session
["username"]
1209 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1211 Delete item by its internal _id
1213 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1214 :param _id: server internal id
1215 :param force: indicates if deletion must be forced in case of conflict
1216 :param dry_run: make checking but do not delete
1217 :param not_send_msg: To not send message (False) or store content (list) instead
1218 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1220 # Allow _id to be a name or uuid
1221 user
= self
.auth
.get_user(_id
)
1223 self
.check_conflict_on_del(session
, uid
, user
)
1225 v
= self
.auth
.delete_user(uid
)
1226 self
._send
_msg
("deleted", user
, not_send_msg
=not_send_msg
)
1231 class ProjectTopicAuth(ProjectTopic
):
1232 # topic = "projects"
1233 topic_msg
= "project"
1234 schema_new
= project_new_schema
1235 schema_edit
= project_edit_schema
1237 def __init__(self
, db
, fs
, msg
, auth
):
1238 ProjectTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1241 def check_conflict_on_new(self
, session
, indata
):
1243 Check that the data to be inserted is valid
1245 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1246 :param indata: data to be inserted
1247 :return: None or raises EngineException
1249 project_name
= indata
.get("name")
1250 if is_valid_uuid(project_name
):
1251 raise EngineException(
1252 "project name '{}' cannot have an uuid format".format(project_name
),
1253 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1256 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
1259 raise EngineException(
1260 "project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
1263 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1265 Check that the data to be edited/uploaded is valid
1267 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1268 :param final_content: data once modified
1269 :param edit_content: incremental data that contains the modifications to apply
1270 :param _id: internal _id
1271 :return: None or raises EngineException
1274 project_name
= edit_content
.get("name")
1275 if project_name
!= final_content
["name"]: # It is a true renaming
1276 if is_valid_uuid(project_name
):
1277 raise EngineException(
1278 "project name '{}' cannot have an uuid format".format(project_name
),
1279 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1282 if final_content
["name"] == "admin":
1283 raise EngineException(
1284 "You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
1287 # Check that project name is not used, regardless keystone already checks this
1288 if project_name
and self
.auth
.get_project_list(
1289 filter_q
={"name": project_name
}
1291 raise EngineException(
1292 "project '{}' is already used".format(project_name
),
1293 HTTPStatus
.CONFLICT
,
1295 return final_content
1297 def check_conflict_on_del(self
, session
, _id
, db_content
):
1299 Check if deletion can be done because of dependencies if it is not force. To override
1301 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1302 :param _id: internal _id
1303 :param db_content: The database content of this item _id
1304 :return: None if ok or raises EngineException with the conflict
1307 def check_rw_projects(topic
, title
, id_field
):
1308 for desc
in self
.db
.get_list(topic
):
1311 in desc
["_admin"]["projects_read"]
1312 + desc
["_admin"]["projects_write"]
1314 raise EngineException(
1315 "Project '{}' ({}) is being used by {} '{}'".format(
1316 db_content
["name"], _id
, title
, desc
[id_field
]
1318 HTTPStatus
.CONFLICT
,
1321 if _id
in session
["project_id"]:
1322 raise EngineException(
1323 "You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
1326 if db_content
["name"] == "admin":
1327 raise EngineException(
1328 "You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
1331 # If any user is using this project, raise CONFLICT exception
1332 if not session
["force"]:
1333 for user
in self
.auth
.get_user_list():
1334 for prm
in user
.get("project_role_mappings"):
1335 if prm
["project"] == _id
:
1336 raise EngineException(
1337 "Project '{}' ({}) is being used by user '{}'".format(
1338 db_content
["name"], _id
, user
["username"]
1340 HTTPStatus
.CONFLICT
,
1343 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1344 if not session
["force"]:
1345 check_rw_projects("vnfds", "VNF Descriptor", "id")
1346 check_rw_projects("nsds", "NS Descriptor", "id")
1347 check_rw_projects("nsts", "NS Template", "id")
1348 check_rw_projects("pdus", "PDU Descriptor", "name")
1350 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1352 Creates a new entry into the authentication backend.
1354 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1356 :param rollback: list to append created items at database in case a rollback may to be done
1357 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1358 :param indata: data to be inserted
1359 :param kwargs: used to override the indata descriptor
1360 :param headers: http request headers
1361 :return: _id: identity of the inserted data, operation _id (None)
1364 content
= BaseTopic
._remove
_envelop
(indata
)
1366 # Override descriptor with query string kwargs
1367 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
1368 content
= self
._validate
_input
_new
(content
, session
["force"])
1369 self
.check_conflict_on_new(session
, content
)
1371 content
, project_id
=session
["project_id"], make_public
=session
["public"]
1373 _id
= self
.auth
.create_project(content
)
1374 rollback
.append({"topic": self
.topic
, "_id": _id
})
1375 self
._send
_msg
("created", content
, not_send_msg
=None)
1377 except ValidationError
as e
:
1378 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1380 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1382 Get complete information on an topic
1384 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1385 :param _id: server internal id
1386 :param filter_q: dict: query parameter
1387 :param api_req: True if this call is serving an external API request. False if serving internal request.
1388 :return: dictionary, raise exception if not found.
1390 # Allow _id to be a name or uuid
1391 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
1392 # projects = self.auth.get_project_list(filter_q=filter_q)
1393 projects
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1394 if len(projects
) == 1:
1396 elif len(projects
) > 1:
1397 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
1399 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
1401 def list(self
, session
, filter_q
=None, api_req
=False):
1403 Get a list of the topic that matches a filter
1405 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1406 :param filter_q: filter of data to be applied
1407 :return: The list, it can be empty if no one match the filter.
1409 project_list
= self
.auth
.get_project_list(filter_q
)
1410 if not session
["allow_show_user_project_role"]:
1411 # Bug 853 - Default filtering
1412 user
= self
.auth
.get_user(session
["username"])
1413 projects
= [prm
["project"] for prm
in user
["project_role_mappings"]]
1414 project_list
= [proj
for proj
in project_list
if proj
["_id"] in projects
]
1417 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1419 Delete item by its internal _id
1421 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1422 :param _id: server internal id
1423 :param dry_run: make checking but do not delete
1424 :param not_send_msg: To not send message (False) or store content (list) instead
1425 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1427 # Allow _id to be a name or uuid
1428 proj
= self
.auth
.get_project(_id
)
1430 self
.check_conflict_on_del(session
, pid
, proj
)
1432 v
= self
.auth
.delete_project(pid
)
1433 self
._send
_msg
("deleted", proj
, not_send_msg
=None)
1437 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1439 Updates a project entry.
1441 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1443 :param indata: data to be inserted
1444 :param kwargs: used to override the indata descriptor
1446 :return: _id: identity of the inserted data.
1448 indata
= self
._remove
_envelop
(indata
)
1450 # Override descriptor with query string kwargs
1452 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
1455 content
= self
.show(session
, _id
)
1456 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1457 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1458 self
.format_on_edit(content
, indata
)
1459 content_original
= copy
.deepcopy(content
)
1460 deep_update_rfc7396(content
, indata
)
1461 self
.auth
.update_project(content
["_id"], content
)
1462 proj_data
= {"_id": _id
, "changes": indata
, "original": content_original
}
1463 self
._send
_msg
("edited", proj_data
, not_send_msg
=None)
1464 except ValidationError
as e
:
1465 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1468 class RoleTopicAuth(BaseTopic
):
1470 topic_msg
= None # "roles"
1471 schema_new
= roles_new_schema
1472 schema_edit
= roles_edit_schema
1473 multiproject
= False
1475 def __init__(self
, db
, fs
, msg
, auth
):
1476 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1478 self
.operations
= auth
.role_permissions
1479 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1482 def validate_role_definition(operations
, role_definitions
):
1484 Validates the role definition against the operations defined in
1485 the resources to operations files.
1487 :param operations: operations list
1488 :param role_definitions: role definition to test
1489 :return: None if ok, raises ValidationError exception on error
1491 if not role_definitions
.get("permissions"):
1493 ignore_fields
= ["admin", "default"]
1494 for role_def
in role_definitions
["permissions"].keys():
1495 if role_def
in ignore_fields
:
1497 if role_def
[-1] == ":":
1498 raise ValidationError("Operation cannot end with ':'")
1503 for op
in operations
1504 if op
== role_def
or op
.startswith(role_def
+ ":")
1510 raise ValidationError("Invalid permission '{}'".format(role_def
))
1512 def _validate_input_new(self
, input, force
=False):
1514 Validates input user content for a new entry.
1516 :param input: user input content for the new topic
1517 :param force: may be used for being more tolerant
1518 :return: The same input content, or a changed version of it.
1521 validate_input(input, self
.schema_new
)
1522 self
.validate_role_definition(self
.operations
, input)
1526 def _validate_input_edit(self
, input, content
, force
=False):
1528 Validates input user content for updating an entry.
1530 :param input: user input content for the new topic
1531 :param force: may be used for being more tolerant
1532 :return: The same input content, or a changed version of it.
1534 if self
.schema_edit
:
1535 validate_input(input, self
.schema_edit
)
1536 self
.validate_role_definition(self
.operations
, input)
1540 def check_conflict_on_new(self
, session
, indata
):
1542 Check that the data to be inserted is valid
1544 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1545 :param indata: data to be inserted
1546 :return: None or raises EngineException
1548 # check name is not uuid
1549 role_name
= indata
.get("name")
1550 if is_valid_uuid(role_name
):
1551 raise EngineException(
1552 "role name '{}' cannot have an uuid format".format(role_name
),
1553 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1555 # check name not exists
1556 name
= indata
["name"]
1557 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1558 if self
.auth
.get_role_list({"name": name
}):
1559 raise EngineException(
1560 "role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
1563 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1565 Check that the data to be edited/uploaded is valid
1567 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1568 :param final_content: data once modified
1569 :param edit_content: incremental data that contains the modifications to apply
1570 :param _id: internal _id
1571 :return: None or raises EngineException
1573 if "default" not in final_content
["permissions"]:
1574 final_content
["permissions"]["default"] = False
1575 if "admin" not in final_content
["permissions"]:
1576 final_content
["permissions"]["admin"] = False
1578 # check name is not uuid
1579 role_name
= edit_content
.get("name")
1580 if is_valid_uuid(role_name
):
1581 raise EngineException(
1582 "role name '{}' cannot have an uuid format".format(role_name
),
1583 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1586 # Check renaming of admin roles
1587 role
= self
.auth
.get_role(_id
)
1588 if role
["name"] in ["system_admin", "project_admin"]:
1589 raise EngineException(
1590 "You cannot rename role '{}'".format(role
["name"]),
1591 http_code
=HTTPStatus
.FORBIDDEN
,
1594 # check name not exists
1595 if "name" in edit_content
:
1596 role_name
= edit_content
["name"]
1597 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1598 roles
= self
.auth
.get_role_list({"name": role_name
})
1599 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
1600 raise EngineException(
1601 "role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
1604 return final_content
1606 def check_conflict_on_del(self
, session
, _id
, db_content
):
1608 Check if deletion can be done because of dependencies if it is not force. To override
1610 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1611 :param _id: internal _id
1612 :param db_content: The database content of this item _id
1613 :return: None if ok or raises EngineException with the conflict
1615 role
= self
.auth
.get_role(_id
)
1616 if role
["name"] in ["system_admin", "project_admin"]:
1617 raise EngineException(
1618 "You cannot delete role '{}'".format(role
["name"]),
1619 http_code
=HTTPStatus
.FORBIDDEN
,
1622 # If any user is using this role, raise CONFLICT exception
1623 if not session
["force"]:
1624 for user
in self
.auth
.get_user_list():
1625 for prm
in user
.get("project_role_mappings"):
1626 if prm
["role"] == _id
:
1627 raise EngineException(
1628 "Role '{}' ({}) is being used by user '{}'".format(
1629 role
["name"], _id
, user
["username"]
1631 HTTPStatus
.CONFLICT
,
1635 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1637 Modifies content descriptor to include _admin
1639 :param content: descriptor to be modified
1640 :param project_id: if included, it add project read/write permissions
1641 :param make_public: if included it is generated as public for reading.
1642 :return: None, but content is modified
1645 if "_admin" not in content
:
1646 content
["_admin"] = {}
1647 if not content
["_admin"].get("created"):
1648 content
["_admin"]["created"] = now
1649 content
["_admin"]["modified"] = now
1651 if "permissions" not in content
:
1652 content
["permissions"] = {}
1654 if "default" not in content
["permissions"]:
1655 content
["permissions"]["default"] = False
1656 if "admin" not in content
["permissions"]:
1657 content
["permissions"]["admin"] = False
1660 def format_on_edit(final_content
, edit_content
):
1662 Modifies final_content descriptor to include the modified date.
1664 :param final_content: final descriptor generated
1665 :param edit_content: alterations to be include
1666 :return: None, but final_content is modified
1668 if "_admin" in final_content
:
1669 final_content
["_admin"]["modified"] = time()
1671 if "permissions" not in final_content
:
1672 final_content
["permissions"] = {}
1674 if "default" not in final_content
["permissions"]:
1675 final_content
["permissions"]["default"] = False
1676 if "admin" not in final_content
["permissions"]:
1677 final_content
["permissions"]["admin"] = False
1680 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1682 Get complete information on an topic
1684 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1685 :param _id: server internal id
1686 :param filter_q: dict: query parameter
1687 :param api_req: True if this call is serving an external API request. False if serving internal request.
1688 :return: dictionary, raise exception if not found.
1690 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1691 # roles = self.auth.get_role_list(filter_q)
1692 roles
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1694 raise AuthconnNotFoundException(
1695 "Not found any role with filter {}".format(filter_q
)
1697 elif len(roles
) > 1:
1698 raise AuthconnConflictException(
1699 "Found more than one role with filter {}".format(filter_q
)
1703 def list(self
, session
, filter_q
=None, api_req
=False):
1705 Get a list of the topic that matches a filter
1707 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1708 :param filter_q: filter of data to be applied
1709 :return: The list, it can be empty if no one match the filter.
1711 role_list
= self
.auth
.get_role_list(filter_q
)
1712 if not session
["allow_show_user_project_role"]:
1713 # Bug 853 - Default filtering
1714 user
= self
.auth
.get_user(session
["username"])
1715 roles
= [prm
["role"] for prm
in user
["project_role_mappings"]]
1716 role_list
= [role
for role
in role_list
if role
["_id"] in roles
]
1719 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1721 Creates a new entry into database.
1723 :param rollback: list to append created items at database in case a rollback may to be done
1724 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1725 :param indata: data to be inserted
1726 :param kwargs: used to override the indata descriptor
1727 :param headers: http request headers
1728 :return: _id: identity of the inserted data, operation _id (None)
1731 content
= self
._remove
_envelop
(indata
)
1733 # Override descriptor with query string kwargs
1734 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1735 content
= self
._validate
_input
_new
(content
, session
["force"])
1736 self
.check_conflict_on_new(session
, content
)
1738 content
, project_id
=session
["project_id"], make_public
=session
["public"]
1740 # role_name = content["name"]
1741 rid
= self
.auth
.create_role(content
)
1742 content
["_id"] = rid
1743 # _id = self.db.create(self.topic, content)
1744 rollback
.append({"topic": self
.topic
, "_id": rid
})
1745 # self._send_msg("created", content, not_send_msg=not_send_msg)
1747 except ValidationError
as e
:
1748 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1750 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1752 Delete item by its internal _id
1754 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1755 :param _id: server internal id
1756 :param dry_run: make checking but do not delete
1757 :param not_send_msg: To not send message (False) or store content (list) instead
1758 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1760 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1761 roles
= self
.auth
.get_role_list(filter_q
)
1763 raise AuthconnNotFoundException(
1764 "Not found any role with filter {}".format(filter_q
)
1766 elif len(roles
) > 1:
1767 raise AuthconnConflictException(
1768 "Found more than one role with filter {}".format(filter_q
)
1770 rid
= roles
[0]["_id"]
1771 self
.check_conflict_on_del(session
, rid
, None)
1772 # filter_q = {"_id": _id}
1773 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1775 v
= self
.auth
.delete_role(rid
)
1776 # v = self.db.del_one(self.topic, filter_q)
1780 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1782 Updates a role entry.
1784 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1786 :param indata: data to be inserted
1787 :param kwargs: used to override the indata descriptor
1789 :return: _id: identity of the inserted data.
1792 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1795 content
= self
.show(session
, _id
)
1796 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1797 deep_update_rfc7396(content
, indata
)
1798 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1799 self
.format_on_edit(content
, indata
)
1800 self
.auth
.update_role(content
)
1801 except ValidationError
as e
:
1802 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)