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 user_new_schema
, user_edit_schema
, project_new_schema
, project_edit_schema
, \
22 vim_account_new_schema
, vim_account_edit_schema
, sdn_new_schema
, sdn_edit_schema
, \
23 wim_account_new_schema
, wim_account_edit_schema
, roles_new_schema
, roles_edit_schema
, \
24 validate_input
, ValidationError
, is_valid_uuid
# To check that User/Project Names don't look like UUIDs
25 from osm_nbi
.base_topic
import BaseTopic
, EngineException
26 from osm_nbi
.authconn
import AuthconnNotFoundException
, AuthconnConflictException
27 from osm_common
.dbbase
import deep_update_rfc7396
29 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
32 class UserTopic(BaseTopic
):
35 schema_new
= user_new_schema
36 schema_edit
= user_edit_schema
39 def __init__(self
, db
, fs
, msg
):
40 BaseTopic
.__init
__(self
, db
, fs
, msg
)
43 def _get_project_filter(session
):
45 Generates a filter dictionary for querying database users.
46 Current policy is admin can show all, non admin, only its own user.
47 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
50 if session
["admin"]: # allows all
53 return {"username": session
["username"]}
55 def check_conflict_on_new(self
, session
, indata
):
56 # check username not exists
57 if self
.db
.get_one(self
.topic
, {"username": indata
.get("username")}, fail_on_empty
=False, fail_on_more
=False):
58 raise EngineException("username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
)
60 if not session
["force"]:
61 for p
in indata
.get("projects") or []:
62 # To allow project addressing by Name as well as ID
63 if not self
.db
.get_one("projects", {BaseTopic
.id_field("projects", p
): p
}, fail_on_empty
=False,
65 raise EngineException("project '{}' does not exist".format(p
), HTTPStatus
.CONFLICT
)
67 def check_conflict_on_del(self
, session
, _id
, db_content
):
69 Check if deletion can be done because of dependencies if it is not force. To override
70 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
71 :param _id: internal _id
72 :param db_content: The database content of this item _id
73 :return: None if ok or raises EngineException with the conflict
75 if _id
== session
["username"]:
76 raise EngineException("You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
)
79 def format_on_new(content
, project_id
=None, make_public
=False):
80 BaseTopic
.format_on_new(content
, make_public
=False)
81 # Removed so that the UUID is kept, to allow User Name modification
82 # content["_id"] = content["username"]
84 content
["_admin"]["salt"] = salt
85 if content
.get("password"):
86 content
["password"] = sha256(content
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
87 if content
.get("project_role_mappings"):
88 projects
= [mapping
["project"] for mapping
in content
["project_role_mappings"]]
90 if content
.get("projects"):
91 content
["projects"] += projects
93 content
["projects"] = projects
96 def format_on_edit(final_content
, edit_content
):
97 BaseTopic
.format_on_edit(final_content
, edit_content
)
98 if edit_content
.get("password"):
100 final_content
["_admin"]["salt"] = salt
101 final_content
["password"] = sha256(edit_content
["password"].encode('utf-8') +
102 salt
.encode('utf-8')).hexdigest()
105 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
106 if not session
["admin"]:
107 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
108 # Names that look like UUIDs are not allowed
109 name
= (indata
if indata
else kwargs
).get("username")
110 if is_valid_uuid(name
):
111 raise EngineException("Usernames that look like UUIDs are not allowed",
112 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
113 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
115 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
116 if not session
["admin"]:
117 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
118 # Names that look like UUIDs are not allowed
119 name
= indata
["username"] if indata
else kwargs
["username"]
120 if is_valid_uuid(name
):
121 raise EngineException("Usernames that look like UUIDs are not allowed",
122 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
123 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
126 class ProjectTopic(BaseTopic
):
128 topic_msg
= "projects"
129 schema_new
= project_new_schema
130 schema_edit
= project_edit_schema
133 def __init__(self
, db
, fs
, msg
):
134 BaseTopic
.__init
__(self
, db
, fs
, msg
)
137 def _get_project_filter(session
):
139 Generates a filter dictionary for querying database users.
140 Current policy is admin can show all, non admin, only its own user.
141 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
144 if session
["admin"]: # allows all
147 return {"_id.cont": session
["project_id"]}
149 def check_conflict_on_new(self
, session
, indata
):
150 if not indata
.get("name"):
151 raise EngineException("missing 'name'")
152 # check name not exists
153 if self
.db
.get_one(self
.topic
, {"name": indata
.get("name")}, fail_on_empty
=False, fail_on_more
=False):
154 raise EngineException("name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
)
157 def format_on_new(content
, project_id
=None, make_public
=False):
158 BaseTopic
.format_on_new(content
, None)
159 # Removed so that the UUID is kept, to allow Project Name modification
160 # content["_id"] = content["name"]
162 def check_conflict_on_del(self
, session
, _id
, db_content
):
164 Check if deletion can be done because of dependencies if it is not force. To override
165 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
166 :param _id: internal _id
167 :param db_content: The database content of this item _id
168 :return: None if ok or raises EngineException with the conflict
170 if _id
in session
["project_id"]:
171 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
174 _filter
= {"projects": _id
}
175 if self
.db
.get_list("users", _filter
):
176 raise EngineException("There is some USER that contains this project", http_code
=HTTPStatus
.CONFLICT
)
178 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
179 if not session
["admin"]:
180 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
181 # Names that look like UUIDs are not allowed
182 name
= (indata
if indata
else kwargs
).get("name")
183 if is_valid_uuid(name
):
184 raise EngineException("Project names that look like UUIDs are not allowed",
185 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
186 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
188 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
189 if not session
["admin"]:
190 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
191 # Names that look like UUIDs are not allowed
192 name
= indata
["name"] if indata
else kwargs
["name"]
193 if is_valid_uuid(name
):
194 raise EngineException("Project names that look like UUIDs are not allowed",
195 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
196 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
199 class CommonVimWimSdn(BaseTopic
):
200 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
201 config_to_encrypt
= () # what keys at config must be encrypted because contains passwords
202 password_to_encrypt
= "" # key that contains a password
205 def _create_operation(op_type
, params
=None):
207 Creates a dictionary with the information to an operation, similar to ns-lcm-op
208 :param op_type: can be create, edit, delete
209 :param params: operation input parameters
210 :return: new dictionary with
214 "lcmOperationType": op_type
,
215 "operationState": "PROCESSING",
217 "statusEnteredTime": now
,
218 "detailed-status": "",
219 "operationParams": params
,
222 def check_conflict_on_new(self
, session
, indata
):
224 Check that the data to be inserted is valid. It is checked that name is unique
225 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
226 :param indata: data to be inserted
227 :return: None or raises EngineException
229 self
.check_unique_name(session
, indata
["name"], _id
=None)
231 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
233 Check that the data to be edited/uploaded is valid. It is checked that name is unique
234 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
235 :param final_content: data once modified. This method may change it.
236 :param edit_content: incremental data that contains the modifications to apply
237 :param _id: internal _id
238 :return: None or raises EngineException
240 if not session
["force"] and edit_content
.get("name"):
241 self
.check_unique_name(session
, edit_content
["name"], _id
=_id
)
243 def format_on_edit(self
, final_content
, edit_content
):
245 Modifies final_content inserting admin information upon edition
246 :param final_content: final content to be stored at database
247 :param edit_content: user requested update content
248 :return: operation id
252 schema_version
= final_content
.get("schema_version")
254 if edit_content
.get(self
.password_to_encrypt
):
255 final_content
[self
.password_to_encrypt
] = self
.db
.encrypt(edit_content
[self
.password_to_encrypt
],
256 schema_version
=schema_version
,
257 salt
=final_content
["_id"])
258 if edit_content
.get("config") and self
.config_to_encrypt
:
259 for p
in self
.config_to_encrypt
:
260 if edit_content
["config"].get(p
):
261 final_content
["config"][p
] = self
.db
.encrypt(edit_content
["config"][p
],
262 schema_version
=schema_version
,
263 salt
=final_content
["_id"])
265 # create edit operation
266 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
267 return "{}:{}".format(final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1)
269 def format_on_new(self
, content
, project_id
=None, make_public
=False):
271 Modifies content descriptor to include _admin and insert create operation
272 :param content: descriptor to be modified
273 :param project_id: if included, it add project read/write permissions. Can be None or a list
274 :param make_public: if included it is generated as public for reading.
275 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
277 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
278 content
["schema_version"] = schema_version
= "1.1"
281 if content
.get(self
.password_to_encrypt
):
282 content
[self
.password_to_encrypt
] = self
.db
.encrypt(content
[self
.password_to_encrypt
],
283 schema_version
=schema_version
,
285 if content
.get("config") and self
.config_to_encrypt
:
286 for p
in self
.config_to_encrypt
:
287 if content
["config"].get(p
):
288 content
["config"][p
] = self
.db
.encrypt(content
["config"][p
],
289 schema_version
=schema_version
,
292 content
["_admin"]["operationalState"] = "PROCESSING"
295 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
296 content
["_admin"]["current_operation"] = None
298 return "{}:0".format(content
["_id"])
300 def delete(self
, session
, _id
, dry_run
=False):
302 Delete item by its internal _id
303 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
304 :param _id: server internal id
305 :param dry_run: make checking but do not delete
306 :return: operation id if it is ordered to delete. None otherwise
309 filter_q
= self
._get
_project
_filter
(session
)
310 filter_q
["_id"] = _id
311 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
313 self
.check_conflict_on_del(session
, _id
, db_content
)
317 # remove reference from project_read. If not last delete
318 if session
["project_id"]:
319 for project_id
in session
["project_id"]:
320 if project_id
in db_content
["_admin"]["projects_read"]:
321 db_content
["_admin"]["projects_read"].remove(project_id
)
322 if project_id
in db_content
["_admin"]["projects_write"]:
323 db_content
["_admin"]["projects_write"].remove(project_id
)
325 db_content
["_admin"]["projects_read"].clear()
326 db_content
["_admin"]["projects_write"].clear()
328 update_dict
= {"_admin.projects_read": db_content
["_admin"]["projects_read"],
329 "_admin.projects_write": db_content
["_admin"]["projects_write"]
332 # check if there are projects referencing it (apart from ANY that means public)....
333 if db_content
["_admin"]["projects_read"] and (len(db_content
["_admin"]["projects_read"]) > 1 or
334 db_content
["_admin"]["projects_read"][0] != "ANY"):
335 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=update_dict
) # remove references but not delete
340 self
.db
.del_one(self
.topic
, {"_id": _id
})
342 self
._send
_msg
("deleted", {"_id": _id
, "op_id": op_id
})
344 update_dict
["_admin.to_delete"] = True
345 self
.db
.set_one(self
.topic
, {"_id": _id
},
346 update_dict
=update_dict
,
347 push
={"_admin.operations": self
._create
_operation
("delete")}
349 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
350 # so the -1 is not needed
351 op_id
= "{}:{}".format(db_content
["_id"], len(db_content
["_admin"]["operations"]))
352 self
._send
_msg
("delete", {"_id": _id
, "op_id": op_id
})
356 class VimAccountTopic(CommonVimWimSdn
):
357 topic
= "vim_accounts"
358 topic_msg
= "vim_account"
359 schema_new
= vim_account_new_schema
360 schema_edit
= vim_account_edit_schema
362 password_to_encrypt
= "vim_password"
363 config_to_encrypt
= ("admin_password", "nsx_password", "vcenter_password")
366 class WimAccountTopic(CommonVimWimSdn
):
367 topic
= "wim_accounts"
368 topic_msg
= "wim_account"
369 schema_new
= wim_account_new_schema
370 schema_edit
= wim_account_edit_schema
372 password_to_encrypt
= "wim_password"
373 config_to_encrypt
= ()
376 class SdnTopic(CommonVimWimSdn
):
379 schema_new
= sdn_new_schema
380 schema_edit
= sdn_edit_schema
382 password_to_encrypt
= "password"
383 config_to_encrypt
= ()
386 class UserTopicAuth(UserTopic
):
388 # topic_msg = "users"
389 schema_new
= user_new_schema
390 schema_edit
= user_edit_schema
392 def __init__(self
, db
, fs
, msg
, auth
):
393 UserTopic
.__init
__(self
, db
, fs
, msg
)
396 def check_conflict_on_new(self
, session
, indata
):
398 Check that the data to be inserted is valid
400 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
401 :param indata: data to be inserted
402 :return: None or raises EngineException
404 username
= indata
.get("username")
405 if is_valid_uuid(username
):
406 raise EngineException("username '{}' cannot have a uuid format".format(username
),
407 HTTPStatus
.UNPROCESSABLE_ENTITY
)
409 # Check that username is not used, regardless keystone already checks this
410 if self
.auth
.get_user_list(filter_q
={"name": username
}):
411 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
413 if "projects" in indata
.keys():
414 # convert to new format project_role_mappings
415 role
= self
.auth
.get_role_list({"name": "project_admin"})
417 role
= self
.auth
.get_role_list()
419 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username
))
421 if not indata
.get("project_role_mappings"):
422 indata
["project_role_mappings"] = []
423 for project
in indata
["projects"]:
424 pid
= self
.auth
.get_project(project
)["_id"]
425 prm
= {"project": pid
, "role": rid
}
426 if prm
not in indata
["project_role_mappings"]:
427 indata
["project_role_mappings"].append(prm
)
428 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
429 # HTTPStatus.BAD_REQUEST)
431 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
433 Check that the data to be edited/uploaded is valid
435 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
436 :param final_content: data once modified
437 :param edit_content: incremental data that contains the modifications to apply
438 :param _id: internal _id
439 :return: None or raises EngineException
442 if "username" in edit_content
:
443 username
= edit_content
.get("username")
444 if is_valid_uuid(username
):
445 raise EngineException("username '{}' cannot have an uuid format".format(username
),
446 HTTPStatus
.UNPROCESSABLE_ENTITY
)
448 # Check that username is not used, regardless keystone already checks this
449 if self
.auth
.get_user_list(filter_q
={"name": username
}):
450 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
452 if final_content
["username"] == "admin":
453 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
454 if mapping
["project"] == "admin" and mapping
.get("role") in (None, "system_admin"):
455 # TODO make this also available for project id and role id
456 raise EngineException("You cannot remove system_admin role from admin user",
457 http_code
=HTTPStatus
.FORBIDDEN
)
459 def check_conflict_on_del(self
, session
, _id
, db_content
):
461 Check if deletion can be done because of dependencies if it is not force. To override
462 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
463 :param _id: internal _id
464 :param db_content: The database content of this item _id
465 :return: None if ok or raises EngineException with the conflict
467 if db_content
["username"] == session
["username"]:
468 raise EngineException("You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
)
469 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
472 def format_on_show(content
):
474 Modifies the content of the role information to separate the role
475 metadata from the role definition.
477 project_role_mappings
= []
479 if "projects" in content
:
480 for project
in content
["projects"]:
481 for role
in project
["roles"]:
482 project_role_mappings
.append({"project": project
["_id"],
483 "project_name": project
["name"],
485 "role_name": role
["name"]})
486 del content
["projects"]
487 content
["project_role_mappings"] = project_role_mappings
491 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
493 Creates a new entry into the authentication backend.
495 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
497 :param rollback: list to append created items at database in case a rollback may to be done
498 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
499 :param indata: data to be inserted
500 :param kwargs: used to override the indata descriptor
501 :param headers: http request headers
502 :return: _id: identity of the inserted data, operation _id (None)
505 content
= BaseTopic
._remove
_envelop
(indata
)
507 # Override descriptor with query string kwargs
508 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
509 content
= self
._validate
_input
_new
(content
, session
["force"])
510 self
.check_conflict_on_new(session
, content
)
511 # self.format_on_new(content, session["project_id"], make_public=session["public"])
513 content
["_admin"] = {"created": now
, "modified": now
}
515 for prm
in content
.get("project_role_mappings", []):
516 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
517 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
518 pid
= proj
["_id"] if proj
else None
519 rid
= role
["_id"] if role
else None
520 prl
= {"project": pid
, "role": rid
}
523 content
["project_role_mappings"] = prms
524 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
525 _id
= self
.auth
.create_user(content
)["_id"]
527 rollback
.append({"topic": self
.topic
, "_id": _id
})
528 # del content["password"]
529 # self._send_msg("create", content)
531 except ValidationError
as e
:
532 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
534 def show(self
, session
, _id
):
536 Get complete information on an topic
538 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
539 :param _id: server internal id
540 :return: dictionary, raise exception if not found.
542 # Allow _id to be a name or uuid
543 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
544 users
= self
.auth
.get_user_list(filter_q
)
549 raise EngineException("Too many users found", HTTPStatus
.CONFLICT
)
551 raise EngineException("User not found", HTTPStatus
.NOT_FOUND
)
553 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
555 Updates an user entry.
557 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
559 :param indata: data to be inserted
560 :param kwargs: used to override the indata descriptor
562 :return: _id: identity of the inserted data.
564 indata
= self
._remove
_envelop
(indata
)
566 # Override descriptor with query string kwargs
568 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
570 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
573 content
= self
.show(session
, _id
)
574 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
575 # self.format_on_edit(content, indata)
577 if not ("password" in indata
or "username" in indata
or indata
.get("remove_project_role_mappings") or
578 indata
.get("add_project_role_mappings") or indata
.get("project_role_mappings") or
579 indata
.get("projects") or indata
.get("add_projects")):
581 if indata
.get("project_role_mappings") \
582 and (indata
.get("remove_project_role_mappings") or indata
.get("add_project_role_mappings")):
583 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
584 "' or 'remove_project_role_mappings'", http_code
=HTTPStatus
.BAD_REQUEST
)
586 if indata
.get("projects") or indata
.get("add_projects"):
587 role
= self
.auth
.get_role_list({"name": "project_admin"})
589 role
= self
.auth
.get_role_list()
591 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
592 .format(content
["username"]))
594 if "add_project_role_mappings" not in indata
:
595 indata
["add_project_role_mappings"] = []
596 if "remove_project_role_mappings" not in indata
:
597 indata
["remove_project_role_mappings"] = []
598 if isinstance(indata
.get("projects"), dict):
599 # backward compatible
600 for k
, v
in indata
["projects"].items():
601 if k
.startswith("$") and v
is None:
602 indata
["remove_project_role_mappings"].append({"project": k
[1:]})
603 elif k
.startswith("$+"):
604 indata
["add_project_role_mappings"].append({"project": v
, "role": rid
})
605 del indata
["projects"]
606 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
607 indata
["add_project_role_mappings"].append({"project": proj
, "role": rid
})
609 # user = self.show(session, _id) # Already in 'content'
610 original_mapping
= content
["project_role_mappings"]
613 mappings_to_remove
= []
616 for to_remove
in indata
.get("remove_project_role_mappings", ()):
617 for mapping
in original_mapping
:
618 if to_remove
["project"] in (mapping
["project"], mapping
["project_name"]):
619 if not to_remove
.get("role") or to_remove
["role"] in (mapping
["role"], mapping
["role_name"]):
620 mappings_to_remove
.append(mapping
)
623 for to_add
in indata
.get("add_project_role_mappings", ()):
624 for mapping
in original_mapping
:
625 if to_add
["project"] in (mapping
["project"], mapping
["project_name"]) and \
626 to_add
["role"] in (mapping
["role"], mapping
["role_name"]):
628 if mapping
in mappings_to_remove
: # do not remove
629 mappings_to_remove
.remove(mapping
)
630 break # do not add, it is already at user
632 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
633 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
634 mappings_to_add
.append({"project": pid
, "role": rid
})
637 if indata
.get("project_role_mappings"):
638 for to_set
in indata
["project_role_mappings"]:
639 for mapping
in original_mapping
:
640 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
641 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
642 if mapping
in mappings_to_remove
: # do not remove
643 mappings_to_remove
.remove(mapping
)
644 break # do not add, it is already at user
646 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
647 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
648 mappings_to_add
.append({"project": pid
, "role": rid
})
649 for mapping
in original_mapping
:
650 for to_set
in indata
["project_role_mappings"]:
651 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
652 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
656 if mapping
not in mappings_to_remove
: # do not remove
657 mappings_to_remove
.append(mapping
)
659 self
.auth
.update_user({"_id": _id
, "username": indata
.get("username"), "password": indata
.get("password"),
660 "add_project_role_mappings": mappings_to_add
,
661 "remove_project_role_mappings": mappings_to_remove
665 except ValidationError
as e
:
666 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
668 def list(self
, session
, filter_q
=None):
670 Get a list of the topic that matches a filter
671 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
672 :param filter_q: filter of data to be applied
673 :return: The list, it can be empty if no one match the filter.
675 users
= self
.auth
.get_user_list(filter_q
)
679 def delete(self
, session
, _id
, dry_run
=False):
681 Delete item by its internal _id
683 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
684 :param _id: server internal id
685 :param force: indicates if deletion must be forced in case of conflict
686 :param dry_run: make checking but do not delete
687 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
689 # Allow _id to be a name or uuid
690 user
= self
.auth
.get_user(_id
)
692 self
.check_conflict_on_del(session
, uid
, user
)
694 v
= self
.auth
.delete_user(uid
)
699 class ProjectTopicAuth(ProjectTopic
):
701 # topic_msg = "projects"
702 schema_new
= project_new_schema
703 schema_edit
= project_edit_schema
705 def __init__(self
, db
, fs
, msg
, auth
):
706 ProjectTopic
.__init
__(self
, db
, fs
, msg
)
709 def check_conflict_on_new(self
, session
, indata
):
711 Check that the data to be inserted is valid
713 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
714 :param indata: data to be inserted
715 :return: None or raises EngineException
717 project_name
= indata
.get("name")
718 if is_valid_uuid(project_name
):
719 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
720 HTTPStatus
.UNPROCESSABLE_ENTITY
)
722 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
725 raise EngineException("project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
)
727 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
729 Check that the data to be edited/uploaded is valid
731 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
732 :param final_content: data once modified
733 :param edit_content: incremental data that contains the modifications to apply
734 :param _id: internal _id
735 :return: None or raises EngineException
738 project_name
= edit_content
.get("name")
739 if project_name
!= final_content
["name"]: # It is a true renaming
740 if is_valid_uuid(project_name
):
741 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
742 HTTPStatus
.UNPROCESSABLE_ENTITY
)
744 if final_content
["name"] == "admin":
745 raise EngineException("You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
747 # Check that project name is not used, regardless keystone already checks this
748 if self
.auth
.get_project_list(filter_q
={"name": project_name
}):
749 raise EngineException("project '{}' is already used".format(project_name
), HTTPStatus
.CONFLICT
)
751 def check_conflict_on_del(self
, session
, _id
, db_content
):
753 Check if deletion can be done because of dependencies if it is not force. To override
755 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
756 :param _id: internal _id
757 :param db_content: The database content of this item _id
758 :return: None if ok or raises EngineException with the conflict
761 def check_rw_projects(topic
, title
, id_field
):
762 for desc
in self
.db
.get_list(topic
):
763 if _id
in desc
["_admin"]["projects_read"] + desc
["_admin"]["projects_write"]:
764 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
765 .format(db_content
["name"], _id
, title
, desc
[id_field
]), HTTPStatus
.CONFLICT
)
767 if _id
in session
["project_id"]:
768 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
770 if db_content
["name"] == "admin":
771 raise EngineException("You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
773 # If any user is using this project, raise CONFLICT exception
774 if not session
["force"]:
775 for user
in self
.auth
.get_user_list():
776 for prm
in user
.get("project_role_mappings"):
777 if prm
["project"] == _id
:
778 raise EngineException("Project '{}' ({}) is being used by user '{}'"
779 .format(db_content
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
781 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
782 if not session
["force"]:
783 check_rw_projects("vnfds", "VNF Descriptor", "id")
784 check_rw_projects("nsds", "NS Descriptor", "id")
785 check_rw_projects("nsts", "NS Template", "id")
786 check_rw_projects("pdus", "PDU Descriptor", "name")
788 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
790 Creates a new entry into the authentication backend.
792 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
794 :param rollback: list to append created items at database in case a rollback may to be done
795 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
796 :param indata: data to be inserted
797 :param kwargs: used to override the indata descriptor
798 :param headers: http request headers
799 :return: _id: identity of the inserted data, operation _id (None)
802 content
= BaseTopic
._remove
_envelop
(indata
)
804 # Override descriptor with query string kwargs
805 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
806 content
= self
._validate
_input
_new
(content
, session
["force"])
807 self
.check_conflict_on_new(session
, content
)
808 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
809 _id
= self
.auth
.create_project(content
)
810 rollback
.append({"topic": self
.topic
, "_id": _id
})
811 # self._send_msg("create", content)
813 except ValidationError
as e
:
814 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
816 def show(self
, session
, _id
):
818 Get complete information on an topic
820 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
821 :param _id: server internal id
822 :return: dictionary, raise exception if not found.
824 # Allow _id to be a name or uuid
825 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
826 projects
= self
.auth
.get_project_list(filter_q
=filter_q
)
828 if len(projects
) == 1:
830 elif len(projects
) > 1:
831 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
833 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
835 def list(self
, session
, filter_q
=None):
837 Get a list of the topic that matches a filter
839 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
840 :param filter_q: filter of data to be applied
841 :return: The list, it can be empty if no one match the filter.
843 return self
.auth
.get_project_list(filter_q
)
845 def delete(self
, session
, _id
, dry_run
=False):
847 Delete item by its internal _id
849 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
850 :param _id: server internal id
851 :param dry_run: make checking but do not delete
852 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
854 # Allow _id to be a name or uuid
855 proj
= self
.auth
.get_project(_id
)
857 self
.check_conflict_on_del(session
, pid
, proj
)
859 v
= self
.auth
.delete_project(pid
)
863 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
865 Updates a project entry.
867 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
869 :param indata: data to be inserted
870 :param kwargs: used to override the indata descriptor
872 :return: _id: identity of the inserted data.
874 indata
= self
._remove
_envelop
(indata
)
876 # Override descriptor with query string kwargs
878 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
880 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
883 content
= self
.show(session
, _id
)
884 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
885 self
.format_on_edit(content
, indata
)
888 content
["name"] = indata
["name"]
889 self
.auth
.update_project(content
["_id"], content
)
890 except ValidationError
as e
:
891 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
894 class RoleTopicAuth(BaseTopic
):
896 topic_msg
= None # "roles"
897 schema_new
= roles_new_schema
898 schema_edit
= roles_edit_schema
901 def __init__(self
, db
, fs
, msg
, auth
, ops
):
902 BaseTopic
.__init
__(self
, db
, fs
, msg
)
904 self
.operations
= ops
905 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
908 def validate_role_definition(operations
, role_definitions
):
910 Validates the role definition against the operations defined in
911 the resources to operations files.
913 :param operations: operations list
914 :param role_definitions: role definition to test
915 :return: None if ok, raises ValidationError exception on error
917 if not role_definitions
.get("permissions"):
919 ignore_fields
= ["admin", "default"]
920 for role_def
in role_definitions
["permissions"].keys():
921 if role_def
in ignore_fields
:
923 if role_def
[-1] == ":":
924 raise ValidationError("Operation cannot end with ':'")
926 role_def_matches
= [op
for op
in operations
if op
.startswith(role_def
)]
928 if len(role_def_matches
) == 0:
929 raise ValidationError("Invalid permission '{}'".format(role_def
))
931 def _validate_input_new(self
, input, force
=False):
933 Validates input user content for a new entry.
935 :param input: user input content for the new topic
936 :param force: may be used for being more tolerant
937 :return: The same input content, or a changed version of it.
940 validate_input(input, self
.schema_new
)
941 self
.validate_role_definition(self
.operations
, input)
945 def _validate_input_edit(self
, input, force
=False):
947 Validates input user content for updating an entry.
949 :param input: user input content for the new topic
950 :param force: may be used for being more tolerant
951 :return: The same input content, or a changed version of it.
954 validate_input(input, self
.schema_edit
)
955 self
.validate_role_definition(self
.operations
, input)
959 def check_conflict_on_new(self
, session
, indata
):
961 Check that the data to be inserted is valid
963 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
964 :param indata: data to be inserted
965 :return: None or raises EngineException
967 # check name not exists
968 name
= indata
["name"]
969 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
970 if self
.auth
.get_role_list({"name": name
}):
971 raise EngineException("role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
)
973 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
975 Check that the data to be edited/uploaded is valid
977 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
978 :param final_content: data once modified
979 :param edit_content: incremental data that contains the modifications to apply
980 :param _id: internal _id
981 :return: None or raises EngineException
983 if "default" not in final_content
["permissions"]:
984 final_content
["permissions"]["default"] = False
985 if "admin" not in final_content
["permissions"]:
986 final_content
["permissions"]["admin"] = False
988 # check name not exists
989 if "name" in edit_content
:
990 role_name
= edit_content
["name"]
991 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
992 roles
= self
.auth
.get_role_list({"name": role_name
})
993 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
994 raise EngineException("role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
)
996 def check_conflict_on_del(self
, session
, _id
, db_content
):
998 Check if deletion can be done because of dependencies if it is not force. To override
1000 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1001 :param _id: internal _id
1002 :param db_content: The database content of this item _id
1003 :return: None if ok or raises EngineException with the conflict
1005 role
= self
.auth
.get_role(_id
)
1006 if role
["name"] in ["system_admin", "project_admin"]:
1007 raise EngineException("You cannot delete role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1009 # If any user is using this role, raise CONFLICT exception
1010 for user
in self
.auth
.get_user_list():
1011 for prm
in user
.get("project_role_mappings"):
1012 if prm
["role"] == _id
:
1013 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1014 .format(role
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
1017 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1019 Modifies content descriptor to include _admin
1021 :param content: descriptor to be modified
1022 :param project_id: if included, it add project read/write permissions
1023 :param make_public: if included it is generated as public for reading.
1024 :return: None, but content is modified
1027 if "_admin" not in content
:
1028 content
["_admin"] = {}
1029 if not content
["_admin"].get("created"):
1030 content
["_admin"]["created"] = now
1031 content
["_admin"]["modified"] = now
1033 if "permissions" not in content
:
1034 content
["permissions"] = {}
1036 if "default" not in content
["permissions"]:
1037 content
["permissions"]["default"] = False
1038 if "admin" not in content
["permissions"]:
1039 content
["permissions"]["admin"] = False
1042 def format_on_edit(final_content
, edit_content
):
1044 Modifies final_content descriptor to include the modified date.
1046 :param final_content: final descriptor generated
1047 :param edit_content: alterations to be include
1048 :return: None, but final_content is modified
1050 if "_admin" in final_content
:
1051 final_content
["_admin"]["modified"] = time()
1053 if "permissions" not in final_content
:
1054 final_content
["permissions"] = {}
1056 if "default" not in final_content
["permissions"]:
1057 final_content
["permissions"]["default"] = False
1058 if "admin" not in final_content
["permissions"]:
1059 final_content
["permissions"]["admin"] = False
1062 def show(self
, session
, _id
):
1064 Get complete information on an topic
1066 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1067 :param _id: server internal id
1068 :return: dictionary, raise exception if not found.
1070 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1071 roles
= self
.auth
.get_role_list(filter_q
)
1073 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1074 elif len(roles
) > 1:
1075 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1078 def list(self
, session
, filter_q
=None):
1080 Get a list of the topic that matches a filter
1082 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1083 :param filter_q: filter of data to be applied
1084 :return: The list, it can be empty if no one match the filter.
1086 return self
.auth
.get_role_list(filter_q
)
1088 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1090 Creates a new entry into database.
1092 :param rollback: list to append created items at database in case a rollback may to be done
1093 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1094 :param indata: data to be inserted
1095 :param kwargs: used to override the indata descriptor
1096 :param headers: http request headers
1097 :return: _id: identity of the inserted data, operation _id (None)
1100 content
= self
._remove
_envelop
(indata
)
1102 # Override descriptor with query string kwargs
1103 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1104 content
= self
._validate
_input
_new
(content
, session
["force"])
1105 self
.check_conflict_on_new(session
, content
)
1106 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
1107 # role_name = content["name"]
1108 rid
= self
.auth
.create_role(content
)
1109 content
["_id"] = rid
1110 # _id = self.db.create(self.topic, content)
1111 rollback
.append({"topic": self
.topic
, "_id": rid
})
1112 # self._send_msg("create", content)
1114 except ValidationError
as e
:
1115 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1117 def delete(self
, session
, _id
, dry_run
=False):
1119 Delete item by its internal _id
1121 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1122 :param _id: server internal id
1123 :param dry_run: make checking but do not delete
1124 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1126 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1127 roles
= self
.auth
.get_role_list(filter_q
)
1129 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1130 elif len(roles
) > 1:
1131 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1132 rid
= roles
[0]["_id"]
1133 self
.check_conflict_on_del(session
, rid
, None)
1134 # filter_q = {"_id": _id}
1135 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1137 v
= self
.auth
.delete_role(rid
)
1138 # v = self.db.del_one(self.topic, filter_q)
1142 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1144 Updates a role entry.
1146 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1148 :param indata: data to be inserted
1149 :param kwargs: used to override the indata descriptor
1151 :return: _id: identity of the inserted data.
1154 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1156 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
1158 content
= self
.show(session
, _id
)
1159 deep_update_rfc7396(content
, indata
)
1160 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1161 self
.format_on_edit(content
, indata
)
1162 self
.auth
.update_role(content
)
1163 except ValidationError
as e
:
1164 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)