summaryrefslogtreecommitdiff
path: root/tests/blobs/test_fs_backend.py
blob: 94b628c439116686f51f5d7420460f61a0261dfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# -*- coding: utf-8 -*-
# test_fs_backend.py
# Copyright (C) 2017 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Tests for blobs backend on server side.
"""
from twisted.trial import unittest
from twisted.internet import defer
from twisted.web.test.test_web import DummyRequest
from leap.common.files import mkdir_p
from leap.soledad.server import _blobs
from io import BytesIO
from mock import Mock
import mock
import os
import base64
import json
import pytest


class FilesystemBackendTestCase(unittest.TestCase):

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch.object(_blobs, 'open')
    def test_tag_header(self, open_mock):
        open_mock.return_value = BytesIO('A' * 40 + 'B' * 16)
        expected_tag = base64.urlsafe_b64encode('B' * 16)
        expected_method = Mock()
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        # write a blob...
        path = backend._get_path('user', 'blob_id', '')
        mkdir_p(os.path.split(path)[0])
        with open(path, "w") as f:
            f.write("bl0b")
        # ...and get its tag
        request = Mock(responseHeaders=Mock(setRawHeaders=expected_method))
        backend.add_tag_header('user', 'blob_id', request)

        expected_method.assert_called_once_with('Tag', [expected_tag])

    @pytest.mark.usefixtures("method_tmpdir")
    def test_get_blob_size(self):
        # get a backend
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        # write a blob with size=10
        path = backend._get_path('user', 'blob_id', '')
        mkdir_p(os.path.split(path)[0])
        with open(path, "w") as f:
            f.write("0123456789")
        # check it's size
        size = backend.get_blob_size('user', 'blob_id', '')
        self.assertEquals(10, size)

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch.object(_blobs.static, 'File')
    @mock.patch.object(_blobs.FilesystemBlobsBackend, '_get_path',
                       Mock(return_value='path'))
    def test_read_blob(self, file_mock):
        render_mock = Mock()
        file_mock.return_value = render_mock
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        request = DummyRequest([''])
        backend.read_blob('user', 'blob_id', request)

        backend._get_path.assert_called_once_with('user', 'blob_id', '')
        ctype = 'application/octet-stream'
        _blobs.static.File.assert_called_once_with('path', defaultType=ctype)
        render_mock.render_GET.assert_called_once_with(request)

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch.object(os.path, 'isfile')
    @mock.patch.object(_blobs.FilesystemBlobsBackend, '_get_path',
                       Mock(return_value='path'))
    @defer.inlineCallbacks
    def test_cannot_overwrite(self, isfile):
        isfile.return_value = True
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        request = DummyRequest([''])
        yield backend.write_blob('user', 'blob_id', request)
        self.assertEquals(request.written[0], "Blob already exists: blob_id")
        self.assertEquals(request.responseCode, 409)

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch.object(os.path, 'isfile')
    @defer.inlineCallbacks
    def test_write_cannot_exceed_quota(self, isfile):
        isfile.return_value = False
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        request = Mock()

        backend.get_total_storage = lambda x: 100
        backend.quota = 90
        yield backend.write_blob('user', 'blob_id', request)

        request.setResponseCode.assert_called_once_with(507)
        request.write.assert_called_once_with('Quota Exceeded!')

    @pytest.mark.usefixtures("method_tmpdir")
    def test_get_path_partitioning_by_default(self):
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        backend.path = '/somewhere/'
        path = backend._get_path('user', 'blob_id', '')
        expected = '/somewhere/user/default/b/blo/blob_i/blob_id'
        self.assertEquals(path, expected)

    @pytest.mark.usefixtures("method_tmpdir")
    def test_get_path_custom(self):
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        backend.path = '/somewhere/'
        path = backend._get_path('user', 'blob_id', 'wonderland')
        expected = '/somewhere/user/wonderland/b/blo/blob_i/blob_id'
        self.assertEquals(expected, path)

    @pytest.mark.usefixtures("method_tmpdir")
    def test_get_path_namespace_traversal_raises(self):
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        backend.path = '/somewhere/'
        with pytest.raises(Exception):
            backend._get_path('user', 'blob_id', '..')

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch('leap.soledad.server._blobs.os.walk')
    def test_list_blobs(self, walk_mock):
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        _ = None
        walk_mock.return_value = [('', _, ['blob_0']), ('', _, ['blob_1'])]
        result = json.loads(backend.list_blobs('user', DummyRequest([''])))
        self.assertEquals(result, ['blob_0', 'blob_1'])

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch('leap.soledad.server._blobs.os.walk')
    def test_list_blobs_limited_by_namespace(self, walk_mock):
        backend = _blobs.FilesystemBlobsBackend(self.tempdir)
        _ = None
        walk_mock.return_value = [('', _, ['blob_0']), ('', _, ['blob_1'])]
        result = json.loads(backend.list_blobs('user', DummyRequest(['']),
                                               namespace='incoming'))
        self.assertEquals(result, ['blob_0', 'blob_1'])
        target_dir = os.path.join(self.tempdir, 'user', 'incoming')
        walk_mock.assert_called_once_with(target_dir)

    @pytest.mark.usefixtures("method_tmpdir")
    def test_path_validation_on_read_blob(self):
        blobs_path, request = self.tempdir, DummyRequest([''])
        backend = _blobs.FilesystemBlobsBackend(blobs_path=blobs_path)
        with pytest.raises(Exception):
            backend.read_blob('..', '..', request)
        with pytest.raises(Exception):
            backend.read_blob('user', '../../../', request)
        with pytest.raises(Exception):
            backend.read_blob('../../../', 'blob_id', request)
        with pytest.raises(Exception):
            backend.read_blob('user', 'blob_id', request, namespace='..')

    @pytest.mark.usefixtures("method_tmpdir")
    @defer.inlineCallbacks
    def test_path_validation_on_write_blob(self):
        blobs_path, request = self.tempdir, DummyRequest([''])
        backend = _blobs.FilesystemBlobsBackend(blobs_path=blobs_path)
        with pytest.raises(Exception):
            yield backend.write_blob('..', '..', request)
        with pytest.raises(Exception):
            yield backend.write_blob('user', '../../../', request)
        with pytest.raises(Exception):
            yield backend.write_blob('../../../', 'id1', request)
        with pytest.raises(Exception):
            yield backend.write_blob('user', 'id2', request, namespace='..')

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch('leap.soledad.server._blobs.os.unlink')
    def test_delete_blob(self, unlink_mock):
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        request = DummyRequest([''])
        # write a blob...
        path = backend._get_path('user', 'blob_id', '')
        mkdir_p(os.path.split(path)[0])
        with open(path, "w") as f:
            f.write("bl0b")
        # ...and delete it
        backend.delete_blob('user', 'blob_id', request)
        unlink_mock.assert_any_call(backend._get_path('user',
                                                      'blob_id'))
        unlink_mock.assert_any_call(backend._get_path('user',
                                                      'blob_id') + '.flags')

    @pytest.mark.usefixtures("method_tmpdir")
    @mock.patch('leap.soledad.server._blobs.os.unlink')
    def test_delete_blob_custom_namespace(self, unlink_mock):
        backend = _blobs.FilesystemBlobsBackend(blobs_path=self.tempdir)
        request = DummyRequest([''])
        # write a blob...
        path = backend._get_path('user', 'blob_id', 'trash')
        mkdir_p(os.path.split(path)[0])
        with open(path, "w") as f:
            f.write("bl0b")
        # ...and delete it
        backend.delete_blob('user', 'blob_id', request, namespace='trash')
        unlink_mock.assert_any_call(backend._get_path('user',
                                                      'blob_id',
                                                      'trash'))
        unlink_mock.assert_any_call(backend._get_path('user',
                                                      'blob_id',
                                                      'trash') + '.flags')