示例#1
0
文件: image.py 项目: johim/thumbor
    def get(self, **kw):
        url = self.request.uri

        if not self.validate(kw["image"]):
            self._error(404, "No original image was specified in the given URL")
            return

        self.context.request = RequestParameters(**kw)

        self.context.request.unsafe = self.context.request.unsafe == "unsafe"

        if self.request.query:
            self.context.request.image_url += "?%s" % self.request.query
        self.context.request.image_url = quote(self.context.request.image_url, "/:?%=&")

        has_none = not self.context.request.unsafe and not self.context.request.hash
        has_both = self.context.request.unsafe and self.context.request.hash

        if has_none or has_both:
            self._error(404, "URL does not have hash or unsafe, or has both: %s" % url)
            return

        if self.context.request.unsafe and not self.context.config.ALLOW_UNSAFE_URL:
            self._error(404, "URL has unsafe but unsafe is not allowed by the config: %s" % url)
            return

        url_signature = self.context.request.hash
        if url_signature:
            signer = Signer(self.context.server.security_key)

            url_to_validate = url.replace("/%s/" % self.context.request.hash, "")
            valid = signer.validate(url_signature, url_to_validate)

            if not valid and self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
                # Retrieves security key for this image if it has been seen before
                security_key = self.context.modules.storage.get_crypto(self.context.request.image_url)
                if security_key is not None:
                    signer = Signer(security_key)
                    valid = signer.validate(url_signature, url_to_validate)

            if not valid:
                is_valid = True
                if self.context.config.ALLOW_OLD_URLS:
                    cr = Cryptor(self.context.server.security_key)
                    options = cr.get_options(self.context.request.hash, self.context.request.image_url)
                    if options is None:
                        is_valid = False
                    else:
                        self.context.request = RequestParameters(**options)
                        logger.warning(
                            "OLD FORMAT URL DETECTED!!! This format of URL will be discontinued in upcoming versions. Please start using the new format as soon as possible. More info at https://github.com/globocom/thumbor/wiki/3.0.0-release-changes"
                        )
                else:
                    is_valid = False

                if not is_valid:
                    self._error(404, "Malformed URL: %s" % url)
                    return

        return self.execute_image_operations()
示例#2
0
    def test_get_options_from_storage(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(
                STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True
            ),
            modules=mock.Mock(
                storage=mock_storage
            ),
        )

        mock_storage.get_crypto.return_value = custom_security_key

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).not_to_be_null()

        expected_options = {
            'trim': 'trim', 'full': False, 'halign': 'center', 'fit_in': False,
            'vertical_flip': True, 'image': '/some/image.jpg',
            'crop': {'top': 11, 'right': 12, 'bottom': 13, 'left': 10},
            'height': 300, 'width': 300, 'meta': False, 'horizontal_flip': True,
            'filters': 'some_filter()', 'valign': 'middle', 'debug': False,
            'hash': 'e2baf424fa420b73a97476956dfb858f', 'adaptive': False, 'smart': True
        }

        expect(options).to_be_like(expected_options)
示例#3
0
    def test_get_options_from_storage_returns_null_if_key_not_found(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(
                STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True
            ),
            modules=mock.Mock(
                storage=mock_storage
            ),
        )

        mock_storage.get_crypto.return_value = None

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()
示例#4
0
    def test_get_options_from_storage_returns_null_if_key_not_found(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True),
            modules=mock.Mock(storage=mock_storage),
        )

        mock_storage.get_crypto.return_value = None

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()
示例#5
0
文件: imaging.py 项目: rdkls/thumbor
    def check_image(self, kw):
        if self.context.config.MAX_ID_LENGTH > 0:
            # Check if an image with an uuid exists in storage
            exists = yield gen.maybe_future(self.context.modules.storage.exists(kw['image'][:self.context.config.MAX_ID_LENGTH]))
            if exists:
                kw['image'] = kw['image'][:self.context.config.MAX_ID_LENGTH]

        url = self.request.uri

        if not self.validate(kw['image']):
            self._error(400, 'No original image was specified in the given URL')
            return

        kw['request'] = self.request

        self.context.request = RequestParameters(**kw)

        has_none = not self.context.request.unsafe and not self.context.request.hash
        has_both = self.context.request.unsafe and self.context.request.hash

        if has_none or has_both:
            self._error(400, 'URL does not have hash or unsafe, or has both: %s' % url)
            return

        if self.context.request.unsafe and not self.context.config.ALLOW_UNSAFE_URL:
            self._error(400, 'URL has unsafe but unsafe is not allowed by the config: %s' % url)
            return

        if self.context.config.USE_BLACKLIST:
            blacklist = yield self.get_blacklist_contents()
            if self.context.request.image_url in blacklist:
                self._error(400, 'Source image url has been blacklisted: %s' % self.context.request.image_url )
                return

        url_signature = self.context.request.hash
        if url_signature:
            signer = Signer(self.context.server.security_key)

            url_to_validate = Url.encode_url(url).replace('/%s/' % self.context.request.hash, '')
            valid = signer.validate(url_signature, url_to_validate)

            if not valid and self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
                # Retrieves security key for this image if it has been seen before
                security_key = yield gen.maybe_future(self.context.modules.storage.get_crypto(self.context.request.image_url))
                if security_key is not None:
                    signer = Signer(security_key)
                    valid = signer.validate(url_signature, url_to_validate)

            if not valid:
                is_valid = True
                if self.context.config.ALLOW_OLD_URLS:
                    cr = Cryptor(self.context.server.security_key)
                    options = cr.get_options(self.context.request.hash, self.context.request.image_url)
                    if options is None:
                        is_valid = False
                    else:
                        options['request'] = self.request
                        self.context.request = RequestParameters(**options)
                        logger.warning(
                            'OLD FORMAT URL DETECTED!!! This format of URL will be discontinued in ' +
                            'upcoming versions. Please start using the new format as soon as possible. ' +
                            'More info at https://github.com/globocom/thumbor/wiki/3.0.0-release-changes'
                        )
                else:
                    is_valid = False

                if not is_valid:
                    self._error(400, 'Malformed URL: %s' % url)
                    return

        self.execute_image_operations()
示例#6
0
文件: imaging.py 项目: y2khjh/thumbor
    def check_image(self, kw):
        if self.context.config.MAX_ID_LENGTH > 0:
            # Check if an image with an uuid exists in storage
            exists = yield gen.maybe_future(
                self.context.modules.storage.exists(
                    kw['image'][:self.context.config.MAX_ID_LENGTH]))
            if exists:
                kw['image'] = kw['image'][:self.context.config.MAX_ID_LENGTH]

        url = self.request.uri

        if not self.validate(kw['image']):
            self._error(400,
                        'No original image was specified in the given URL')
            return

        kw['request'] = self.request

        self.context.request = RequestParameters(**kw)

        has_none = not self.context.request.unsafe and not self.context.request.hash
        has_both = self.context.request.unsafe and self.context.request.hash

        if has_none or has_both:
            self._error(
                400, 'URL does not have hash or unsafe, or has both: %s' % url)
            return

        if self.context.request.unsafe and not self.context.config.ALLOW_UNSAFE_URL:
            self._error(
                400,
                'URL has unsafe but unsafe is not allowed by the config: %s' %
                url)
            return

        if self.context.config.USE_BLACKLIST:
            blacklist = yield self.get_blacklist_contents()
            if self.context.request.image_url in blacklist:
                self._error(
                    400, 'Source image url has been blacklisted: %s' %
                    self.context.request.image_url)
                return

        url_signature = self.context.request.hash
        if url_signature:
            signer = self.context.modules.url_signer(
                self.context.server.security_key)

            url_to_validate = Url.encode_url(url).replace(
                '/%s/' % self.context.request.hash, '')
            valid = signer.validate(url_signature, url_to_validate)

            if not valid and self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
                # Retrieves security key for this image if it has been seen before
                security_key = yield gen.maybe_future(
                    self.context.modules.storage.get_crypto(
                        self.context.request.image_url))
                if security_key is not None:
                    signer = self.context.modules.url_signer(security_key)
                    valid = signer.validate(url_signature, url_to_validate)

            if not valid:
                is_valid = True
                if self.context.config.ALLOW_OLD_URLS:
                    cr = Cryptor(self.context.server.security_key)
                    options = cr.get_options(self.context.request.hash,
                                             self.context.request.image_url)
                    if options is None:
                        is_valid = False
                    else:
                        options['request'] = self.request
                        self.context.request = RequestParameters(**options)
                        logger.warning(
                            'OLD FORMAT URL DETECTED!!! This format of URL will be discontinued in '
                            +
                            'upcoming versions. Please start using the new format as soon as possible. '
                            +
                            'More info at https://github.com/thumbor/thumbor/wiki/3.0.0-release-changes'
                        )
                else:
                    is_valid = False

                if not is_valid:
                    self._error(400, 'Malformed URL: %s' % url)
                    return

        self.execute_image_operations()
示例#7
0
文件: image.py 项目: mal/thumbor
    def get(self, **kw):
        url = self.request.uri

        if not self.validate(kw['image']):
            self._error(404,
                        'No original image was specified in the given URL')
            return

        self.context.request = RequestParameters(**kw)

        self.context.request.unsafe = self.context.request.unsafe == 'unsafe'

        if (self.request.query):
            self.context.request.image_url += '?%s' % self.request.query
        self.context.request.image_url = self.encode_url(
            self.context.request.image_url.encode('utf-8'))

        has_none = not self.context.request.unsafe and not self.context.request.hash
        has_both = self.context.request.unsafe and self.context.request.hash

        if has_none or has_both:
            self._error(
                404, 'URL does not have hash or unsafe, or has both: %s' % url)
            return

        if self.context.request.unsafe and not self.context.config.ALLOW_UNSAFE_URL:
            self._error(
                404,
                'URL has unsafe but unsafe is not allowed by the config: %s' %
                url)
            return

        url_signature = self.context.request.hash
        if url_signature:
            signer = Signer(self.context.server.security_key)

            url_to_validate = self.encode_url(url).replace(
                '/%s/' % self.context.request.hash, '')
            valid = signer.validate(url_signature, url_to_validate)

            if not valid and self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
                # Retrieves security key for this image if it has been seen before
                security_key = self.context.modules.storage.get_crypto(
                    self.context.request.image_url)
                if security_key is not None:
                    signer = Signer(security_key)
                    valid = signer.validate(url_signature, url_to_validate)

            if not valid:
                is_valid = True
                if self.context.config.ALLOW_OLD_URLS:
                    cr = Cryptor(self.context.server.security_key)
                    options = cr.get_options(self.context.request.hash,
                                             self.context.request.image_url)
                    if options is None:
                        is_valid = False
                    else:
                        self.context.request = RequestParameters(**options)
                        logger.warning(
                            'OLD FORMAT URL DETECTED!!! This format of URL will be discontinued in upcoming versions. Please start using the new format as soon as possible. More info at https://github.com/globocom/thumbor/wiki/3.0.0-release-changes'
                        )
                else:
                    is_valid = False

                if not is_valid:
                    self._error(404, 'Malformed URL: %s' % url)
                    return

        return self.execute_image_operations()
示例#8
0
class CryptoTestCase(TestCase):
    def setUp(self, *args, **kw):
        super(CryptoTestCase, self).setUp(*args, **kw)
        self.cryptor = Cryptor(security_key="something")
        self.cryptor.context = mock.Mock(
            config=mock.Mock(STORES_CRYPTO_KEY_FOR_EACH_IMAGE=False), )

    def test_can_create_crypto_with_key(self):
        cryptor = Cryptor("key")
        expect(cryptor).not_to_be_null()
        expect(cryptor.security_key).to_equal("keykeykeykeykeyk")

    def test_can_encrypt(self):
        encrypted = self.cryptor.encrypt(width=300,
                                         height=300,
                                         smart=True,
                                         adaptive=False,
                                         full=False,
                                         fit_in=False,
                                         flip_horizontal=True,
                                         flip_vertical=True,
                                         halign="center",
                                         valign="middle",
                                         trim=True,
                                         crop_left=10,
                                         crop_top=11,
                                         crop_right=12,
                                         crop_bottom=13,
                                         filters='some_filter()',
                                         image="/some/image.jpg")

        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"

        expect(encrypted).to_equal(encrypted_str)

    def test_can_decrypt(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"

        decrypted = self.cryptor.decrypt(encrypted_str)

        expect(decrypted).not_to_be_null()
        expect(decrypted).not_to_be_an_error()
        expect(decrypted).not_to_be_empty()
        expect(decrypted['width']).to_equal(300)
        expect(decrypted['height']).to_equal(300)
        expect(decrypted['smart']).to_be_true()
        expect(decrypted['fit_in']).to_be_false()
        expect(decrypted['horizontal_flip']).to_be_true()
        expect(decrypted['vertical_flip']).to_be_true()
        expect(decrypted['halign']).to_equal('center')
        expect(decrypted['valign']).to_equal('middle')
        expect(decrypted['crop']['left']).to_equal(10)
        expect(decrypted['crop']['top']).to_equal(11)
        expect(decrypted['crop']['right']).to_equal(12)
        expect(decrypted['crop']['bottom']).to_equal(13)
        expect(decrypted['filters']).to_equal('some_filter()')

        image_hash = hashlib.md5('/some/image.jpg').hexdigest()
        expect(decrypted['image_hash']).to_equal(image_hash)

    def test_decrypting_with_wrong_key(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"

        cryptor = Cryptor(security_key="simething")
        wrong = cryptor.decrypt(encrypted_str)
        right = self.cryptor.decrypt(encrypted_str)
        expect(wrong['image_hash']).not_to_equal(str(right['image_hash']))

    def test_get_options(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"
        image_url = "/some/image.jpg"

        expected_options = {
            'trim': 'trim',
            'full': False,
            'halign': 'center',
            'fit_in': False,
            'vertical_flip': True,
            'image': '/some/image.jpg',
            'crop': {
                'top': 11,
                'right': 12,
                'bottom': 13,
                'left': 10
            },
            'height': 300,
            'width': 300,
            'meta': False,
            'horizontal_flip': True,
            'filters': 'some_filter()',
            'valign': 'middle',
            'debug': False,
            'hash': 'e2baf424fa420b73a97476956dfb858f',
            'adaptive': False,
            'smart': True
        }
        options = self.cryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_like(expected_options)

    def test_get_options_returns_null_if_invalid(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs"
        image_url = "/some/image.jpg"

        options = self.cryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()

    def test_get_options_returns_null_if_different_path(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"
        image_url = "/some/image2.jpg"

        options = self.cryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()

    def test_get_options_from_storage(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True),
            modules=mock.Mock(storage=mock_storage),
        )

        mock_storage.get_crypto.return_value = custom_security_key

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).not_to_be_null()

        expected_options = {
            'trim': 'trim',
            'full': False,
            'halign': 'center',
            'fit_in': False,
            'vertical_flip': True,
            'image': '/some/image.jpg',
            'crop': {
                'top': 11,
                'right': 12,
                'bottom': 13,
                'left': 10
            },
            'height': 300,
            'width': 300,
            'meta': False,
            'horizontal_flip': True,
            'filters': 'some_filter()',
            'valign': 'middle',
            'debug': False,
            'hash': 'e2baf424fa420b73a97476956dfb858f',
            'adaptive': False,
            'smart': True
        }

        expect(options).to_be_like(expected_options)

    def test_get_options_from_storage_returns_null_if_key_not_found(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True),
            modules=mock.Mock(storage=mock_storage),
        )

        mock_storage.get_crypto.return_value = None

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()
示例#9
0
    def test_get_options_from_storage(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True),
            modules=mock.Mock(storage=mock_storage),
        )

        mock_storage.get_crypto.return_value = custom_security_key

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).not_to_be_null()

        expected_options = {
            'trim': 'trim',
            'full': False,
            'halign': 'center',
            'fit_in': False,
            'vertical_flip': True,
            'image': '/some/image.jpg',
            'crop': {
                'top': 11,
                'right': 12,
                'bottom': 13,
                'left': 10
            },
            'height': 300,
            'width': 300,
            'meta': False,
            'horizontal_flip': True,
            'filters': 'some_filter()',
            'valign': 'middle',
            'debug': False,
            'hash': 'e2baf424fa420b73a97476956dfb858f',
            'adaptive': False,
            'smart': True
        }

        expect(options).to_be_like(expected_options)
示例#10
0
    def get(self, **kw):

        # Check if an image with an uuid exists in storage
        if self.context.modules.storage.exists(kw['image'][:32]):
            kw['image'] = kw['image'][:32]

        url = self.request.uri

        if not self.validate(kw['image']):
            self._error(404, 'No original image was specified in the given URL')
            return

        self.context.request = RequestParameters(**kw)

        self.context.request.unsafe = self.context.request.unsafe == 'unsafe'

        if (self.request.query):
            self.context.request.image_url += '?%s' % self.request.query
        self.context.request.image_url = self.encode_url(self.context.request.image_url.encode('utf-8'))

        has_none = not self.context.request.unsafe and not self.context.request.hash
        has_both = self.context.request.unsafe and self.context.request.hash

        if has_none or has_both:
            self._error(404, 'URL does not have hash or unsafe, or has both: %s' % url)
            return

        if self.context.request.unsafe and not self.context.config.ALLOW_UNSAFE_URL:
            self._error(404, 'URL has unsafe but unsafe is not allowed by the config: %s' % url)
            return

        url_signature = self.context.request.hash
        if url_signature:
            signer = Signer(self.context.server.security_key)

            url_to_validate = self.encode_url(url).replace('/%s/' % self.context.request.hash, '')
            valid = signer.validate(url_signature, url_to_validate)

            if not valid and self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
                # Retrieves security key for this image if it has been seen before
                security_key = self.context.modules.storage.get_crypto(self.context.request.image_url)
                if security_key is not None:
                    signer = Signer(security_key)
                    valid = signer.validate(url_signature, url_to_validate)

            if not valid:
                is_valid = True
                if self.context.config.ALLOW_OLD_URLS:
                    cr = Cryptor(self.context.server.security_key)
                    options = cr.get_options(self.context.request.hash, self.context.request.image_url)
                    if options is None:
                        is_valid = False
                    else:
                        self.context.request = RequestParameters(**options)
                        logger.warning('OLD FORMAT URL DETECTED!!! This format of URL will be discontinued in upcoming versions. Please start using the new format as soon as possible. More info at https://github.com/globocom/thumbor/wiki/3.0.0-release-changes')
                else:
                    is_valid = False

                if not is_valid:
                    self._error(404, 'Malformed URL: %s' % url)
                    return

        return self.execute_image_operations()
示例#11
0
class CryptoTestCase(TestCase):
    def setUp(self, *args, **kw):
        super(CryptoTestCase, self).setUp(*args, **kw)
        self.cryptor = Cryptor(security_key="something")
        self.cryptor.context = mock.Mock(
            config=mock.Mock(
                STORES_CRYPTO_KEY_FOR_EACH_IMAGE=False
            ),
        )

    def test_can_create_crypto_with_key(self):
        cryptor = Cryptor("key")
        expect(cryptor).not_to_be_null()
        expect(cryptor.security_key).to_equal("keykeykeykeykeyk")

    def test_can_encrypt(self):
        encrypted = self.cryptor.encrypt(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image="/some/image.jpg"
        )

        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"

        expect(encrypted).to_equal(encrypted_str)

    def test_can_decrypt(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"

        decrypted = self.cryptor.decrypt(encrypted_str)

        expect(decrypted).not_to_be_null()
        expect(decrypted).not_to_be_an_error()
        expect(decrypted).not_to_be_empty()
        expect(decrypted['width']).to_equal(300)
        expect(decrypted['height']).to_equal(300)
        expect(decrypted['smart']).to_be_true()
        expect(decrypted['fit_in']).to_be_false()
        expect(decrypted['horizontal_flip']).to_be_true()
        expect(decrypted['vertical_flip']).to_be_true()
        expect(decrypted['halign']).to_equal('center')
        expect(decrypted['valign']).to_equal('middle')
        expect(decrypted['crop']['left']).to_equal(10)
        expect(decrypted['crop']['top']).to_equal(11)
        expect(decrypted['crop']['right']).to_equal(12)
        expect(decrypted['crop']['bottom']).to_equal(13)
        expect(decrypted['filters']).to_equal('some_filter()')

        image_hash = hashlib.md5('/some/image.jpg').hexdigest()
        expect(decrypted['image_hash']).to_equal(image_hash)

    def test_decrypting_with_wrong_key(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"

        cryptor = Cryptor(security_key="simething")
        wrong = cryptor.decrypt(encrypted_str)
        right = self.cryptor.decrypt(encrypted_str)
        expect(wrong['image_hash']).not_to_equal(str(right['image_hash']))

    def test_get_options(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"
        image_url = "/some/image.jpg"

        expected_options = {
            'trim': 'trim', 'full': False, 'halign': 'center', 'fit_in': False,
            'vertical_flip': True, 'image': '/some/image.jpg',
            'crop': {'top': 11, 'right': 12, 'bottom': 13, 'left': 10},
            'height': 300, 'width': 300, 'meta': False, 'horizontal_flip': True,
            'filters': 'some_filter()', 'valign': 'middle', 'debug': False,
            'hash': 'e2baf424fa420b73a97476956dfb858f', 'adaptive': False, 'smart': True
        }
        options = self.cryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_like(expected_options)

    def test_get_options_returns_null_if_invalid(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs"
        image_url = "/some/image.jpg"

        options = self.cryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()

    def test_get_options_returns_null_if_different_path(self):
        encrypted_str = "hELdyDzyYtjXU5GhGxJVHjRvGrSP_iYKnIQbq_MuVq86rSObCeJvo2iXFRUjLgs" \
            "U9wDzhqK9J_SHmpxDJHW_rBD8eilO26x2M_hzJfGB-V9cGF65GO_7CgJXI8Ktw188"
        image_url = "/some/image2.jpg"

        options = self.cryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()

    def test_get_options_from_storage(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(
                STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True
            ),
            modules=mock.Mock(
                storage=mock_storage
            ),
        )

        mock_storage.get_crypto.return_value = custom_security_key

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).not_to_be_null()

        expected_options = {
            'trim': 'trim', 'full': False, 'halign': 'center', 'fit_in': False,
            'vertical_flip': True, 'image': '/some/image.jpg',
            'crop': {'top': 11, 'right': 12, 'bottom': 13, 'left': 10},
            'height': 300, 'width': 300, 'meta': False, 'horizontal_flip': True,
            'filters': 'some_filter()', 'valign': 'middle', 'debug': False,
            'hash': 'e2baf424fa420b73a97476956dfb858f', 'adaptive': False, 'smart': True
        }

        expect(options).to_be_like(expected_options)

    def test_get_options_from_storage_returns_null_if_key_not_found(self):
        image_url = "/some/image.jpg"
        custom_security_key = "custom-sec"
        cryptor = Cryptor(security_key=custom_security_key)
        decryptor = Cryptor(security_key="something")

        expected_options = dict(
            width=300,
            height=300,
            smart=True,
            adaptive=False,
            full=False,
            fit_in=False,
            flip_horizontal=True,
            flip_vertical=True,
            halign="center",
            valign="middle",
            trim=True,
            crop_left=10,
            crop_top=11,
            crop_right=12,
            crop_bottom=13,
            filters='some_filter()',
            image=image_url,
        )

        encrypted_str = cryptor.encrypt(**expected_options)

        mock_storage = mock.Mock()
        decryptor.context = mock.Mock(
            config=mock.Mock(
                STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True
            ),
            modules=mock.Mock(
                storage=mock_storage
            ),
        )

        mock_storage.get_crypto.return_value = None

        options = decryptor.get_options(encrypted_str, image_url)
        expect(options).to_be_null()