File: service.py

package info (click to toggle)
python-etesync 0.12.1-1.2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 256 kB
  • sloc: python: 1,353; sh: 3; makefile: 2
file content (327 lines) | stat: -rw-r--r-- 11,451 bytes parent folder | download | duplicates (2)
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# Copyright © 2017 Tom Hacohen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, version 3.
#
# This library 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/>.

import requests
import json
import base64
import binascii
from http import HTTPStatus
from furl import furl

from .crypto import CryptoManager, HMAC_SIZE
from . import exceptions
from ._version import __version__

API_PATH = ('api', 'v1')
USER_AGENT = 'pyetesync/' + __version__


def _status_success(status_code):
    return status_code // 100 == 2


class Authenticator:
    def __init__(self, remote):
        self.remote = furl(remote)
        self.remote.path.segments.extend(('api-token-auth', ''))
        self.remote.path.normalize()

    def get_auth_token(self, username, password):
        headers = {'User-Agent': USER_AGENT}
        response = requests.post(self.remote.url, data={'username': username, 'password': password}, headers=headers)
        if response.status_code == HTTPStatus.BAD_REQUEST:
            raise exceptions.UnauthorizedException("Username or password incorrect.")
        elif not _status_success(response.status_code):
            raise exceptions.HttpException(response.status_code)

        data = response.json()
        return data['token']


class RawBase:
    def __init__(self, crypto_manager, content=None, uid=None):
        self.crypto_manager = crypto_manager
        self.uid = uid
        self.content = content

    @property
    def version(self):
        return self.crypto_manager.version

    def getContent(self):
        return self.crypto_manager.decrypt(self.content)

    def setContent(self, content):
        self.content = self.crypto_manager.encrypt(content)

    def to_simple(self):
        content = base64.b64encode(self.content)
        return {'uid': self.uid, 'content': content.decode()}

    def _verify_hmac(self, hmac1, hmac2):
        if hmac1 != hmac2:
            raise exceptions.IntegrityException("HMAC mismatch: {} != {}".format(
                binascii.hexlify(hmac1).decode(), binascii.hexlify(hmac2).decode()))


class RawJournal(RawBase):
    def __init__(self, crypto_manager, content=None, uid=None, owner=None, encrypted_key=None, read_only=False, remote_last_uid=None):
        super().__init__(crypto_manager, content, uid)
        if content is not None:
            self.hmac = content[:HMAC_SIZE]
            self.content = content[HMAC_SIZE:]
        self.owner = owner
        self.encrypted_key = encrypted_key
        self.read_only = read_only
        self.remote_last_uid = remote_last_uid

    def calc_hmac(self):
        return self.crypto_manager.hmac(self.uid.encode() + self.content)

    def verify(self):
        self._verify_hmac(self.hmac, self.calc_hmac())

    def to_simple(self):
        content = base64.b64encode(self.hmac + self.content)
        return {'uid': self.uid, 'content': content.decode(), 'version': self.version}

    def update(self, content):
        self.setContent(content)
        self.hmac = self.calc_hmac()


class RawEntry(RawBase):
    def calc_hmac(self, prev):
        prevUid = b''
        if prev is not None:
            prevUid = prev.uid.encode()

        return self.crypto_manager.hmac(prevUid + self.content)

    def verify(self, prev):
        self._verify_hmac(binascii.unhexlify(self.uid), self.calc_hmac(prev))

    def update(self, content, prev):
        self.setContent(content)
        self.uid = binascii.hexlify(self.calc_hmac(prev)).decode()


class RawUserInfo(RawBase):
    def __init__(self, crypto_manager, owner=None, pubkey=None, content=None):
        super().__init__(crypto_manager, content, None)
        self.owner = owner
        self.pubkey = pubkey
        if content is not None:
            self.hmac = content[:HMAC_SIZE]
            self.content = content[HMAC_SIZE:]

    def calc_hmac(self):
        return self.crypto_manager.hmac(self.content + self.pubkey)

    def verify(self):
        self._verify_hmac(self.hmac, self.calc_hmac())

    def to_simple(self):
        content = base64.b64encode(self.hmac + self.content)
        pubkey = base64.b64encode(self.pubkey)
        return {'owner': self.owner, 'pubkey': pubkey.decode(), 'content': content.decode(), 'version': self.version}

    def update(self, content):
        self.setContent(content)
        self.hmac = self.calc_hmac()


class BaseManager:
    def __init__(self, auth_token):
        headers = {
            'User-Agent': USER_AGENT,
            'Authorization': 'Token ' + auth_token,
        }
        self.requests = requests.Session()
        self.requests.headers.update(headers)

    def detail_url(self, uid):
        remote = self.remote.copy()
        remote.path.segments.extend((uid, ''))
        remote.path.normalize()
        return remote

    def _validate_response(self, response):
        if response.status_code == HTTPStatus.SERVICE_UNAVAILABLE:
            raise exceptions.ServiceUnavailableException("Service unavailable")
        elif response.status_code == HTTPStatus.UNAUTHORIZED:
            raise exceptions.UnauthorizedException("UNAUTHORIZED auth token")
        elif response.status_code == HTTPStatus.FORBIDDEN:
            data = response.json()
            if data.get('code') == 'service_inactive':
                raise exceptions.UserInactiveException(data.get('detail'))
        elif response.status_code == HTTPStatus.NOT_FOUND:
            raise exceptions.HttpNotFound(response.status_code)
        elif not _status_success(response.status_code):
            raise exceptions.HttpException(response.status_code)
        return response


class JournalManager(BaseManager):
    def __init__(self, remote, auth_token):
        super().__init__(auth_token)
        self.remote = furl(remote)
        self.remote.path.segments.extend(API_PATH + ('journals', ''))
        self.remote.path.normalize()

    def list(self, password):
        response = self.requests.get(self.remote.url)
        self._validate_response(response)
        data = response.json()
        for j in data:
            uid = j['uid']
            version = j['version']
            content = base64.b64decode(j['content'])
            owner = j['owner']
            key = j['key']
            readOnly = j['readOnly']
            last_uid = j.get('lastUid', None)
            encrypted_key = base64.b64decode(key) if key is not None else None
            crypto_manager = CryptoManager(version, password, uid.encode())
            journal = RawJournal(crypto_manager=crypto_manager, content=content, uid=uid, owner=owner,
                                 encrypted_key=encrypted_key, read_only=readOnly, remote_last_uid=last_uid)
            yield journal

    def add(self, journal):
        data = journal.to_simple()
        response = self.requests.post(self.remote.url, json=data)
        self._validate_response(response)

    def delete(self, journal):
        remote = self.detail_url(journal.uid)
        response = self.requests.delete(remote.url)
        self._validate_response(response)

    def update(self, journal):
        remote = self.detail_url(journal.uid)
        data = journal.to_simple()
        response = self.requests.put(remote.url, json=data)
        self._validate_response(response)

    # Members
    def _get_member_remote(self, journal, member_user=None):
        remote = self.detail_url(journal.uid).copy()
        segments = ['members']
        if member_user is not None:
            segments.append(member_user)
        segments.append('')
        remote.path.segments.extend(segments)
        remote.path.normalize()
        return remote

    def member_add(self, journal, member):
        remote = self._get_member_remote(journal)
        data = member.to_simple()
        response = self.requests.post(remote.url, json=data)
        self._validate_response(response)


class EntryManager(BaseManager):
    def __init__(self, remote, auth_token, journalId):
        super().__init__(auth_token)
        self.remote = furl(remote)
        self.remote.path.segments.extend(API_PATH + ('journals', journalId, 'entries', ''))
        self.remote.path.normalize()

    def list(self, crypto_manager, last=None):
        remote = self.remote.copy()
        prev = None
        if last is not None:
            prev = RawEntry(crypto_manager, b'', last)
            remote.args['last'] = last

        response = self.requests.get(remote.url)
        self._validate_response(response)
        data = response.json()
        for j in data:
            uid = j['uid']
            content = base64.b64decode(j['content'])
            entry = RawEntry(crypto_manager=crypto_manager, content=content, uid=uid)
            entry.verify(prev)
            prev = entry
            yield entry

    def add(self, entries, last=None):
        remote = self.remote.copy()
        if last is not None:
            remote.args['last'] = last

        data = list(map(lambda x: x.to_simple(), entries))
        response = self.requests.post(remote.url, json=data)
        self._validate_response(response)


class UserInfoManager(BaseManager):
    def __init__(self, remote, auth_token):
        super().__init__(auth_token)
        self.remote = furl(remote)
        self.remote.path.segments.extend(API_PATH + ('user', ''))
        self.remote.path.normalize()

    def get(self, owner, cipher_key):
        remote = self.detail_url(owner)
        response = self.requests.get(remote.url)
        self._validate_response(response)
        data = response.json()
        version = data['version']
        content = base64.b64decode(data['content'])
        pubkey = base64.b64decode(data['pubkey'])
        crypto_manager = CryptoManager(version, cipher_key, b"userInfo")
        return RawUserInfo(crypto_manager, owner, pubkey, content)

    def add(self, user_info):
        data = user_info.to_simple()
        response = self.requests.post(self.remote.url, json=data)
        self._validate_response(response)

    def delete(self, user_info):
        remote = self.detail_url(user_info.owner)
        response = self.requests.delete(remote.url)
        self._validate_response(response)

    def update(self, user_info):
        remote = self.detail_url(user_info.owner)
        data = user_info.to_simple()
        response = self.requests.put(remote.url, json=data)
        self._validate_response(response)


class SyncEntry:
    def __init__(self, action, content):
        self.action = action
        self.content = content

    @classmethod
    def from_json(cls, json_string):
        data = json.loads(json_string)
        return SyncEntry(data['action'], data['content'])

    def to_json(self):
        data = {'action': self.action, 'content': self.content}
        return json.dumps(data, ensure_ascii=False)


class Member:
    def __init__(self, user, key):
        self.user = user
        self.key = key

    def to_simple(self):
        key = base64.b64encode(self.key)
        return {'user': self.user, 'key': key.decode()}