plugin XEP-0384: Fully reworked to adjust to the reworked python-omemo:

- support for both (modern) OMEMO under the `urn:xmpp:omemo:2` namespace and (legacy) OMEMO under the `eu.siacs.conversations.axolotl` namespace
- maintains one identity across both versions of OMEMO
- migrates data from the old plugin
- includes more features for protocol stability
- uses SCE for modern OMEMO
- fully type-checked, linted and format-checked
- added type hints to various pieces of backend code used by the plugin
- added stubs for some Twisted APIs used by the plugin under stubs/ (use `export MYPYPATH=stubs/` before running mypy)
- core (xmpp): enabled `send` trigger and made it an asyncPoint

fix 375
This commit is contained in:
Syndace 2022-08-23 21:06:24 +02:00
commit 75ae8160ae
5 changed files with 2202 additions and 1414 deletions

View file

@ -22,6 +22,7 @@ try:
except ImportError:
BaseDirectory = None
from os.path import dirname
from typing_extensions import Final
import sat
@ -126,7 +127,7 @@ class Const(object):
EXTRA_INFO_ENCR_ERR = "ENCRYPTION_ERROR"
# encryption is a key for plugins
MESS_KEY_ENCRYPTION = "ENCRYPTION"
MESS_KEY_ENCRYPTION: Final = "ENCRYPTION"
# encrypted is a key for frontends
MESS_KEY_ENCRYPTED = "encrypted"
MESS_KEY_TRUSTED = "trusted"
@ -431,7 +432,7 @@ class Const(object):
return value.lower() in (cls.BOOL_TRUE, "1", "yes", "on")
@classmethod
def boolConst(cls, value):
def boolConst(cls, value: bool) -> str:
"""@return (str): constant associated to bool value"""
assert isinstance(value, bool)
return cls.BOOL_TRUE if value else cls.BOOL_FALSE

View file

@ -16,10 +16,47 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from collections import namedtuple
from typing import Dict
from typing_extensions import TypedDict
from twisted.words.protocols.jabber import jid as t_jid
from twisted.words.xish import domish
class SatXMPPEntity:
jid: t_jid.JID
is_component: bool
EncryptionPlugin = namedtuple("EncryptionPlugin", ("instance",
"name",
"namespace",
"priority",
"directed"))
class EncryptionSession(TypedDict):
plugin: EncryptionPlugin
# Incomplete types built through observation rather than code inspection.
MessageDataExtra = TypedDict(
"MessageDataExtra",
{ "encrypted": bool, "origin_id": str },
total=False
)
MessageData = TypedDict("MessageData", {
"from": t_jid.JID,
"to": t_jid.JID,
"uid": str,
"message": Dict[str, str],
"subject": Dict[str, str],
"type": str,
"timestamp": float,
"extra": MessageDataExtra,
"ENCRYPTION": EncryptionSession,
"xml": domish.Element
}, total=False)

View file

@ -21,6 +21,14 @@
# XXX: this module use standard logging module when possible, but as SàT can work in different cases where logging is not the best choice (twisted, pyjamas, etc), it is necessary to have a dedicated module. Additional feature like environment variables and colors are also managed.
# TODO: change formatting from "%s" style to "{}" when moved to Python 3
from typing import TYPE_CHECKING, Any, Optional
from typing_extensions import TypedDict
if TYPE_CHECKING:
from logging import _ExcInfoType
else:
_ExcInfoType = Any
from sat.core.constants import Const as C
from sat.tools.common.ansi import ANSI as A
from sat.core import exceptions
@ -37,6 +45,10 @@ class Filtered(Exception):
pass
class KWArgs(TypedDict):
exc_info: _ExcInfoType
class Logger:
"""High level logging class"""
fmt = None # format option as given by user (e.g. SAT_LOG_LOGGER)
@ -60,7 +72,7 @@ class Logger:
tb = traceback.format_exc()
return message + "\n==== traceback ====\n" + tb
def out(self, message, level=None, **kwargs):
def out(self, message: object, level: Optional[str] = None, **kwargs: KWArgs) -> None:
"""Actually log the message
@param message: formatted message
@ -69,7 +81,7 @@ class Logger:
message = self.addTraceback(message)
print(message)
def log(self, level, message, **kwargs):
def log(self, level: str, message: object, **kwargs: KWArgs) -> None:
"""Print message
@param level: one of C.LOG_LEVELS
@ -84,7 +96,7 @@ class Logger:
except Filtered:
pass
def format(self, level, message):
def format(self, level: str, message: object) -> object:
"""Format message according to Logger.fmt
@param level: one of C.LOG_LEVELS
@ -117,19 +129,19 @@ class Logger:
else:
raise e
def debug(self, msg, **kwargs):
def debug(self, msg: object, **kwargs: KWArgs) -> None:
self.log(C.LOG_LVL_DEBUG, msg, **kwargs)
def info(self, msg, **kwargs):
def info(self, msg: object, **kwargs: KWArgs) -> None:
self.log(C.LOG_LVL_INFO, msg, **kwargs)
def warning(self, msg, **kwargs):
def warning(self, msg: object, **kwargs: KWArgs) -> None:
self.log(C.LOG_LVL_WARNING, msg, **kwargs)
def error(self, msg, **kwargs):
def error(self, msg: object, **kwargs: KWArgs) -> None:
self.log(C.LOG_LVL_ERROR, msg, **kwargs)
def critical(self, msg, **kwargs):
def critical(self, msg: object, **kwargs: KWArgs) -> None:
self.log(C.LOG_LVL_CRITICAL, msg, **kwargs)

View file

@ -634,10 +634,10 @@ class SAT(service.Service):
return (None, None)
return (self.profiles[profile].jid, self.profiles[profile].xmlstream)
def getClient(self, profile_key):
def getClient(self, profile_key: str) -> xmpp.SatXMPPClient:
"""Convenient method to get client from profile key
@return: client or None if it doesn't exist
@return: the client
@raise exceptions.ProfileKeyUnknown: the profile or profile key doesn't exist
@raise exceptions.NotFound: client is not available
This happen if profile has not been used yet

View file

@ -550,10 +550,14 @@ class SatXMPPEntity(core_types.SatXMPPEntity):
).toResponse(iq_elt)
self.xmlstream.send(iq_error_elt)
def generateMessageXML(self, data, post_xml_treatments=None):
def generateMessageXML(
self,
data: core_types.MessageData,
post_xml_treatments: Optional[defer.Deferred] = None
) -> core_types.MessageData:
"""Generate <message/> stanza from message data
@param data(dict): message data
@param data: message data
domish element will be put in data['xml']
following keys are needed:
- from
@ -563,9 +567,9 @@ class SatXMPPEntity(core_types.SatXMPPEntity):
- type
- subject
- extra
@param post_xml_treatments(Deferred): a Deferred which will be called with data
once XML is generated
@return (dict) message data
@param post_xml_treatments: a Deferred which will be called with data once XML is
generated
@return: message data
"""
data["xml"] = message_elt = domish.Element((None, "message"))
message_elt["to"] = data["to"].full()
@ -612,7 +616,7 @@ class SatXMPPEntity(core_types.SatXMPPEntity):
"""
raise NotImplementedError
def send(self, obj):
async def send(self, obj):
# original send method accept string
# but we restrict to domish.Element to make trigger treatments easier
assert isinstance(obj, domish.Element)
@ -622,14 +626,11 @@ class SatXMPPEntity(core_types.SatXMPPEntity):
# (out of band transmission for instance).
# e2e should have a priority of 0 here, and out of band transmission
# a lower priority
#  FIXME: trigger not used yet, can be uncommented when e2e full stanza
# encryption is implemented
#  if not self.host_app.trigger.point("send", self, obj):
#   return
if not (await self.host_app.trigger.asyncPoint("send", self, obj)):
return
super().send(obj)
@defer.inlineCallbacks
def sendMessageData(self, mess_data):
async def sendMessageData(self, mess_data):
"""Convenient method to send message data to stream
This method will send mess_data[u'xml'] to stream, but a trigger is there
@ -644,10 +645,10 @@ class SatXMPPEntity(core_types.SatXMPPEntity):
# This is intented for e2e encryption which doesn't do full stanza
# encryption (e.g. OTR)
# This trigger point can't cancel the method
yield self.host_app.trigger.asyncPoint("sendMessageData", self, mess_data,
await self.host_app.trigger.asyncPoint("sendMessageData", self, mess_data,
triggers_no_cancel=True)
self.send(mess_data["xml"])
defer.returnValue(mess_data)
await self.send(mess_data["xml"])
return mess_data
def sendMessage(
self, to_jid, message, subject=None, mess_type="auto", extra=None, uid=None,
@ -824,6 +825,9 @@ class SatXMPPEntity(core_types.SatXMPPEntity):
return ClientPluginWrapper(self, plugin_name, missing)
ExtraDict = dict # TODO
@implementer(iwokkel.IDisco)
class SatXMPPClient(SatXMPPEntity, wokkel_client.XMPPClient):
trigger_suffix = ""
@ -930,15 +934,20 @@ class SatXMPPClient(SatXMPPEntity, wokkel_client.XMPPClient):
)
post_xml_treatments.addCallback(self.messageSendToBridge)
def feedback(self, to_jid, message, extra=None):
def feedback(
self,
to_jid: jid.JID,
message: str,
extra: Optional[ExtraDict] = None
) -> None:
"""Send message to frontends
This message will be an info message, not recorded in history.
It can be used to give feedback of a command
@param to_jid(jid.JID): destinee jid
@param message(unicode): message to send to frontends
@param extra(None, dict): extra data to use
in particular, info subtype can be specified with MESS_EXTRA_INFO
@param to_jid: destinee jid
@param message: message to send to frontends
@param extra: extra data to use in particular, info subtype can be specified with
MESS_EXTRA_INFO
"""
if extra is None:
extra = {}