Reformatted code base using black.

This commit is contained in:
Goffi 2024-06-19 18:44:57 +02:00
commit 53fdaa9d09

View file

@ -53,14 +53,24 @@ PLUGIN_INFO = {
C.PI_TYPE: C.PLUG_TYPE_EXP,
C.PI_PROTOCOLS: ["XEP-0448"],
C.PI_DEPENDENCIES: [
"XEP-0103", "XEP-0300", "XEP-0334", "XEP-0363", "XEP-0384", "XEP-0447",
"DOWNLOAD", "ATTACH"
"XEP-0103",
"XEP-0300",
"XEP-0334",
"XEP-0363",
"XEP-0384",
"XEP-0447",
"DOWNLOAD",
"ATTACH",
],
C.PI_MAIN: "XEP_0448",
C.PI_HANDLER: "yes",
C.PI_DESCRIPTION: dedent(_("""\
C.PI_DESCRIPTION: dedent(
_(
"""\
Implementation of e2e encryption for media sharing
""")),
"""
)
),
}
NS_ESFS = "urn:xmpp:esfs:0"
@ -137,7 +147,7 @@ class XEP_0448:
attachment: Dict[str, Any],
source: Dict[str, Any],
dest_path: Union[Path, str],
extra: Optional[Dict[str, Any]] = None
extra: Optional[Dict[str, Any]] = None,
) -> Tuple[str, defer.Deferred]:
# TODO: check hash
if extra is None:
@ -154,10 +164,8 @@ class XEP_0448:
except KeyError:
raise ValueError(f"{source} has missing URL")
if extra.get('ignore_tls_errors', False):
log.warning(
"TLS certificate check disabled, this is highly insecure"
)
if extra.get("ignore_tls_errors", False):
log.warning("TLS certificate check disabled, this is highly insecure")
treq_client = treq_client_no_ssl
else:
treq_client = treq
@ -166,7 +174,7 @@ class XEP_0448:
file_size = int(attachment["size"])
except (KeyError, ValueError):
head_data = await treq_client.head(download_url)
content_length = int(head_data.headers.getRawHeaders('content-length')[0])
content_length = int(head_data.headers.getRawHeaders("content-length")[0])
# the 128 bits tag is put at the end
file_size = content_length - 16
@ -175,7 +183,7 @@ class XEP_0448:
client,
dest_path,
mode="wb",
size = file_size,
size=file_size,
)
if cipher in (NS_AES_128_GCM, NS_AES_256_GCM):
@ -204,13 +212,13 @@ class XEP_0448:
client=client,
file_obj=file_obj,
decryptor=decryptor,
unpadder=unpadder
unpadder=unpadder,
)
finalize_cb = partial(
self.cbc_decrypt_finalize,
file_obj=file_obj,
decryptor=decryptor,
unpadder=unpadder
unpadder=unpadder,
)
else:
msg = f"cipher {cipher!r} is not supported"
@ -253,10 +261,7 @@ class XEP_0448:
}
attachment["filename"] = filename
return await self._http_upload.file_http_upload(
client=client,
filepath=filepath,
filename="encrypted",
extra=extra
client=client, filepath=filepath, filename="encrypted", extra=extra
)
async def attach(self, client, data):
@ -264,7 +269,7 @@ class XEP_0448:
# we need to send each file in a separate message, in the same way as for
# plugin_sec_aesgcm.
attachments = data["extra"][C.KEY_ATTACHMENTS]
if not data['message'] or data['message'] == {'': ''}:
if not data["message"] or data["message"] == {"": ""}:
extra_attachments = attachments[1:]
del attachments[1:]
else:
@ -287,24 +292,23 @@ class XEP_0448:
[],
name=attachment["filename"],
size=attachment["size"],
file_hash=file_hash
file_hash=file_hash,
)
encrypted_elt = file_sharing_elt.sources.addElement(
(NS_ESFS, "encrypted")
)
encrypted_elt["cipher"] = NS_AES_256_GCM
encrypted_elt.addElement(
"key",
content=base64.b64encode(encryption_data["key"]).decode()
"key", content=base64.b64encode(encryption_data["key"]).decode()
)
encrypted_elt.addElement(
"iv",
content=base64.b64encode(encryption_data["iv"]).decode()
"iv", content=base64.b64encode(encryption_data["iv"]).decode()
)
encrypted_elt.addChild(
self._h.build_hash_elt(
attachment["encrypted_hash"], attachment["encrypted_hash_algo"]
)
)
encrypted_elt.addChild(self._h.build_hash_elt(
attachment["encrypted_hash"],
attachment["encrypted_hash_algo"]
))
encrypted_elt.addChild(
self._sfs.get_sources_elt(
[self._u.get_url_data_elt(attachment["url"])]
@ -315,16 +319,18 @@ class XEP_0448:
for attachment in extra_attachments:
# we send all remaining attachment in a separate message
await client.sendMessage(
to_jid=data['to'],
message={'': ''},
subject=data['subject'],
mess_type=data['type'],
to_jid=data["to"],
message={"": ""},
subject=data["subject"],
mess_type=data["type"],
extra={C.KEY_ATTACHMENTS: [attachment]},
)
if ((not data['extra']
and (not data['message'] or data['message'] == {'': ''})
and not data['subject'])):
if (
not data["extra"]
and (not data["message"] or data["message"] == {"": ""})
and not data["subject"]
):
# nothing left to send, we can cancel the message
raise exceptions.CancelError("Cancelled by XEP_0448 attachment handling")
@ -333,7 +339,7 @@ class XEP_0448:
data: bytes,
client: SatXMPPEntity,
file_obj: stream.SatFile,
decryptor: CipherContext
decryptor: CipherContext,
) -> None:
if file_obj.tell() + len(data) > file_obj.size: # type: ignore
# we're reaching end of file with this bunch of data
@ -371,16 +377,13 @@ class XEP_0448:
client: SatXMPPEntity,
file_obj: stream.SatFile,
decryptor: CipherContext,
unpadder: PaddingContext
unpadder: PaddingContext,
) -> None:
decrypted = decryptor.update(data)
file_obj.write(unpadder.update(decrypted))
def cbc_decrypt_finalize(
self,
file_obj: stream.SatFile,
decryptor: CipherContext,
unpadder: PaddingContext
self, file_obj: stream.SatFile, decryptor: CipherContext, unpadder: PaddingContext
) -> None:
decrypted = decryptor.finalize()
file_obj.write(unpadder.update(decrypted))
@ -388,7 +391,7 @@ class XEP_0448:
file_obj.close()
def _upload_pre_slot(self, client, extra, file_metadata):
if extra.get('encryption') != IMPORT_NAME:
if extra.get("encryption") != IMPORT_NAME:
return True
# the tag is appended to the file
file_metadata["size"] += 16
@ -414,10 +417,10 @@ class XEP_0448:
return ret
except AlreadyFinalized:
# as we have already finalized, we can now send EOF
return b''
return b""
def _upload_trigger(self, client, extra, sat_file, file_producer, slot):
if extra.get('encryption') != IMPORT_NAME:
if extra.get("encryption") != IMPORT_NAME:
return True
attachment = extra["attachment"]
encryption_data = extra["encryption_data"]
@ -442,14 +445,17 @@ class XEP_0448:
if sat_file.data_cb is not None:
raise exceptions.InternalError(
f"data_cb was expected to be None, it is set to {sat_file.data_cb}")
f"data_cb was expected to be None, it is set to {sat_file.data_cb}"
)
attachment.update({
"hash_algo": self._h.ALGO_DEFAULT,
"hasher": self._h.get_hasher(),
"encrypted_hash_algo": self._h.ALGO_DEFAULT,
"encrypted_hasher": self._h.get_hasher(),
})
attachment.update(
{
"hash_algo": self._h.ALGO_DEFAULT,
"hasher": self._h.get_hasher(),
"encrypted_hash_algo": self._h.ALGO_DEFAULT,
"encrypted_hasher": self._h.get_hasher(),
}
)
# with data_cb we encrypt the file on the fly
sat_file.data_cb = partial(