From 090c01bf8a4c6c12d7570f3a247b3b4e854a0ec0 Mon Sep 17 00:00:00 2001 From: Martin Zimmermann Date: Fri, 25 Jul 2014 10:55:01 +0200 Subject: [PATCH] disable zlib compression in signer --- isso/tests/test_utils.py | 18 ++++++++++++++++++ isso/utils/__init__.py | 21 +++++++++++++++++++++ isso/views/api.py | 2 ++ 3 files changed, 41 insertions(+) diff --git a/isso/tests/test_utils.py b/isso/tests/test_utils.py index 0504c15..aa52264 100644 --- a/isso/tests/test_utils.py +++ b/isso/tests/test_utils.py @@ -2,6 +2,8 @@ import unittest +import itsdangerous + from isso import utils from isso.utils import parse @@ -19,6 +21,22 @@ class TestUtils(unittest.TestCase): self.assertEqual(utils.anonymize(addr), anonymized) +class TestURLSafeTimedSerializer(unittest.TestCase): + + def test_serializer(self): + signer = utils.URLSafeTimedSerializer("") + payload = [1, "x" * 1024] + self.assertEqual(signer.loads(signer.dumps(payload)), payload) + + def test_nocompression(self): + plain = utils.URLSafeTimedSerializer("") + zlib = itsdangerous.URLSafeTimedSerializer("") + + payload = "x" * 1024 + self.assertTrue(zlib.dumps(payload).startswith(".")) + self.assertNotEqual(plain.dumps(payload), zlib.dumps(payload)) + + class TestParse(unittest.TestCase): def test_thread(self): diff --git a/isso/utils/__init__.py b/isso/utils/__init__.py index 6a22581..8f45e14 100644 --- a/isso/utils/__init__.py +++ b/isso/utils/__init__.py @@ -6,8 +6,11 @@ import pkg_resources werkzeug = pkg_resources.get_distribution("werkzeug") import json +import base64 import hashlib +from itsdangerous import BadPayload, TimedSerializer, compact_json + from werkzeug.wrappers import Request, Response from werkzeug.exceptions import BadRequest @@ -103,3 +106,21 @@ class JSONResponse(Response): kwargs["content_type"] = "application/json" super(JSONResponse, self).__init__( json.dumps(obj).encode("utf-8"), *args, **kwargs) + + +class URLSafeTimedSerializer(TimedSerializer): + + default_serializer = compact_json + + def load_payload(self, payload): + try: + json = base64.b64decode(payload + b"=" * (len(payload) % 4)) + except Exception as e: + raise BadPayload('Could not base64 decode the payload because of ' + 'an exception', original_error=e) + + return super(TimedSerializer, self).load_payload(json) + + def dump_payload(self, obj): + json = super(TimedSerializer, self).dump_payload(obj) + return base64.b64encode(json) diff --git a/isso/views/api.py b/isso/views/api.py index 3bbf772..76a05a2 100644 --- a/isso/views/api.py +++ b/isso/views/api.py @@ -50,6 +50,7 @@ def xhr(func): return dec + def auth(func): """A decorator to check the validity of an auth cookie.""" @@ -65,6 +66,7 @@ def auth(func): return dec + class API(object): # comment fields, that can be submitted