Adding filter to ProjectTopicAuth
[osm/NBI.git] / osm_nbi / base_topic.py
1 # -*- coding: utf-8 -*-
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import logging
17 from uuid import uuid4
18 from http import HTTPStatus
19 from time import time
20 from osm_common.dbbase import deep_update_rfc7396
21 from validation import validate_input, ValidationError, is_valid_uuid
22
23 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
24
25
26 class EngineException(Exception):
27
28 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
29 self.http_code = http_code
30 Exception.__init__(self, message)
31
32
33 def get_iterable(input_var):
34 """
35 Returns an iterable, in case input_var is None it just returns an empty tuple
36 :param input_var: can be a list, tuple or None
37 :return: input_var or () if it is None
38 """
39 if input_var is None:
40 return ()
41 return input_var
42
43
44 def versiontuple(v):
45 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
46 filled = []
47 for point in v.split("."):
48 filled.append(point.zfill(8))
49 return tuple(filled)
50
51
52 class BaseTopic:
53 # static variables for all instance classes
54 topic = None # to_override
55 topic_msg = None # to_override
56 schema_new = None # to_override
57 schema_edit = None # to_override
58 multiproject = True # True if this Topic can be shared by several projects. Then it contains _admin.projects_read
59
60 # Alternative ID Fields for some Topics
61 alt_id_field = {
62 "projects": "name",
63 "users": "username"
64 }
65
66 def __init__(self, db, fs, msg):
67 self.db = db
68 self.fs = fs
69 self.msg = msg
70 self.logger = logging.getLogger("nbi.engine")
71
72 @staticmethod
73 def id_field(topic, value):
74 """Returns ID Field for given topic and field value"""
75 if topic in ["projects", "users"] and not is_valid_uuid(value):
76 return BaseTopic.alt_id_field[topic]
77 else:
78 return "_id"
79
80 @staticmethod
81 def _remove_envelop(indata=None):
82 if not indata:
83 return {}
84 return indata
85
86 def _validate_input_new(self, input, force=False):
87 """
88 Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind
89 :param input: user input content for the new topic
90 :param force: may be used for being more tolerant
91 :return: The same input content, or a changed version of it.
92 """
93 if self.schema_new:
94 validate_input(input, self.schema_new)
95 return input
96
97 def _validate_input_edit(self, input, force=False):
98 """
99 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
100 :param input: user input content for the new topic
101 :param force: may be used for being more tolerant
102 :return: The same input content, or a changed version of it.
103 """
104 if self.schema_edit:
105 validate_input(input, self.schema_edit)
106 return input
107
108 @staticmethod
109 def _get_project_filter(session):
110 """
111 Generates a filter dictionary for querying database, so that only allowed items for this project can be
112 addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
113 not present or contains ANY mean public.
114 :param session: contains:
115 project_id: project list this session has rights to access. Can be empty, one or several
116 set_project: items created will contain this project list
117 force: True or False
118 public: True, False or None
119 method: "list", "show", "write", "delete"
120 admin: True or False
121 :return: dictionary with project filter
122 """
123 p_filter = {}
124 project_filter_n = []
125 project_filter = list(session["project_id"])
126
127 if session["method"] not in ("list", "delete"):
128 if project_filter:
129 project_filter.append("ANY")
130 elif session["public"] is not None:
131 if session["public"]:
132 project_filter.append("ANY")
133 else:
134 project_filter_n.append("ANY")
135
136 if session.get("PROJECT.ne"):
137 project_filter_n.append(session["PROJECT.ne"])
138
139 if project_filter:
140 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
141 p_filter["_admin.projects_read.cont"] = project_filter
142 else:
143 p_filter["_admin.projects_write.cont"] = project_filter
144 if project_filter_n:
145 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
146 p_filter["_admin.projects_read.ncont"] = project_filter_n
147 else:
148 p_filter["_admin.projects_write.ncont"] = project_filter_n
149
150 return p_filter
151
152 def check_conflict_on_new(self, session, indata):
153 """
154 Check that the data to be inserted is valid
155 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
156 :param indata: data to be inserted
157 :return: None or raises EngineException
158 """
159 pass
160
161 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
162 """
163 Check that the data to be edited/uploaded is valid
164 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
165 :param final_content: data once modified. This methdo may change it.
166 :param edit_content: incremental data that contains the modifications to apply
167 :param _id: internal _id
168 :return: None or raises EngineException
169 """
170 if not self.multiproject:
171 return
172 # Change public status
173 if session["public"] is not None:
174 if session["public"] and "ANY" not in final_content["_admin"]["projects_read"]:
175 final_content["_admin"]["projects_read"].append("ANY")
176 final_content["_admin"]["projects_write"].clear()
177 if not session["public"] and "ANY" in final_content["_admin"]["projects_read"]:
178 final_content["_admin"]["projects_read"].remove("ANY")
179
180 # Change project status
181 if session.get("set_project"):
182 for p in session["set_project"]:
183 if p not in final_content["_admin"]["projects_read"]:
184 final_content["_admin"]["projects_read"].append(p)
185
186 def check_unique_name(self, session, name, _id=None):
187 """
188 Check that the name is unique for this project
189 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
190 :param name: name to be checked
191 :param _id: If not None, ignore this entry that are going to change
192 :return: None or raises EngineException
193 """
194 _filter = self._get_project_filter(session)
195 _filter["name"] = name
196 if _id:
197 _filter["_id.neq"] = _id
198 if self.db.get_one(self.topic, _filter, fail_on_empty=False, fail_on_more=False):
199 raise EngineException("name '{}' already exists for {}".format(name, self.topic), HTTPStatus.CONFLICT)
200
201 @staticmethod
202 def format_on_new(content, project_id=None, make_public=False):
203 """
204 Modifies content descriptor to include _admin
205 :param content: descriptor to be modified
206 :param project_id: if included, it add project read/write permissions. Can be None or a list
207 :param make_public: if included it is generated as public for reading.
208 :return: None, but content is modified
209 """
210 now = time()
211 if "_admin" not in content:
212 content["_admin"] = {}
213 if not content["_admin"].get("created"):
214 content["_admin"]["created"] = now
215 content["_admin"]["modified"] = now
216 if not content.get("_id"):
217 content["_id"] = str(uuid4())
218 if project_id is not None:
219 if not content["_admin"].get("projects_read"):
220 content["_admin"]["projects_read"] = list(project_id)
221 if make_public:
222 content["_admin"]["projects_read"].append("ANY")
223 if not content["_admin"].get("projects_write"):
224 content["_admin"]["projects_write"] = list(project_id)
225
226 @staticmethod
227 def format_on_edit(final_content, edit_content):
228 if final_content.get("_admin"):
229 now = time()
230 final_content["_admin"]["modified"] = now
231
232 def _send_msg(self, action, content):
233 if self.topic_msg:
234 content.pop("_admin", None)
235 self.msg.write(self.topic_msg, action, content)
236
237 def check_conflict_on_del(self, session, _id):
238 """
239 Check if deletion can be done because of dependencies if it is not force. To override
240 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
241 :param _id: internal _id
242 :return: None if ok or raises EngineException with the conflict
243 """
244 pass
245
246 @staticmethod
247 def _update_input_with_kwargs(desc, kwargs):
248 """
249 Update descriptor with the kwargs. It contains dot separated keys
250 :param desc: dictionary to be updated
251 :param kwargs: plain dictionary to be used for updating.
252 :return: None, 'desc' is modified. It raises EngineException.
253 """
254 if not kwargs:
255 return
256 try:
257 for k, v in kwargs.items():
258 update_content = desc
259 kitem_old = None
260 klist = k.split(".")
261 for kitem in klist:
262 if kitem_old is not None:
263 update_content = update_content[kitem_old]
264 if isinstance(update_content, dict):
265 kitem_old = kitem
266 elif isinstance(update_content, list):
267 kitem_old = int(kitem)
268 else:
269 raise EngineException(
270 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
271 update_content[kitem_old] = v
272 except KeyError:
273 raise EngineException(
274 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
275 except ValueError:
276 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
277 k, kitem))
278 except IndexError:
279 raise EngineException(
280 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
281
282 def show(self, session, _id):
283 """
284 Get complete information on an topic
285 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
286 :param _id: server internal id
287 :return: dictionary, raise exception if not found.
288 """
289 filter_db = self._get_project_filter(session)
290 # To allow project&user addressing by name AS WELL AS _id
291 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
292 return self.db.get_one(self.topic, filter_db)
293 # TODO transform data for SOL005 URL requests
294 # TODO remove _admin if not admin
295
296 def get_file(self, session, _id, path=None, accept_header=None):
297 """
298 Only implemented for descriptor topics. Return the file content of a descriptor
299 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
300 :param _id: Identity of the item to get content
301 :param path: artifact path or "$DESCRIPTOR" or None
302 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
303 :return: opened file or raises an exception
304 """
305 raise EngineException("Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
306
307 def list(self, session, filter_q=None):
308 """
309 Get a list of the topic that matches a filter
310 :param session: contains the used login username and working project
311 :param filter_q: filter of data to be applied
312 :return: The list, it can be empty if no one match the filter.
313 """
314 if not filter_q:
315 filter_q = {}
316
317 filter_q.update(self._get_project_filter(session))
318
319 # TODO transform data for SOL005 URL requests. Transform filtering
320 # TODO implement "field-type" query string SOL005
321 return self.db.get_list(self.topic, filter_q)
322
323 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
324 """
325 Creates a new entry into database.
326 :param rollback: list to append created items at database in case a rollback may to be done
327 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
328 :param indata: data to be inserted
329 :param kwargs: used to override the indata descriptor
330 :param headers: http request headers
331 :return: _id: identity of the inserted data.
332 """
333 try:
334 content = self._remove_envelop(indata)
335
336 # Override descriptor with query string kwargs
337 self._update_input_with_kwargs(content, kwargs)
338 content = self._validate_input_new(content, force=session["force"])
339 self.check_conflict_on_new(session, content)
340 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
341 _id = self.db.create(self.topic, content)
342 rollback.append({"topic": self.topic, "_id": _id})
343 self._send_msg("create", content)
344 return _id
345 except ValidationError as e:
346 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
347
348 def upload_content(self, session, _id, indata, kwargs, headers):
349 """
350 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
351 and/or gzip file. It will store and extract)
352 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
353 :param _id : the database id of entry to be updated
354 :param indata: http body request
355 :param kwargs: user query string to override parameters. NOT USED
356 :param headers: http request headers
357 :return: True package has is completely uploaded or False if partial content has been uplodaed.
358 Raise exception on error
359 """
360 raise EngineException("Method upload_content not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
361
362 def delete_list(self, session, filter_q=None):
363 """
364 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
365 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
366 :param filter_q: filter of data to be applied
367 :return: The deleted list, it can be empty if no one match the filter.
368 """
369 # TODO add admin to filter, validate rights
370 if not filter_q:
371 filter_q = {}
372 filter_q.update(self._get_project_filter(session))
373 return self.db.del_list(self.topic, filter_q)
374
375 def delete_extra(self, session, _id):
376 """
377 Delete other things apart from database entry of a item _id.
378 e.g.: other associated elements at database and other file system storage
379 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
380 :param _id: server internal id
381 """
382 pass
383
384 def delete(self, session, _id, dry_run=False):
385 """
386 Delete item by its internal _id
387 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
388 :param _id: server internal id
389 :param dry_run: make checking but do not delete
390 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
391 """
392 # TODO add admin to filter, validate rights
393 # data = self.get_item(topic, _id)
394 self.check_conflict_on_del(session, _id)
395 filter_q = self._get_project_filter(session)
396 # To allow project addressing by name AS WELL AS _id
397 filter_q[BaseTopic.id_field(self.topic, _id)] = _id
398 if dry_run:
399 return None
400 if self.multiproject and session["project_id"]:
401 # remove reference from project_read. If not last delete
402 self.db.set_one(self.topic, filter_q, update_dict=None,
403 pull={"_admin.projects_read": {"$in": session["project_id"]}})
404 # try to delete if there is not any more reference from projects. Ignore if it is not deleted
405 filter_q = {'_id': _id, '_admin.projects_read': [[], ["ANY"]]}
406 v = self.db.del_one(self.topic, filter_q, fail_on_empty=False)
407 if not v or not v["deleted"]:
408 return v
409 else:
410 v = self.db.del_one(self.topic, filter_q)
411 self.delete_extra(session, _id)
412 self._send_msg("deleted", {"_id": _id})
413 return v
414
415 def edit(self, session, _id, indata=None, kwargs=None, content=None):
416 """
417 Change the content of an item
418 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
419 :param _id: server internal id
420 :param indata: contains the changes to apply
421 :param kwargs: modifies indata
422 :param content: original content of the item
423 :return:
424 """
425 indata = self._remove_envelop(indata)
426
427 # Override descriptor with query string kwargs
428 if kwargs:
429 self._update_input_with_kwargs(indata, kwargs)
430 try:
431 if indata and session.get("set_project"):
432 raise EngineException("Cannot edit content and set to project (query string SET_PROJECT) at same time",
433 HTTPStatus.UNPROCESSABLE_ENTITY)
434 indata = self._validate_input_edit(indata, force=session["force"])
435
436 # TODO self._check_edition(session, indata, _id, force)
437 if not content:
438 content = self.show(session, _id)
439 deep_update_rfc7396(content, indata)
440 self.check_conflict_on_edit(session, content, indata, _id=_id)
441 self.format_on_edit(content, indata)
442 # To allow project addressing by name AS WELL AS _id
443 # self.db.replace(self.topic, _id, content)
444 cid = content.get("_id")
445 self.db.replace(self.topic, cid if cid else _id, content)
446
447 indata.pop("_admin", None)
448 indata["_id"] = _id
449 self._send_msg("edit", indata)
450 return _id
451 except ValidationError as e:
452 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)