summaryrefslogtreecommitdiff
path: root/client/src/leap/soledad/client/shared_db.py
blob: 6abf8ea37d64656ab379d57225d886b10931c991 (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
# -*- coding: utf-8 -*-
# shared_db.py
# Copyright (C) 2013 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/>.
"""
A shared database for storing/retrieving encrypted key material.
"""
from u1db.remote import http_database

from leap.soledad.client.auth import TokenBasedAuth


# ----------------------------------------------------------------------------
# Soledad shared database
# ----------------------------------------------------------------------------

# TODO could have a hierarchy of soledad exceptions.


class NoTokenForAuth(Exception):
    """
    No token was found for token-based authentication.
    """


class Unauthorized(Exception):
    """
    User does not have authorization to perform task.
    """


class ImproperlyConfiguredError(Exception):
    """
    Wrong parameters in the database configuration.
    """


class SoledadSharedDatabase(http_database.HTTPDatabase, TokenBasedAuth):
    """
    This is a shared recovery database that enables users to store their
    encryption secrets in the server and retrieve them afterwards.
    """
    # TODO: prevent client from messing with the shared DB.
    # TODO: define and document API.

    # If syncable is False, the database will not attempt to sync against
    # a remote replica. Default is True.
    syncable = True

    #
    # Token auth methods.
    #

    def set_token_credentials(self, uuid, token):
        """
        Store given credentials so we can sign the request later.

        :param uuid: The user's uuid.
        :type uuid: str
        :param token: The authentication token.
        :type token: str
        """
        TokenBasedAuth.set_token_credentials(self, uuid, token)

    def _sign_request(self, method, url_query, params):
        """
        Return an authorization header to be included in the HTTP request.

        :param method: The HTTP method.
        :type method: str
        :param url_query: The URL query string.
        :type url_query: str
        :param params: A list with encoded query parameters.
        :type param: list

        :return: The Authorization header.
        :rtype: list of tuple
        """
        return TokenBasedAuth._sign_request(self, method, url_query, params)

    #
    # Modified HTTPDatabase methods.
    #

    @staticmethod
    def open_database(url, uuid, creds=None, syncable=True):
        """
        Open a Soledad shared database.

        :param url: URL of the remote database.
        :type url: str
        :param uuid: The user's unique id.
        :type uuid: str
        :param creds: A tuple containing the authentication method and
            credentials.
        :type creds: tuple
        :param syncable:
            If syncable is False, the database will not attempt to sync against
            a remote replica.
        :type syncable: bool

        :return: The shared database in the given url.
        :rtype: SoledadSharedDatabase
        """
        # XXX fix below, doesn't work with tests.
        # if syncable and not url.startswith('https://'):
        #    raise ImproperlyConfiguredError(
        #        "Remote soledad server must be an https URI")
        db = SoledadSharedDatabase(url, uuid, creds=creds)
        db.syncable = syncable
        return db

    @staticmethod
    def delete_database(url):
        """
        Dummy method that prevents from deleting shared database.

        :raise: This will always raise an Unauthorized exception.

        :param url: The database URL.
        :type url: str
        """
        raise Unauthorized("Can't delete shared database.")

    def __init__(self, url, uuid, document_factory=None, creds=None):
        """
        Initialize database with auth token and encryption powers.

        :param url: URL of the remote database.
        :type url: str
        :param uuid: The user's unique id.
        :type uuid: str
        :param document_factory: A factory for U1BD documents.
        :type document_factory: u1db.Document
        :param creds: A tuple containing the authentication method and
            credentials.
        :type creds: tuple
        """
        http_database.HTTPDatabase.__init__(self, url, document_factory,
                                            creds)
        self._uuid = uuid

    def lock(self):
        """
        Obtain a lock on document with id C{doc_id}.

        :return: A tuple containing the token to unlock and the timeout until
                 lock expiration.
        :rtype: (str, float)

        :raise HTTPError: Raised if any HTTP error occurs.
        """
        if self.syncable:
            res, headers = self._request_json(
                'PUT', ['lock', self._uuid], body={})
            return res['token'], res['timeout']
        else:
            return None, None

    def unlock(self, token):
        """
        Release the lock on shared database.

        :param token: The token returned by a previous call to lock().
        :type token: str

        :raise HTTPError:
        """
        if self.syncable:
            _, _ = self._request_json(
                'DELETE', ['lock', self._uuid], params={'token': token})