cq: Format with black and isort
This commit is contained in:
@@ -16,15 +16,14 @@
|
||||
|
||||
import logging
|
||||
|
||||
from nbxmpp.protocol import JID
|
||||
|
||||
import gpg
|
||||
from gpg.results import ImportResult
|
||||
from nbxmpp.protocol import JID
|
||||
|
||||
from openpgp.backend.util import parse_uid
|
||||
from openpgp.modules.util import DecryptionFailed
|
||||
|
||||
log = logging.getLogger('gajim.p.openpgp.gpgme')
|
||||
log = logging.getLogger("gajim.p.openpgp.gpgme")
|
||||
|
||||
|
||||
class KeyringItem:
|
||||
@@ -73,31 +72,33 @@ class GPGME:
|
||||
def __init__(self, jid, gnuhome):
|
||||
self._jid = jid
|
||||
self._context_args = {
|
||||
'home_dir': str(gnuhome),
|
||||
'offline': True,
|
||||
'armor': False,
|
||||
"home_dir": str(gnuhome),
|
||||
"offline": True,
|
||||
"armor": False,
|
||||
}
|
||||
|
||||
def generate_key(self):
|
||||
with gpg.Context(**self._context_args) as context:
|
||||
result = context.create_key(f'xmpp:{str(self._jid)}',
|
||||
algorithm='default',
|
||||
expires=False,
|
||||
passphrase=None,
|
||||
force=False)
|
||||
result = context.create_key(
|
||||
f"xmpp:{str(self._jid)}",
|
||||
algorithm="default",
|
||||
expires=False,
|
||||
passphrase=None,
|
||||
force=False,
|
||||
)
|
||||
|
||||
log.info('Generated new key: %s', result.fpr)
|
||||
log.info("Generated new key: %s", result.fpr)
|
||||
|
||||
def get_key(self, fingerprint):
|
||||
with gpg.Context(**self._context_args) as context:
|
||||
try:
|
||||
key = context.get_key(fingerprint)
|
||||
except gpg.errors.KeyNotFound as error:
|
||||
log.warning('key not found: %s', error.keystr)
|
||||
log.warning("key not found: %s", error.keystr)
|
||||
return
|
||||
|
||||
except Exception as error:
|
||||
log.warning('get_key() error: %s', error)
|
||||
log.warning("get_key() error: %s", error)
|
||||
return
|
||||
|
||||
return key
|
||||
@@ -121,7 +122,7 @@ class GPGME:
|
||||
for key in context.keylist():
|
||||
keyring_item = KeyringItem(key)
|
||||
if not keyring_item.is_xmpp_key:
|
||||
log.warning('Key not suited for xmpp: %s', key.fpr)
|
||||
log.warning("Key not suited for xmpp: %s", key.fpr)
|
||||
self.delete_key(keyring_item.fingerprint)
|
||||
continue
|
||||
|
||||
@@ -157,12 +158,12 @@ class GPGME:
|
||||
recipients.append(key)
|
||||
|
||||
if not recipients:
|
||||
return None, 'No keys found to encrypt to'
|
||||
return None, "No keys found to encrypt to"
|
||||
|
||||
with gpg.Context(**self._context_args) as context:
|
||||
result = context.encrypt(str(plaintext).encode(),
|
||||
recipients,
|
||||
always_trust=True)
|
||||
result = context.encrypt(
|
||||
str(plaintext).encode(), recipients, always_trust=True
|
||||
)
|
||||
|
||||
ciphertext, result, _sign_result = result
|
||||
return ciphertext, None
|
||||
@@ -172,7 +173,7 @@ class GPGME:
|
||||
try:
|
||||
result = context.decrypt(ciphertext)
|
||||
except Exception as error:
|
||||
raise DecryptionFailed('Decryption failed: %s' % error)
|
||||
raise DecryptionFailed("Decryption failed: %s" % error)
|
||||
|
||||
plaintext, result, verify_result = result
|
||||
plaintext = plaintext.decode()
|
||||
@@ -181,16 +182,16 @@ class GPGME:
|
||||
if not fingerprints or len(fingerprints) > 1:
|
||||
log.error(result)
|
||||
log.error(verify_result)
|
||||
raise DecryptionFailed('Verification failed')
|
||||
raise DecryptionFailed("Verification failed")
|
||||
|
||||
return plaintext, fingerprints[0]
|
||||
|
||||
def import_key(self, data, jid):
|
||||
log.info('Import key from %s', jid)
|
||||
log.info("Import key from %s", jid)
|
||||
with gpg.Context(**self._context_args) as context:
|
||||
result = context.key_import(data)
|
||||
if not isinstance(result, ImportResult) or result.imported != 1:
|
||||
log.error('Key import failed: %s', jid)
|
||||
log.error("Key import failed: %s", jid)
|
||||
log.error(result)
|
||||
return
|
||||
|
||||
@@ -198,7 +199,7 @@ class GPGME:
|
||||
key = self.get_key(fingerprint)
|
||||
item = KeyringItem(key)
|
||||
if not item.is_valid(jid):
|
||||
log.warning('Invalid key found')
|
||||
log.warning("Invalid key found")
|
||||
log.warning(key)
|
||||
self.delete_key(item.fingerprint)
|
||||
return
|
||||
@@ -206,7 +207,7 @@ class GPGME:
|
||||
return item
|
||||
|
||||
def delete_key(self, fingerprint):
|
||||
log.info('Delete Key: %s', fingerprint)
|
||||
log.info("Delete Key: %s", fingerprint)
|
||||
key = self.get_key(fingerprint)
|
||||
with gpg.Context(**self._context_args) as context:
|
||||
context.op_delete(key, True)
|
||||
|
||||
@@ -23,10 +23,9 @@ from nbxmpp.protocol import JID
|
||||
from openpgp.backend.util import parse_uid
|
||||
from openpgp.modules.util import DecryptionFailed
|
||||
|
||||
|
||||
log = logging.getLogger('gajim.p.openpgp.pygnupg')
|
||||
log = logging.getLogger("gajim.p.openpgp.pygnupg")
|
||||
if log.getEffectiveLevel() == logging.DEBUG:
|
||||
log = logging.getLogger('gnupg')
|
||||
log = logging.getLogger("gnupg")
|
||||
log.addHandler(logging.StreamHandler())
|
||||
log.setLevel(logging.DEBUG)
|
||||
|
||||
@@ -50,10 +49,10 @@ class KeyringItem:
|
||||
|
||||
@property
|
||||
def keyid(self) -> str:
|
||||
return self._key['keyid']
|
||||
return self._key["keyid"]
|
||||
|
||||
def _get_uid(self) -> str | None:
|
||||
for uid in self._key['uids']:
|
||||
for uid in self._key["uids"]:
|
||||
try:
|
||||
return parse_uid(uid)
|
||||
except Exception:
|
||||
@@ -61,7 +60,7 @@ class KeyringItem:
|
||||
|
||||
@property
|
||||
def fingerprint(self):
|
||||
return self._key['fingerprint']
|
||||
return self._key["fingerprint"]
|
||||
|
||||
@property
|
||||
def uid(self):
|
||||
@@ -79,28 +78,28 @@ class KeyringItem:
|
||||
|
||||
class PythonGnuPG(gnupg.GPG):
|
||||
def __init__(self, jid: str, gnupghome: Path) -> None:
|
||||
gnupg.GPG.__init__(self, gpgbinary='gpg', gnupghome=str(gnupghome))
|
||||
gnupg.GPG.__init__(self, gpgbinary="gpg", gnupghome=str(gnupghome))
|
||||
|
||||
self._jid = jid
|
||||
self._own_fingerprint = None
|
||||
|
||||
@staticmethod
|
||||
def _get_key_params(jid):
|
||||
'''
|
||||
"""
|
||||
Generate --gen-key input
|
||||
'''
|
||||
"""
|
||||
|
||||
params = {
|
||||
'Key-Type': 'RSA',
|
||||
'Key-Length': 2048,
|
||||
'Name-Real': 'xmpp:%s' % jid,
|
||||
"Key-Type": "RSA",
|
||||
"Key-Length": 2048,
|
||||
"Name-Real": "xmpp:%s" % jid,
|
||||
}
|
||||
|
||||
out = 'Key-Type: %s\n' % params.pop('Key-Type')
|
||||
out = "Key-Type: %s\n" % params.pop("Key-Type")
|
||||
for key, val in list(params.items()):
|
||||
out += '%s: %s\n' % (key, val)
|
||||
out += '%no-protection\n'
|
||||
out += '%commit\n'
|
||||
out += "%s: %s\n" % (key, val)
|
||||
out += "%no-protection\n"
|
||||
out += "%commit\n"
|
||||
return out
|
||||
|
||||
def generate_key(self):
|
||||
@@ -108,18 +107,20 @@ class PythonGnuPG(gnupg.GPG):
|
||||
|
||||
def encrypt(self, payload, keys):
|
||||
recipients = [key.fingerprint for key in keys]
|
||||
log.info('encrypt to:')
|
||||
log.info("encrypt to:")
|
||||
for fingerprint in recipients:
|
||||
log.info(fingerprint)
|
||||
|
||||
result = super().encrypt(str(payload).encode('utf8'),
|
||||
recipients,
|
||||
armor=False,
|
||||
sign=self._own_fingerprint,
|
||||
always_trust=True)
|
||||
result = super().encrypt(
|
||||
str(payload).encode("utf8"),
|
||||
recipients,
|
||||
armor=False,
|
||||
sign=self._own_fingerprint,
|
||||
always_trust=True,
|
||||
)
|
||||
|
||||
if result.ok:
|
||||
error = ''
|
||||
error = ""
|
||||
else:
|
||||
error = result.status
|
||||
|
||||
@@ -130,7 +131,7 @@ class PythonGnuPG(gnupg.GPG):
|
||||
if not result.ok:
|
||||
raise DecryptionFailed(result.status)
|
||||
|
||||
return result.data.decode('utf8'), result.fingerprint
|
||||
return result.data.decode("utf8"), result.fingerprint
|
||||
|
||||
def get_key(self, fingerprint):
|
||||
return super().list_keys(keys=[fingerprint])
|
||||
@@ -141,7 +142,7 @@ class PythonGnuPG(gnupg.GPG):
|
||||
for key in result:
|
||||
item = KeyringItem(key)
|
||||
if not item.is_xmpp_key:
|
||||
log.warning('Invalid key found, deleting key')
|
||||
log.warning("Invalid key found, deleting key")
|
||||
log.warning(key)
|
||||
self.delete_key(item.fingerprint)
|
||||
continue
|
||||
@@ -149,17 +150,17 @@ class PythonGnuPG(gnupg.GPG):
|
||||
return keys
|
||||
|
||||
def import_key(self, data, jid):
|
||||
log.info('Import key from %s', jid)
|
||||
log.info("Import key from %s", jid)
|
||||
result = super().import_keys(data)
|
||||
if not result:
|
||||
log.error('Could not import key')
|
||||
log.error("Could not import key")
|
||||
log.error(result)
|
||||
return
|
||||
|
||||
key = self.get_key(result.results[0]['fingerprint'])
|
||||
key = self.get_key(result.results[0]["fingerprint"])
|
||||
item = KeyringItem(key[0])
|
||||
if not item.is_valid(jid):
|
||||
log.warning('Invalid key found, deleting key')
|
||||
log.warning("Invalid key found, deleting key")
|
||||
log.warning(key)
|
||||
self.delete_key(item.fingerprint)
|
||||
return
|
||||
@@ -172,17 +173,16 @@ class PythonGnuPG(gnupg.GPG):
|
||||
return None, None
|
||||
|
||||
if len(result) > 1:
|
||||
log.error('More than one secret key found')
|
||||
log.error("More than one secret key found")
|
||||
return None, None
|
||||
|
||||
self._own_fingerprint = result[0]['fingerprint']
|
||||
return self._own_fingerprint, int(result[0]['date'])
|
||||
self._own_fingerprint = result[0]["fingerprint"]
|
||||
return self._own_fingerprint, int(result[0]["date"])
|
||||
|
||||
def export_key(self, fingerprint):
|
||||
key = super().export_keys(
|
||||
fingerprint, secret=False, armor=False, minimal=True)
|
||||
key = super().export_keys(fingerprint, secret=False, armor=False, minimal=True)
|
||||
return key
|
||||
|
||||
def delete_key(self, fingerprint):
|
||||
log.info('Delete Key: %s', fingerprint)
|
||||
log.info("Delete Key: %s", fingerprint)
|
||||
super().delete_keys(fingerprint)
|
||||
|
||||
@@ -14,13 +14,13 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with OpenPGP Gajim Plugin. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import sqlite3
|
||||
import logging
|
||||
import sqlite3
|
||||
from collections import namedtuple
|
||||
|
||||
log = logging.getLogger('gajim.p.openpgp.sql')
|
||||
log = logging.getLogger("gajim.p.openpgp.sql")
|
||||
|
||||
TABLE_LAYOUT = '''
|
||||
TABLE_LAYOUT = """
|
||||
CREATE TABLE contacts (
|
||||
jid TEXT,
|
||||
fingerprint TEXT,
|
||||
@@ -29,13 +29,14 @@ TABLE_LAYOUT = '''
|
||||
timestamp INTEGER,
|
||||
comment TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX jid_fingerprint ON contacts (jid, fingerprint);'''
|
||||
CREATE UNIQUE INDEX jid_fingerprint ON contacts (jid, fingerprint);"""
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, folder_path):
|
||||
self._con = sqlite3.connect(str(folder_path / 'contacts.db'),
|
||||
detect_types=sqlite3.PARSE_COLNAMES)
|
||||
self._con = sqlite3.connect(
|
||||
str(folder_path / "contacts.db"), detect_types=sqlite3.PARSE_COLNAMES
|
||||
)
|
||||
|
||||
self._con.row_factory = self._namedtuple_factory
|
||||
self._create_database()
|
||||
@@ -51,11 +52,11 @@ class Storage:
|
||||
return named_row
|
||||
|
||||
def _user_version(self):
|
||||
return self._con.execute('PRAGMA user_version').fetchone()[0]
|
||||
return self._con.execute("PRAGMA user_version").fetchone()[0]
|
||||
|
||||
def _create_database(self):
|
||||
if not self._user_version():
|
||||
log.info('Create contacts.db')
|
||||
log.info("Create contacts.db")
|
||||
self._execute_query(TABLE_LAYOUT)
|
||||
|
||||
def _execute_query(self, query):
|
||||
@@ -64,41 +65,43 @@ class Storage:
|
||||
%s
|
||||
PRAGMA user_version=1;
|
||||
END TRANSACTION;
|
||||
""" % (query)
|
||||
""" % (
|
||||
query
|
||||
)
|
||||
self._con.executescript(transaction)
|
||||
|
||||
def _migrate_database(self):
|
||||
pass
|
||||
|
||||
def load_contacts(self):
|
||||
sql = '''SELECT jid as "jid [jid]",
|
||||
sql = """SELECT jid as "jid [jid]",
|
||||
fingerprint,
|
||||
active,
|
||||
trust,
|
||||
timestamp,
|
||||
comment
|
||||
FROM contacts'''
|
||||
FROM contacts"""
|
||||
|
||||
return self._con.execute(sql).fetchall()
|
||||
|
||||
def save_contact(self, db_values):
|
||||
sql = '''REPLACE INTO
|
||||
sql = """REPLACE INTO
|
||||
contacts(jid, fingerprint, active, trust, timestamp, comment)
|
||||
VALUES(?, ?, ?, ?, ?, ?)'''
|
||||
VALUES(?, ?, ?, ?, ?, ?)"""
|
||||
for values in db_values:
|
||||
log.info('Store key: %s', values)
|
||||
log.info("Store key: %s", values)
|
||||
self._con.execute(sql, values)
|
||||
self._con.commit()
|
||||
|
||||
def set_trust(self, jid, fingerprint, trust):
|
||||
sql = 'UPDATE contacts SET trust = ? WHERE jid = ? AND fingerprint = ?'
|
||||
log.info('Set Trust: %s %s %s', trust, jid, fingerprint)
|
||||
sql = "UPDATE contacts SET trust = ? WHERE jid = ? AND fingerprint = ?"
|
||||
log.info("Set Trust: %s %s %s", trust, jid, fingerprint)
|
||||
self._con.execute(sql, (trust, jid, fingerprint))
|
||||
self._con.commit()
|
||||
|
||||
def delete_key(self, jid, fingerprint):
|
||||
sql = 'DELETE from contacts WHERE jid = ? AND fingerprint = ?'
|
||||
log.info('Delete Key: %s %s', jid, fingerprint)
|
||||
sql = "DELETE from contacts WHERE jid = ? AND fingerprint = ?"
|
||||
log.info("Delete Key: %s %s", jid, fingerprint)
|
||||
self._con.execute(sql, (jid, fingerprint))
|
||||
self._con.commit()
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def parse_uid(uid: str, compat=False) -> str:
|
||||
if uid.startswith('xmpp:'):
|
||||
if uid.startswith("xmpp:"):
|
||||
return uid[5:]
|
||||
|
||||
# Compat with uids of form "Name <xmpp:my@jid.com>"
|
||||
if compat and '<xmpp:' in uid and uid.endswith('>'):
|
||||
return uid[:-1].split('<xmpp:', maxsplit=1)[1]
|
||||
if compat and "<xmpp:" in uid and uid.endswith(">"):
|
||||
return uid[:-1].split("<xmpp:", maxsplit=1)[1]
|
||||
|
||||
raise ValueError('Uknown UID format: %s' % uid)
|
||||
raise ValueError("Uknown UID format: %s" % uid)
|
||||
|
||||
Reference in New Issue
Block a user