File: database_manager.py

package info (click to toggle)
secrets 12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,616 kB
  • sloc: python: 6,838; xml: 7; makefile: 4
file content (427 lines) | stat: -rw-r--r-- 14,157 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# SPDX-License-Identifier: GPL-3.0-only
from __future__ import annotations

import io
import json
import logging
from pathlib import Path

from gi.repository import Gio, GLib, GObject
from pykeepass import PyKeePass
from pykeepass.exceptions import CredentialsError

import gsecrets.config_manager as config
from gsecrets.err import ErrorType, error, generic_error
from gsecrets.recent_manager import RecentManager
from gsecrets.safe_element import SafeEntry, SafeGroup
from gsecrets.utils import LazyValue, compare_passwords


class DatabaseManager(GObject.Object):
    # pylint: disable=too-many-public-methods
    # pylint: disable=too-many-instance-attributes
    """Implements database functionality that is independent of the UI.

    Useful attributes:
     .path: str containing the filepath of the database
     .is_dirty: bool telling whether the database is in a dirty state

    Group objects are of type `pykeepass.group.Group`
    Entry objects are of type `pykeepass.entry.Entry`
    Instances of both have useful attributes:
    .uuid: a `uuid.UUID` object
    """

    # self.db contains a `PyKeePass` database
    _elements_loaded = False
    password_try = ""
    _is_dirty = False  # Does the database need saving?
    save_running = False
    _opened = False

    # Used for checking if there are changes in the file.
    file_size: int | None = None
    file_mtime: int | None = None

    # Only used for setting the credentials to their actual values in case of
    # errors.
    old_password: str = ""
    composition_key: bytes | None = None

    trash_bin: SafeGroup | None = None
    root: SafeGroup | None = None

    locked = GObject.Property(type=bool, default=False)
    is_dirty = GObject.Property(type=bool, default=False)

    # To be emitted when the elements list model needs to be re sorted.
    sorting_changed = GObject.Signal(arg_types=(bool,))

    def __init__(self, key_providers: list, database_path: str) -> None:
        """Initialize the database handling logic.

        :param str database_path: The database path
        """
        super().__init__()

        self.entries = Gio.ListStore.new(SafeEntry)
        self.groups = Gio.ListStore.new(SafeGroup)

        self._key_providers = key_providers
        self._path = database_path
        self.db: PyKeePass = None

    def unlock_async(
        self,
        password: str,
        composition_key: bytes | None = None,
        callback: Gio.AsyncReadyCallback = None,
    ) -> None:
        """Unlocks and opens a safe.

        This pykeepass to open a safe database. If the database cannot
        be opened, an exception is raised.

        :param str password: password to use or an empty string
        :param str composition_key: composition_key as bytes
        :param GAsyncReadyCallback: callback run after the unlock operation ends
        """
        self._opened = False

        def unlock_task(task, _source_object, _task_data, _cancellable):
            if Path(self._path).suffix == ".kdb":
                # NOTE kdb is a an older format for Keepass databases.
                err = error(ErrorType.UNSUPPORTED_FORMAT)
                task.return_error(err)
                return

            try:
                db = PyKeePass(
                    self.path,
                    password,
                    io.BytesIO(composition_key) if composition_key else None,
                )
            except CredentialsError:
                err = error(ErrorType.CREDENTIALS_ERROR)
                task.return_error(err)
            except Exception as err:  # pylint: disable=broad-except
                err = generic_error(str(err))
                task.return_error(err)
            else:
                self.composition_key = composition_key
                self._update_file_monitor()
                task.return_value(db)

        task = Gio.Task.new(self, None, callback)
        task.run_in_thread(unlock_task)

    def unlock_finish(self, result):
        """Finish unlocking.

        Can raise errors.
        """
        _success, db = result.propagate_value()

        self.db = db
        self._opened = True
        logging.debug("Opening of safe %s was successful", self.path)

        if not self._elements_loaded:
            self.entries.splice(0, 0, [SafeEntry(self, e) for e in db.entries])
            self.groups.splice(0, 0, [SafeGroup(self, g) for g in db.groups])

            self._elements_loaded = True

        self.notify("description")
        self.notify("name")

    #
    # Database Modifications
    #

    def save_async(self, callback: Gio.AsyncReadyCallback) -> None:
        """Write all changes to database.

        This consists in two parts, we first save it to a byte stream in memory
        and then we write the contents of the stream into the database using
        Gio. This is done in this way since pykeepass save is not atomic,
        whereas GFile operations are.

        Note that certain operations in pykeepass can fail at the middle of the
        operation, nuking the database in the process.
        """
        task = Gio.Task.new(self, None, callback)
        task.run_in_thread(self._save_task)

    def _save_task(self, task, _obj, _data, _cancellable):
        if self.save_running:
            task.return_boolean(False)
            logging.debug("Save already running")
            return

        if not self.is_dirty:
            task.return_boolean(False)
            logging.debug("Safe is not dirty")
            return

        logging.debug("Saving database %s", self.path)
        self.save_running = True

        with io.BytesIO() as buf:
            try:
                self.db.save(buf)
            except Exception as err:  # pylint: disable=broad-except
                err = generic_error(str(err))
                task.return_error(err)
            else:
                flags = Gio.FileCreateFlags.NONE
                gfile = Gio.File.new_for_path(self._path)
                contents = buf.getvalue()
                try:
                    gfile.replace_contents(contents, None, False, flags, None)
                except GLib.Error as err:  # pylint: disable=broad-except
                    task.return_error(err)
                else:
                    self._update_file_monitor()
                    task.return_boolean(True)

    def save_finish(self, result: Gio.AsyncResult) -> bool:
        """Finish save_async.

        Returns whether the safe was saved. Can raise GLib.Error.
        """
        self.save_running = False
        is_saved = result.propagate_boolean()

        self.is_dirty = False
        if is_saved:
            logging.debug("Database %s saved successfully", self.path)

        return is_saved

    def set_credentials_async(
        self,
        password: str,
        composition_key: bytes | None = None,
        callback: Gio.AsyncReadyCallback = None,
    ) -> None:
        """Set credentials for safe.

        It does almost the same as save_async, with the difference that
        correctly handles errors, it won't leave the database in a state where
        its fields have the incorrect values.
        """

        def set_credentials_task(task, obj, data, cancellable):
            self.old_password = self.password
            self.password = password

            self.composition_key = composition_key
            if composition_key:
                self.db.keyfile = io.BytesIO(composition_key)
            else:
                self.db.keyfile = None

            self.is_dirty = True

            self._save_task(task, obj, data, cancellable)

        task = Gio.Task.new(self, None, callback)
        task.run_in_thread(set_credentials_task)

    def set_credentials_finish(self, result):
        self.save_running = False
        try:
            is_saved = result.propagate_boolean()
        except GLib.Error:
            self.password = self.old_password

            raise

        self.is_dirty = False
        if is_saved:
            logging.debug("Credentials changed successfully")

        return is_saved

    def add_to_history(self) -> None:
        gfile = Gio.File.new_for_path(self._path)
        uri = gfile.get_uri()

        recents = RecentManager()
        recents.add_item(gfile)

        # Set last opened database.
        config.set_last_opened_database(uri)

        if not config.get_remember_composite_key():
            return

        keyprovider_pairs = config.get_last_used_key_provider()

        data = {}
        for key_provider in self._key_providers:
            if key_provider.available and key_provider.key:
                provider_config = key_provider.config()
                data[type(key_provider).__name__] = provider_config

        keyprovider_pairs[uri] = json.dumps(data)
        config.set_last_used_key_provider(keyprovider_pairs)

    def _update_file_monitor(self):
        """Update the modified time and size of the database.

        This is a blocking operation.
        """
        gfile = Gio.File.new_for_path(self._path)
        attributes = (
            f"{Gio.FILE_ATTRIBUTE_STANDARD_SIZE},{Gio.FILE_ATTRIBUTE_TIME_MODIFIED}"
        )
        try:
            info = gfile.query_info(attributes, Gio.FileQueryInfoFlags.NONE, None)
        except GLib.Error:
            logging.exception("Could not read file size")
        else:
            self.file_size = info.get_size()
            self.file_mtime = info.get_modification_date_time().to_unix()

    def check_file_changes_async(self, callback: Gio.AsyncReadyCallback) -> None:
        task = Gio.Task.new(self, None, callback)
        task.run_in_thread(self._check_file_changes_task)

    def _check_file_changes_task(self, task, _obj, _data, _cancellable):
        gfile = Gio.File.new_for_path(self._path)
        attributes = (
            f"{Gio.FILE_ATTRIBUTE_STANDARD_SIZE},{Gio.FILE_ATTRIBUTE_TIME_MODIFIED}"
        )
        try:
            info = gfile.query_info(attributes, Gio.FileQueryInfoFlags.NONE, None)
        except GLib.Error as err:
            err = generic_error(str(err))
            task.return_error(err)
        else:
            if (
                self.file_size != info.get_size()
                or self.file_mtime != info.get_modification_date_time().to_unix()
            ):
                task.return_boolean(True)
            else:
                task.return_boolean(False)

    def check_file_changes_finish(self, result: Gio.AsyncResult) -> bool:
        """Finish check_file_changes_async.

        Returns whether the file was changed, can raise GLib.Error.
        """
        return result.propagate_boolean()

    @property
    def password(self) -> str:
        """Get the current password or '' if not set."""
        if db := self.db:
            return db.password or ""

        return ""

    @password.setter
    def password(self, new_password: str | None) -> None:
        """Set database password (None if a old_composition key is used)."""
        self.db.password = new_password
        self.is_dirty = True

    @GObject.Property(type=str, default="")
    def name(self) -> str:
        """Get the database name or '' if not set."""
        return self.db.database_name or ""

    @name.setter  # type: ignore
    def name(self, new_name: str | None) -> None:
        """Set database name."""
        self.db.database_name = new_name
        self.is_dirty = True

    @GObject.Property(type=str, default="")
    def description(self) -> str:
        """Get the database description or '' if not set."""
        return self.db.database_description or ""

    @description.setter  # type: ignore
    def description(self, new_description: str | None) -> None:
        """Set database description."""
        self.db.database_description = new_description
        self.is_dirty = True

    @property
    def default_username(self) -> str:
        """Get the default username or '' if not set."""
        return self.db.default_username or ""

    @default_username.setter
    def default_username(self, new_username: str | None) -> None:
        """Set default username."""
        self.db.default_username = new_username
        self.is_dirty = True

    #
    # Read Database
    #

    # Check if entry with title in group exists
    def check_entry_in_group_exists(self, title, group):
        entry = self.db.find_entries(
            title=title,
            group=group,
            recursive=False,
            history=False,
            first=True,
        )
        return entry is not None

    #
    # Database creation methods
    #

    # Set the first password entered by the user (for comparing reasons)
    def set_password_try(self, password):
        self.password_try = password

    def compare_passwords(self, password2: str) -> bool:
        """Compare the first password entered by the user with the second one.

        It also does not allow empty passwords.
        :returns: True if passwords match and are non-empty.
        """
        return compare_passwords(self.password_try, password2)

    def parent_checker(self, current_group, moved_group):
        """Return True if moved_group is an ancestor of current_group."""
        # recursively invoke ourself until we reach the root group
        if current_group.is_root_group:
            return False
        if current_group.uuid == moved_group.uuid:
            return True
        return self.parent_checker(current_group.parentgroup, moved_group)

    @property
    def version(self):
        """Returns the database version."""
        return self.db.version

    @property
    def opened(self) -> bool:
        return self._opened

    @property
    def path(self) -> str:
        return self._path

    def get_salt_as_lazy(self) -> LazyValue[bytes]:
        path = self.path
        return LazyValue(lambda: DatabaseManager.salt_from_path(path))

    # This is static so as there is no need to carry around a
    # DatabaseManager object in another thread
    @staticmethod
    def salt_from_path(path: str) -> bytes:
        db = PyKeePass(path, None, None, decrypt=False)
        return db.database_salt