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 validation
import user_new_schema
, user_edit_schema
, project_new_schema
, project_edit_schema
22 from validation
import vim_account_new_schema
, vim_account_edit_schema
, sdn_new_schema
, sdn_edit_schema
23 from validation
import wim_account_new_schema
, wim_account_edit_schema
, roles_new_schema
, roles_edit_schema
24 from validation
import validate_input
25 from validation
import ValidationError
26 from validation
import is_valid_uuid
# To check that User/Project Names don't look like UUIDs
27 from base_topic
import BaseTopic
, EngineException
28 from osm_common
.dbbase
import deep_update_rfc7396
29 from authconn
import AuthconnNotFoundException
, AuthconnConflictException
30 # from authconn_keystone import AuthconnKeystone
32 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
35 class UserTopic(BaseTopic
):
38 schema_new
= user_new_schema
39 schema_edit
= user_edit_schema
42 def __init__(self
, db
, fs
, msg
):
43 BaseTopic
.__init
__(self
, db
, fs
, msg
)
46 def _get_project_filter(session
):
48 Generates a filter dictionary for querying database users.
49 Current policy is admin can show all, non admin, only its own user.
50 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
53 if session
["admin"]: # allows all
56 return {"username": session
["username"]}
58 def check_conflict_on_new(self
, session
, indata
):
59 # check username not exists
60 if self
.db
.get_one(self
.topic
, {"username": indata
.get("username")}, fail_on_empty
=False, fail_on_more
=False):
61 raise EngineException("username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
)
63 if not session
["force"]:
64 for p
in indata
.get("projects") or []:
65 # To allow project addressing by Name as well as ID
66 if not self
.db
.get_one("projects", {BaseTopic
.id_field("projects", p
): p
}, fail_on_empty
=False,
68 raise EngineException("project '{}' does not exist".format(p
), HTTPStatus
.CONFLICT
)
70 def check_conflict_on_del(self
, session
, _id
, db_content
):
72 Check if deletion can be done because of dependencies if it is not force. To override
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: internal _id
75 :param db_content: The database content of this item _id
76 :return: None if ok or raises EngineException with the conflict
78 if _id
== session
["username"]:
79 raise EngineException("You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
)
82 def format_on_new(content
, project_id
=None, make_public
=False):
83 BaseTopic
.format_on_new(content
, make_public
=False)
84 # Removed so that the UUID is kept, to allow User Name modification
85 # content["_id"] = content["username"]
87 content
["_admin"]["salt"] = salt
88 if content
.get("password"):
89 content
["password"] = sha256(content
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
90 if content
.get("project_role_mappings"):
91 projects
= [mapping
["project"] for mapping
in content
["project_role_mappings"]]
93 if content
.get("projects"):
94 content
["projects"] += projects
96 content
["projects"] = projects
99 def format_on_edit(final_content
, edit_content
):
100 BaseTopic
.format_on_edit(final_content
, edit_content
)
101 if edit_content
.get("password"):
103 final_content
["_admin"]["salt"] = salt
104 final_content
["password"] = sha256(edit_content
["password"].encode('utf-8') +
105 salt
.encode('utf-8')).hexdigest()
108 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
109 if not session
["admin"]:
110 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
111 # Names that look like UUIDs are not allowed
112 name
= (indata
if indata
else kwargs
).get("username")
113 if is_valid_uuid(name
):
114 raise EngineException("Usernames that look like UUIDs are not allowed",
115 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
116 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
118 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
119 if not session
["admin"]:
120 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
121 # Names that look like UUIDs are not allowed
122 name
= indata
["username"] if indata
else kwargs
["username"]
123 if is_valid_uuid(name
):
124 raise EngineException("Usernames that look like UUIDs are not allowed",
125 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
126 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
129 class ProjectTopic(BaseTopic
):
131 topic_msg
= "projects"
132 schema_new
= project_new_schema
133 schema_edit
= project_edit_schema
136 def __init__(self
, db
, fs
, msg
):
137 BaseTopic
.__init
__(self
, db
, fs
, msg
)
140 def _get_project_filter(session
):
142 Generates a filter dictionary for querying database users.
143 Current policy is admin can show all, non admin, only its own user.
144 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
147 if session
["admin"]: # allows all
150 return {"_id.cont": session
["project_id"]}
152 def check_conflict_on_new(self
, session
, indata
):
153 if not indata
.get("name"):
154 raise EngineException("missing 'name'")
155 # check name not exists
156 if self
.db
.get_one(self
.topic
, {"name": indata
.get("name")}, fail_on_empty
=False, fail_on_more
=False):
157 raise EngineException("name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
)
160 def format_on_new(content
, project_id
=None, make_public
=False):
161 BaseTopic
.format_on_new(content
, None)
162 # Removed so that the UUID is kept, to allow Project Name modification
163 # content["_id"] = content["name"]
165 def check_conflict_on_del(self
, session
, _id
, db_content
):
167 Check if deletion can be done because of dependencies if it is not force. To override
168 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
169 :param _id: internal _id
170 :param db_content: The database content of this item _id
171 :return: None if ok or raises EngineException with the conflict
173 if _id
in session
["project_id"]:
174 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
177 _filter
= {"projects": _id
}
178 if self
.db
.get_list("users", _filter
):
179 raise EngineException("There is some USER that contains this project", http_code
=HTTPStatus
.CONFLICT
)
181 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
182 if not session
["admin"]:
183 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
184 # Names that look like UUIDs are not allowed
185 name
= (indata
if indata
else kwargs
).get("name")
186 if is_valid_uuid(name
):
187 raise EngineException("Project names that look like UUIDs are not allowed",
188 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
189 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
191 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
192 if not session
["admin"]:
193 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
194 # Names that look like UUIDs are not allowed
195 name
= indata
["name"] if indata
else kwargs
["name"]
196 if is_valid_uuid(name
):
197 raise EngineException("Project names that look like UUIDs are not allowed",
198 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
199 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
202 class CommonVimWimSdn(BaseTopic
):
203 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
204 config_to_encrypt
= () # what keys at config must be encrypted because contains passwords
205 password_to_encrypt
= "" # key that contains a password
208 def _create_operation(op_type
, params
=None):
210 Creates a dictionary with the information to an operation, similar to ns-lcm-op
211 :param op_type: can be create, edit, delete
212 :param params: operation input parameters
213 :return: new dictionary with
217 "lcmOperationType": op_type
,
218 "operationState": "PROCESSING",
220 "statusEnteredTime": now
,
221 "detailed-status": "",
222 "operationParams": params
,
225 def check_conflict_on_new(self
, session
, indata
):
227 Check that the data to be inserted is valid. It is checked that name is unique
228 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
229 :param indata: data to be inserted
230 :return: None or raises EngineException
232 self
.check_unique_name(session
, indata
["name"], _id
=None)
234 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
236 Check that the data to be edited/uploaded is valid. It is checked that name is unique
237 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
238 :param final_content: data once modified. This method may change it.
239 :param edit_content: incremental data that contains the modifications to apply
240 :param _id: internal _id
241 :return: None or raises EngineException
243 if not session
["force"] and edit_content
.get("name"):
244 self
.check_unique_name(session
, edit_content
["name"], _id
=_id
)
246 def format_on_edit(self
, final_content
, edit_content
):
248 Modifies final_content inserting admin information upon edition
249 :param final_content: final content to be stored at database
250 :param edit_content: user requested update content
251 :return: operation id
255 schema_version
= final_content
.get("schema_version")
257 if edit_content
.get(self
.password_to_encrypt
):
258 final_content
[self
.password_to_encrypt
] = self
.db
.encrypt(edit_content
[self
.password_to_encrypt
],
259 schema_version
=schema_version
,
260 salt
=final_content
["_id"])
261 if edit_content
.get("config") and self
.config_to_encrypt
:
262 for p
in self
.config_to_encrypt
:
263 if edit_content
["config"].get(p
):
264 final_content
["config"][p
] = self
.db
.encrypt(edit_content
["config"][p
],
265 schema_version
=schema_version
,
266 salt
=final_content
["_id"])
268 # create edit operation
269 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
270 return "{}:{}".format(final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1)
272 def format_on_new(self
, content
, project_id
=None, make_public
=False):
274 Modifies content descriptor to include _admin and insert create operation
275 :param content: descriptor to be modified
276 :param project_id: if included, it add project read/write permissions. Can be None or a list
277 :param make_public: if included it is generated as public for reading.
278 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
280 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
281 content
["schema_version"] = schema_version
= "1.1"
284 if content
.get(self
.password_to_encrypt
):
285 content
[self
.password_to_encrypt
] = self
.db
.encrypt(content
[self
.password_to_encrypt
],
286 schema_version
=schema_version
,
288 if content
.get("config") and self
.config_to_encrypt
:
289 for p
in self
.config_to_encrypt
:
290 if content
["config"].get(p
):
291 content
["config"][p
] = self
.db
.encrypt(content
["config"][p
],
292 schema_version
=schema_version
,
295 content
["_admin"]["operationalState"] = "PROCESSING"
298 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
299 content
["_admin"]["current_operation"] = None
301 return "{}:0".format(content
["_id"])
303 def delete(self
, session
, _id
, dry_run
=False):
305 Delete item by its internal _id
306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
307 :param _id: server internal id
308 :param dry_run: make checking but do not delete
309 :return: operation id if it is ordered to delete. None otherwise
312 filter_q
= self
._get
_project
_filter
(session
)
313 filter_q
["_id"] = _id
314 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
316 self
.check_conflict_on_del(session
, _id
, db_content
)
320 # remove reference from project_read. If not last delete
321 if session
["project_id"]:
322 for project_id
in session
["project_id"]:
323 if project_id
in db_content
["_admin"]["projects_read"]:
324 db_content
["_admin"]["projects_read"].remove(project_id
)
325 if project_id
in db_content
["_admin"]["projects_write"]:
326 db_content
["_admin"]["projects_write"].remove(project_id
)
328 db_content
["_admin"]["projects_read"].clear()
329 db_content
["_admin"]["projects_write"].clear()
331 update_dict
= {"_admin.projects_read": db_content
["_admin"]["projects_read"],
332 "_admin.projects_write": db_content
["_admin"]["projects_write"]
335 # check if there are projects referencing it (apart from ANY that means public)....
336 if db_content
["_admin"]["projects_read"] and (len(db_content
["_admin"]["projects_read"]) > 1 or
337 db_content
["_admin"]["projects_read"][0] != "ANY"):
338 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=update_dict
) # remove references but not delete
343 self
.db
.del_one(self
.topic
, {"_id": _id
})
345 self
._send
_msg
("deleted", {"_id": _id
, "op_id": op_id
})
347 update_dict
["_admin.to_delete"] = True
348 self
.db
.set_one(self
.topic
, {"_id": _id
},
349 update_dict
=update_dict
,
350 push
={"_admin.operations": self
._create
_operation
("delete")}
352 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
353 # so the -1 is not needed
354 op_id
= "{}:{}".format(db_content
["_id"], len(db_content
["_admin"]["operations"]))
355 self
._send
_msg
("delete", {"_id": _id
, "op_id": op_id
})
359 class VimAccountTopic(CommonVimWimSdn
):
360 topic
= "vim_accounts"
361 topic_msg
= "vim_account"
362 schema_new
= vim_account_new_schema
363 schema_edit
= vim_account_edit_schema
365 password_to_encrypt
= "vim_password"
366 config_to_encrypt
= ("admin_password", "nsx_password", "vcenter_password")
369 class WimAccountTopic(CommonVimWimSdn
):
370 topic
= "wim_accounts"
371 topic_msg
= "wim_account"
372 schema_new
= wim_account_new_schema
373 schema_edit
= wim_account_edit_schema
375 password_to_encrypt
= "wim_password"
376 config_to_encrypt
= ()
379 class SdnTopic(CommonVimWimSdn
):
382 schema_new
= sdn_new_schema
383 schema_edit
= sdn_edit_schema
385 password_to_encrypt
= "password"
386 config_to_encrypt
= ()
389 class UserTopicAuth(UserTopic
):
391 # topic_msg = "users"
392 schema_new
= user_new_schema
393 schema_edit
= user_edit_schema
395 def __init__(self
, db
, fs
, msg
, auth
):
396 UserTopic
.__init
__(self
, db
, fs
, msg
)
399 def check_conflict_on_new(self
, session
, indata
):
401 Check that the data to be inserted is valid
403 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
404 :param indata: data to be inserted
405 :return: None or raises EngineException
407 username
= indata
.get("username")
408 if is_valid_uuid(username
):
409 raise EngineException("username '{}' cannot have a uuid format".format(username
),
410 HTTPStatus
.UNPROCESSABLE_ENTITY
)
412 # Check that username is not used, regardless keystone already checks this
413 if self
.auth
.get_user_list(filter_q
={"name": username
}):
414 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
416 if "projects" in indata
.keys():
417 # convert to new format project_role_mappings
418 role
= self
.auth
.get_role_list({"name": "project_admin"})
420 role
= self
.auth
.get_role_list()
422 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username
))
424 if not indata
.get("project_role_mappings"):
425 indata
["project_role_mappings"] = []
426 for project
in indata
["projects"]:
427 pid
= self
.auth
.get_project(project
)["_id"]
428 prm
= {"project": pid
, "role": rid
}
429 if prm
not in indata
["project_role_mappings"]:
430 indata
["project_role_mappings"].append(prm
)
431 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
432 # HTTPStatus.BAD_REQUEST)
434 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
436 Check that the data to be edited/uploaded is valid
438 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
439 :param final_content: data once modified
440 :param edit_content: incremental data that contains the modifications to apply
441 :param _id: internal _id
442 :return: None or raises EngineException
445 if "username" in edit_content
:
446 username
= edit_content
.get("username")
447 if is_valid_uuid(username
):
448 raise EngineException("username '{}' cannot have an uuid format".format(username
),
449 HTTPStatus
.UNPROCESSABLE_ENTITY
)
451 # Check that username is not used, regardless keystone already checks this
452 if self
.auth
.get_user_list(filter_q
={"name": username
}):
453 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
455 if final_content
["username"] == "admin":
456 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
457 if mapping
["project"] == "admin" and mapping
.get("role") in (None, "system_admin"):
458 # TODO make this also available for project id and role id
459 raise EngineException("You cannot remove system_admin role from admin user",
460 http_code
=HTTPStatus
.FORBIDDEN
)
462 def check_conflict_on_del(self
, session
, _id
, db_content
):
464 Check if deletion can be done because of dependencies if it is not force. To override
465 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
466 :param _id: internal _id
467 :param db_content: The database content of this item _id
468 :return: None if ok or raises EngineException with the conflict
470 if db_content
["username"] == session
["username"]:
471 raise EngineException("You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
)
472 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
475 def format_on_show(content
):
477 Modifies the content of the role information to separate the role
478 metadata from the role definition.
480 project_role_mappings
= []
482 if "projects" in content
:
483 for project
in content
["projects"]:
484 for role
in project
["roles"]:
485 project_role_mappings
.append({"project": project
["_id"],
486 "project_name": project
["name"],
488 "role_name": role
["name"]})
489 del content
["projects"]
490 content
["project_role_mappings"] = project_role_mappings
494 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
496 Creates a new entry into the authentication backend.
498 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
500 :param rollback: list to append created items at database in case a rollback may to be done
501 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
502 :param indata: data to be inserted
503 :param kwargs: used to override the indata descriptor
504 :param headers: http request headers
505 :return: _id: identity of the inserted data, operation _id (None)
508 content
= BaseTopic
._remove
_envelop
(indata
)
510 # Override descriptor with query string kwargs
511 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
512 content
= self
._validate
_input
_new
(content
, session
["force"])
513 self
.check_conflict_on_new(session
, content
)
514 # self.format_on_new(content, session["project_id"], make_public=session["public"])
516 content
["_admin"] = {"created": now
, "modified": now
}
518 for prm
in content
.get("project_role_mappings", []):
519 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
520 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
521 pid
= proj
["_id"] if proj
else None
522 rid
= role
["_id"] if role
else None
523 prl
= {"project": pid
, "role": rid
}
526 content
["project_role_mappings"] = prms
527 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
528 _id
= self
.auth
.create_user(content
)["_id"]
530 rollback
.append({"topic": self
.topic
, "_id": _id
})
531 # del content["password"]
532 # self._send_msg("create", content)
534 except ValidationError
as e
:
535 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
537 def show(self
, session
, _id
):
539 Get complete information on an topic
541 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
542 :param _id: server internal id
543 :return: dictionary, raise exception if not found.
545 # Allow _id to be a name or uuid
546 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
547 users
= self
.auth
.get_user_list(filter_q
)
552 raise EngineException("Too many users found", HTTPStatus
.CONFLICT
)
554 raise EngineException("User not found", HTTPStatus
.NOT_FOUND
)
556 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
558 Updates an user entry.
560 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
562 :param indata: data to be inserted
563 :param kwargs: used to override the indata descriptor
565 :return: _id: identity of the inserted data.
567 indata
= self
._remove
_envelop
(indata
)
569 # Override descriptor with query string kwargs
571 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
573 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
576 content
= self
.show(session
, _id
)
577 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
578 # self.format_on_edit(content, indata)
580 if not ("password" in indata
or "username" in indata
or indata
.get("remove_project_role_mappings") or
581 indata
.get("add_project_role_mappings") or indata
.get("project_role_mappings") or
582 indata
.get("projects") or indata
.get("add_projects")):
584 if indata
.get("project_role_mappings") \
585 and (indata
.get("remove_project_role_mappings") or indata
.get("add_project_role_mappings")):
586 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
587 "' or 'remove_project_role_mappings'", http_code
=HTTPStatus
.BAD_REQUEST
)
589 if indata
.get("projects") or indata
.get("add_projects"):
590 role
= self
.auth
.get_role_list({"name": "project_admin"})
592 role
= self
.auth
.get_role_list()
594 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
595 .format(content
["username"]))
597 if "add_project_role_mappings" not in indata
:
598 indata
["add_project_role_mappings"] = []
599 if "remove_project_role_mappings" not in indata
:
600 indata
["remove_project_role_mappings"] = []
601 if isinstance(indata
.get("projects"), dict):
602 # backward compatible
603 for k
, v
in indata
["projects"].items():
604 if k
.startswith("$") and v
is None:
605 indata
["remove_project_role_mappings"].append({"project": k
[1:]})
606 elif k
.startswith("$+"):
607 indata
["add_project_role_mappings"].append({"project": v
, "role": rid
})
608 del indata
["projects"]
609 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
610 indata
["add_project_role_mappings"].append({"project": proj
, "role": rid
})
612 # user = self.show(session, _id) # Already in 'content'
613 original_mapping
= content
["project_role_mappings"]
616 mappings_to_remove
= []
619 for to_remove
in indata
.get("remove_project_role_mappings", ()):
620 for mapping
in original_mapping
:
621 if to_remove
["project"] in (mapping
["project"], mapping
["project_name"]):
622 if not to_remove
.get("role") or to_remove
["role"] in (mapping
["role"], mapping
["role_name"]):
623 mappings_to_remove
.append(mapping
)
626 for to_add
in indata
.get("add_project_role_mappings", ()):
627 for mapping
in original_mapping
:
628 if to_add
["project"] in (mapping
["project"], mapping
["project_name"]) and \
629 to_add
["role"] in (mapping
["role"], mapping
["role_name"]):
631 if mapping
in mappings_to_remove
: # do not remove
632 mappings_to_remove
.remove(mapping
)
633 break # do not add, it is already at user
635 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
636 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
637 mappings_to_add
.append({"project": pid
, "role": rid
})
640 if indata
.get("project_role_mappings"):
641 for to_set
in indata
["project_role_mappings"]:
642 for mapping
in original_mapping
:
643 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
644 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
645 if mapping
in mappings_to_remove
: # do not remove
646 mappings_to_remove
.remove(mapping
)
647 break # do not add, it is already at user
649 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
650 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
651 mappings_to_add
.append({"project": pid
, "role": rid
})
652 for mapping
in original_mapping
:
653 for to_set
in indata
["project_role_mappings"]:
654 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
655 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
659 if mapping
not in mappings_to_remove
: # do not remove
660 mappings_to_remove
.append(mapping
)
662 self
.auth
.update_user({"_id": _id
, "username": indata
.get("username"), "password": indata
.get("password"),
663 "add_project_role_mappings": mappings_to_add
,
664 "remove_project_role_mappings": mappings_to_remove
668 except ValidationError
as e
:
669 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
671 def list(self
, session
, filter_q
=None):
673 Get a list of the topic that matches a filter
674 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
675 :param filter_q: filter of data to be applied
676 :return: The list, it can be empty if no one match the filter.
678 users
= self
.auth
.get_user_list(filter_q
)
682 def delete(self
, session
, _id
, dry_run
=False):
684 Delete item by its internal _id
686 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
687 :param _id: server internal id
688 :param force: indicates if deletion must be forced in case of conflict
689 :param dry_run: make checking but do not delete
690 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
692 # Allow _id to be a name or uuid
693 user
= self
.auth
.get_user(_id
)
695 self
.check_conflict_on_del(session
, uid
, user
)
697 v
= self
.auth
.delete_user(uid
)
702 class ProjectTopicAuth(ProjectTopic
):
704 # topic_msg = "projects"
705 schema_new
= project_new_schema
706 schema_edit
= project_edit_schema
708 def __init__(self
, db
, fs
, msg
, auth
):
709 ProjectTopic
.__init
__(self
, db
, fs
, msg
)
712 def check_conflict_on_new(self
, session
, indata
):
714 Check that the data to be inserted is valid
716 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
717 :param indata: data to be inserted
718 :return: None or raises EngineException
720 project_name
= indata
.get("name")
721 if is_valid_uuid(project_name
):
722 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
723 HTTPStatus
.UNPROCESSABLE_ENTITY
)
725 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
728 raise EngineException("project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
)
730 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
732 Check that the data to be edited/uploaded is valid
734 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
735 :param final_content: data once modified
736 :param edit_content: incremental data that contains the modifications to apply
737 :param _id: internal _id
738 :return: None or raises EngineException
741 project_name
= edit_content
.get("name")
742 if project_name
!= final_content
["name"]: # It is a true renaming
743 if is_valid_uuid(project_name
):
744 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
745 HTTPStatus
.UNPROCESSABLE_ENTITY
)
747 if final_content
["name"] == "admin":
748 raise EngineException("You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
750 # Check that project name is not used, regardless keystone already checks this
751 if self
.auth
.get_project_list(filter_q
={"name": project_name
}):
752 raise EngineException("project '{}' is already used".format(project_name
), HTTPStatus
.CONFLICT
)
754 def check_conflict_on_del(self
, session
, _id
, db_content
):
756 Check if deletion can be done because of dependencies if it is not force. To override
758 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
759 :param _id: internal _id
760 :param db_content: The database content of this item _id
761 :return: None if ok or raises EngineException with the conflict
764 def check_rw_projects(topic
, title
, id_field
):
765 for desc
in self
.db
.get_list(topic
):
766 if _id
in desc
["_admin"]["projects_read"] + desc
["_admin"]["projects_write"]:
767 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
768 .format(db_content
["name"], _id
, title
, desc
[id_field
]), HTTPStatus
.CONFLICT
)
770 if _id
in session
["project_id"]:
771 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
773 if db_content
["name"] == "admin":
774 raise EngineException("You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
776 # If any user is using this project, raise CONFLICT exception
777 if not session
["force"]:
778 for user
in self
.auth
.get_user_list():
779 for prm
in user
.get("project_role_mappings"):
780 if prm
["project"] == _id
:
781 raise EngineException("Project '{}' ({}) is being used by user '{}'"
782 .format(db_content
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
784 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
785 if not session
["force"]:
786 check_rw_projects("vnfds", "VNF Descriptor", "id")
787 check_rw_projects("nsds", "NS Descriptor", "id")
788 check_rw_projects("nsts", "NS Template", "id")
789 check_rw_projects("pdus", "PDU Descriptor", "name")
791 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
793 Creates a new entry into the authentication backend.
795 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
797 :param rollback: list to append created items at database in case a rollback may to be done
798 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
799 :param indata: data to be inserted
800 :param kwargs: used to override the indata descriptor
801 :param headers: http request headers
802 :return: _id: identity of the inserted data, operation _id (None)
805 content
= BaseTopic
._remove
_envelop
(indata
)
807 # Override descriptor with query string kwargs
808 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
809 content
= self
._validate
_input
_new
(content
, session
["force"])
810 self
.check_conflict_on_new(session
, content
)
811 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
812 _id
= self
.auth
.create_project(content
)
813 rollback
.append({"topic": self
.topic
, "_id": _id
})
814 # self._send_msg("create", content)
816 except ValidationError
as e
:
817 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
819 def show(self
, session
, _id
):
821 Get complete information on an topic
823 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
824 :param _id: server internal id
825 :return: dictionary, raise exception if not found.
827 # Allow _id to be a name or uuid
828 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
829 projects
= self
.auth
.get_project_list(filter_q
=filter_q
)
831 if len(projects
) == 1:
833 elif len(projects
) > 1:
834 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
836 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
838 def list(self
, session
, filter_q
=None):
840 Get a list of the topic that matches a filter
842 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
843 :param filter_q: filter of data to be applied
844 :return: The list, it can be empty if no one match the filter.
846 return self
.auth
.get_project_list(filter_q
)
848 def delete(self
, session
, _id
, dry_run
=False):
850 Delete item by its internal _id
852 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
853 :param _id: server internal id
854 :param dry_run: make checking but do not delete
855 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
857 # Allow _id to be a name or uuid
858 proj
= self
.auth
.get_project(_id
)
860 self
.check_conflict_on_del(session
, pid
, proj
)
862 v
= self
.auth
.delete_project(pid
)
866 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
868 Updates a project entry.
870 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
872 :param indata: data to be inserted
873 :param kwargs: used to override the indata descriptor
875 :return: _id: identity of the inserted data.
877 indata
= self
._remove
_envelop
(indata
)
879 # Override descriptor with query string kwargs
881 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
883 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
886 content
= self
.show(session
, _id
)
887 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
888 self
.format_on_edit(content
, indata
)
891 content
["name"] = indata
["name"]
892 self
.auth
.update_project(content
["_id"], content
)
893 except ValidationError
as e
:
894 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
897 class RoleTopicAuth(BaseTopic
):
899 topic_msg
= None # "roles"
900 schema_new
= roles_new_schema
901 schema_edit
= roles_edit_schema
904 def __init__(self
, db
, fs
, msg
, auth
, ops
):
905 BaseTopic
.__init
__(self
, db
, fs
, msg
)
907 self
.operations
= ops
908 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
911 def validate_role_definition(operations
, role_definitions
):
913 Validates the role definition against the operations defined in
914 the resources to operations files.
916 :param operations: operations list
917 :param role_definitions: role definition to test
918 :return: None if ok, raises ValidationError exception on error
920 if not role_definitions
.get("permissions"):
922 ignore_fields
= ["admin", "default"]
923 for role_def
in role_definitions
["permissions"].keys():
924 if role_def
in ignore_fields
:
926 if role_def
[-1] == ":":
927 raise ValidationError("Operation cannot end with ':'")
929 role_def_matches
= [op
for op
in operations
if op
.startswith(role_def
)]
931 if len(role_def_matches
) == 0:
932 raise ValidationError("Invalid permission '{}'".format(role_def
))
934 def _validate_input_new(self
, input, force
=False):
936 Validates input user content for a new entry.
938 :param input: user input content for the new topic
939 :param force: may be used for being more tolerant
940 :return: The same input content, or a changed version of it.
943 validate_input(input, self
.schema_new
)
944 self
.validate_role_definition(self
.operations
, input)
948 def _validate_input_edit(self
, input, force
=False):
950 Validates input user content for updating an entry.
952 :param input: user input content for the new topic
953 :param force: may be used for being more tolerant
954 :return: The same input content, or a changed version of it.
957 validate_input(input, self
.schema_edit
)
958 self
.validate_role_definition(self
.operations
, input)
962 def check_conflict_on_new(self
, session
, indata
):
964 Check that the data to be inserted is valid
966 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
967 :param indata: data to be inserted
968 :return: None or raises EngineException
970 # check name not exists
971 name
= indata
["name"]
972 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
973 if self
.auth
.get_role_list({"name": name
}):
974 raise EngineException("role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
)
976 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
978 Check that the data to be edited/uploaded is valid
980 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
981 :param final_content: data once modified
982 :param edit_content: incremental data that contains the modifications to apply
983 :param _id: internal _id
984 :return: None or raises EngineException
986 if "default" not in final_content
["permissions"]:
987 final_content
["permissions"]["default"] = False
988 if "admin" not in final_content
["permissions"]:
989 final_content
["permissions"]["admin"] = False
991 # check name not exists
992 if "name" in edit_content
:
993 role_name
= edit_content
["name"]
994 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
995 roles
= self
.auth
.get_role_list({"name": role_name
})
996 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
997 raise EngineException("role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
)
999 def check_conflict_on_del(self
, session
, _id
, db_content
):
1001 Check if deletion can be done because of dependencies if it is not force. To override
1003 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1004 :param _id: internal _id
1005 :param db_content: The database content of this item _id
1006 :return: None if ok or raises EngineException with the conflict
1008 role
= self
.auth
.get_role(_id
)
1009 if role
["name"] in ["system_admin", "project_admin"]:
1010 raise EngineException("You cannot delete role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1012 # If any user is using this role, raise CONFLICT exception
1013 for user
in self
.auth
.get_user_list():
1014 for prm
in user
.get("project_role_mappings"):
1015 if prm
["role"] == _id
:
1016 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1017 .format(role
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
1020 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1022 Modifies content descriptor to include _admin
1024 :param content: descriptor to be modified
1025 :param project_id: if included, it add project read/write permissions
1026 :param make_public: if included it is generated as public for reading.
1027 :return: None, but content is modified
1030 if "_admin" not in content
:
1031 content
["_admin"] = {}
1032 if not content
["_admin"].get("created"):
1033 content
["_admin"]["created"] = now
1034 content
["_admin"]["modified"] = now
1036 if "permissions" not in content
:
1037 content
["permissions"] = {}
1039 if "default" not in content
["permissions"]:
1040 content
["permissions"]["default"] = False
1041 if "admin" not in content
["permissions"]:
1042 content
["permissions"]["admin"] = False
1045 def format_on_edit(final_content
, edit_content
):
1047 Modifies final_content descriptor to include the modified date.
1049 :param final_content: final descriptor generated
1050 :param edit_content: alterations to be include
1051 :return: None, but final_content is modified
1053 if "_admin" in final_content
:
1054 final_content
["_admin"]["modified"] = time()
1056 if "permissions" not in final_content
:
1057 final_content
["permissions"] = {}
1059 if "default" not in final_content
["permissions"]:
1060 final_content
["permissions"]["default"] = False
1061 if "admin" not in final_content
["permissions"]:
1062 final_content
["permissions"]["admin"] = False
1065 def show(self
, session
, _id
):
1067 Get complete information on an topic
1069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1070 :param _id: server internal id
1071 :return: dictionary, raise exception if not found.
1073 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1074 roles
= self
.auth
.get_role_list(filter_q
)
1076 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1077 elif len(roles
) > 1:
1078 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1081 def list(self
, session
, filter_q
=None):
1083 Get a list of the topic that matches a filter
1085 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1086 :param filter_q: filter of data to be applied
1087 :return: The list, it can be empty if no one match the filter.
1089 return self
.auth
.get_role_list(filter_q
)
1091 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1093 Creates a new entry into database.
1095 :param rollback: list to append created items at database in case a rollback may to be done
1096 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1097 :param indata: data to be inserted
1098 :param kwargs: used to override the indata descriptor
1099 :param headers: http request headers
1100 :return: _id: identity of the inserted data, operation _id (None)
1103 content
= self
._remove
_envelop
(indata
)
1105 # Override descriptor with query string kwargs
1106 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1107 content
= self
._validate
_input
_new
(content
, session
["force"])
1108 self
.check_conflict_on_new(session
, content
)
1109 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
1110 # role_name = content["name"]
1111 rid
= self
.auth
.create_role(content
)
1112 content
["_id"] = rid
1113 # _id = self.db.create(self.topic, content)
1114 rollback
.append({"topic": self
.topic
, "_id": rid
})
1115 # self._send_msg("create", content)
1117 except ValidationError
as e
:
1118 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1120 def delete(self
, session
, _id
, dry_run
=False):
1122 Delete item by its internal _id
1124 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1125 :param _id: server internal id
1126 :param dry_run: make checking but do not delete
1127 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1129 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1130 roles
= self
.auth
.get_role_list(filter_q
)
1132 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1133 elif len(roles
) > 1:
1134 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1135 rid
= roles
[0]["_id"]
1136 self
.check_conflict_on_del(session
, rid
, None)
1137 # filter_q = {"_id": _id}
1138 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1140 v
= self
.auth
.delete_role(rid
)
1141 # v = self.db.del_one(self.topic, filter_q)
1145 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1147 Updates a role entry.
1149 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1151 :param indata: data to be inserted
1152 :param kwargs: used to override the indata descriptor
1154 :return: _id: identity of the inserted data.
1157 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1159 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
1161 content
= self
.show(session
, _id
)
1162 deep_update_rfc7396(content
, indata
)
1163 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1164 self
.format_on_edit(content
, indata
)
1165 self
.auth
.update_role(content
)
1166 except ValidationError
as e
:
1167 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)