From c50c7c94135655a4fbe52365f29eae0f20600bb3 Mon Sep 17 00:00:00 2001 From: "Antonio J. Delgado" Date: Thu, 28 Nov 2024 11:35:02 +0200 Subject: [PATCH] Handle issue when encryption password for local cache is missing --- nc_password_client/nc_password_client.py | 48 ++++++++++++++++++------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/nc_password_client/nc_password_client.py b/nc_password_client/nc_password_client.py index 7fe3c78..2f177e9 100755 --- a/nc_password_client/nc_password_client.py +++ b/nc_password_client/nc_password_client.py @@ -24,6 +24,7 @@ import click import click_config_file import passpy import secretstorage +import cryptography.fernet from cryptography.fernet import Fernet from yaml import dump try: @@ -128,7 +129,7 @@ class NextcloudHandler: self.field_replacements[key] = value self.debug( { - "action": "Initializing Netcloud handler", + "action": "Initializing Nextcloud handler", "field_replacements": self.field_replacements } ) @@ -229,9 +230,18 @@ class NextcloudHandler: collection = secretstorage.get_default_collection(connection) if collection.is_locked(): collection.unlock() - for item in collection.get_all_items(): - if item.get_label() == 'nc_password_client': - self.encryption_pass = item.get_secret() + try: + for item in collection.get_all_items(): + if item.get_label() == 'nc_password_client': + self.encryption_pass = item.get_secret() + except secretstorage.exceptions.ItemNotFoundException as error: + self.error( + { + "action": "_get_encryption_pass_from_keyring", + "message": "Item not found browsing keyring items", + "error": error + } + ) if self.encryption_pass is None: self.debug( { @@ -245,10 +255,11 @@ class NextcloudHandler: } item = collection.create_item('nc_password_client', attributes, self.encryption_pass) else: + print(self.encryption_pass) self.debug( { "action": "_get_encryption_pass_from_keyring", - "message": "Encryption password obtained from keyring" + "message": "Encryption password obtained from keyring", } ) @@ -264,14 +275,27 @@ class NextcloudHandler: content = cache_file.read() if len(content) != 0: cipher_suite = Fernet(self.encryption_pass) - self.cache = json.loads(cipher_suite.decrypt(content)) - self.debug( - { - "action": "_read_cache", - "last_update": self.cache['last_update'], - "total_cached_password": len(self.cache['cached_passwords']) + try: + self.cache = json.loads(cipher_suite.decrypt(content)) + self.debug( + { + "action": "_read_cache", + "last_update": self.cache['last_update'], + "total_cached_password": len(self.cache['cached_passwords']) + } + ) + except cryptography.fernet.InvalidToken as error: + self.debug( + { + "action": "_read_cache", + "message": "Fernet token for passwords local cache is invalid, discarding the local cache.", + } + ) + self.cache = { + "last_update": -1, + "cached_passwords": [] } - ) + else: self.debug( {