From 1aea92a5f140e40fff07dca1fb13046d30188281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Jan 2019 14:35:32 +0100 Subject: [PATCH] =?UTF-8?q?=E2=98=94=20Protect=20against=20invalid=20preem?= =?UTF-8?q?ptive=20cache=20config=20data?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #3023 --- src/octoprint/server/util/flask.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index a62f3dee9..772538acd 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -878,11 +878,15 @@ class PreemptiveCache(object): if cache_data is None: cache_data = dict() + if not self._validate_data(cache_data): + self._logger.warn("Preemptive cache data was invalid, ignoring it") + cache_data = dict() + return cache_data def get_data(self, root): cache_data = self.get_all_data() - return cache_data.get(root, dict()) + return cache_data.get(root, list()) def set_all_data(self, data): from octoprint.util import atomic_write @@ -925,7 +929,7 @@ class PreemptiveCache(object): def get_newest(entries): result = None for entry in entries: - if "_timestamp" in entry and (result is None or ("_timestamp" in entry and result["_timestamp"] < entry["_timestamp"])): + if "_timestamp" in entry and (result is None or ("_timestamp" in result and result["_timestamp"] < entry["_timestamp"])): result = entry return result @@ -951,12 +955,32 @@ class PreemptiveCache(object): return set(strip_ignored(a).items()) == set(strip_ignored(b).items()) + def _validate_data(self, data): + if not isinstance(data, dict): + return False + + for root, entries in data.items(): + if not isinstance(entries, list): + return False + + for entry in entries: + if not self._validate_entry(entry): + return False + + return True + + def _validate_entry(self, entry): + return isinstance(entry, dict) and "_timestamp" in entry and "_count" in entry + def preemptively_cached(cache, data, unless=None): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): - cache.record(data, unless=unless) + try: + cache.record(data, unless=unless) + except: + logging.getLogger(__name__).exception(u"Error while recording preemptive cache entry: {!r}".format(data)) return f(*args, **kwargs) return decorated_function return decorator