├── .flake8 ├── .github └── workflows │ └── test-and-publish.yml ├── .gitignore ├── .readthedocs.yaml ├── CHANGELOG.md ├── Exceptions.drawio ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── _static │ └── .gitkeep ├── conf.py ├── getting_started.rst ├── index.rst ├── installation.rst ├── make.bat ├── migration_from_legacy.rst ├── omemo │ ├── backend.rst │ ├── bundle.rst │ ├── identity_key_pair.rst │ ├── message.rst │ ├── package.rst │ ├── session.rst │ ├── session_manager.rst │ ├── storage.rst │ └── types.rst └── requirements.txt ├── examples ├── README.md └── btbv_session_manager.py ├── functionality.md ├── omemo ├── __init__.py ├── backend.py ├── bundle.py ├── identity_key_pair.py ├── message.py ├── project.py ├── py.typed ├── session.py ├── session_manager.py ├── storage.py ├── types.py └── version.py ├── pylintrc ├── pyproject.toml ├── requirements.txt ├── setup.py └── tests ├── LICENSE ├── __init__.py ├── data.py ├── in_memory_storage.py ├── migration.py ├── session_manager_impl.py └── test_session_manager.py /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | 3 | max-line-length = 110 4 | doctests = True 5 | ignore = E201,E202,W503 6 | per-file-ignores = 7 | omemo/project.py:E203 8 | omemo/__init__.py:F401 9 | -------------------------------------------------------------------------------- /.github/workflows/test-and-publish.yml: -------------------------------------------------------------------------------- 1 | name: Test & Publish 2 | 3 | on: [push, pull_request] 4 | 5 | permissions: 6 | contents: read 7 | 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "pypy-3.10"] 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v5 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | 24 | - name: Update pip 25 | run: python -m pip install --upgrade pip 26 | - name: Build and install python-omemo 27 | run: pip install . 28 | - name: Install test dependencies 29 | run: | 30 | pip install --upgrade pytest pytest-asyncio pytest-cov mypy pylint flake8 setuptools 31 | pip install --upgrade twisted twomemo[xml] oldmemo[xml] 32 | 33 | - name: Type-check using mypy 34 | run: mypy --strict --disable-error-code str-bytes-safe omemo/ setup.py examples/ tests/ 35 | - name: Lint using pylint 36 | run: pylint omemo/ setup.py examples/ tests/ 37 | - name: Format-check using Flake8 38 | run: flake8 omemo/ setup.py examples/ tests/ 39 | - name: Test using pytest 40 | run: pytest --cov=omemo --cov-report term-missing:skip-covered 41 | 42 | build: 43 | name: Build source distribution and wheel 44 | runs-on: ubuntu-latest 45 | 46 | steps: 47 | - uses: actions/checkout@v4 48 | 49 | - name: Build source distribution and wheel 50 | run: python3 setup.py sdist bdist_wheel 51 | 52 | - uses: actions/upload-artifact@v4 53 | with: 54 | name: dist 55 | path: | 56 | dist/*.tar.gz 57 | dist/*.whl 58 | 59 | publish: 60 | needs: [test, build] 61 | runs-on: ubuntu-latest 62 | permissions: 63 | id-token: write 64 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') 65 | 66 | steps: 67 | - uses: actions/download-artifact@v4 68 | with: 69 | path: dist 70 | merge-multiple: true 71 | 72 | - name: Publish package distributions to PyPI 73 | uses: pypa/gh-action-pypi-publish@release/v1 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | OMEMO.egg-info/ 3 | 4 | __pycache__/ 5 | .pytest_cache/ 6 | .mypy_cache/ 7 | .coverage 8 | 9 | build/ 10 | docs/_build/ 11 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | build: 4 | os: ubuntu-lts-latest 5 | tools: 6 | python: "3" 7 | 8 | sphinx: 9 | configuration: docs/conf.py 10 | fail_on_warning: true 11 | 12 | python: 13 | install: 14 | - requirements: docs/requirements.txt 15 | - method: pip 16 | path: . 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [1.2.0] - 15th of October, 2024 10 | 11 | ### Changed 12 | - Slightly improved logging for less spam and more clarity 13 | - Drop support for Python3.8, add support for Python3.13, bump PyPy test version to 3.10 14 | - Internal housekeeping, mostly related to pylint 15 | 16 | ## [1.1.0] - 28th of September, 2024 17 | 18 | ### Changed 19 | - No changes; the last release should have been a new minor version. 20 | 21 | ## [1.0.5] - 25th of September, 2024 22 | 23 | ### Added 24 | - A new method `refresh_device_lists` that calls `refresh_device_list` for all loaded backends. 25 | 26 | ## [1.0.4] - 14th of July, 2024 27 | 28 | ### Fixed 29 | - Attempt to fix a storage data inconsistency where namespace support is stored for a device but activity information is not 30 | 31 | ## [1.0.3] - 9th of July, 2024 32 | 33 | ### Changed 34 | - Removed unnecessary complexity/flexibility by returning `None` instead of `Any` from abstract methods whose return values are not used 35 | - The bundle publishing logic in the signed pre key rotation did not correctly double the retry delay 36 | - Log message improvements 37 | - 2024 maintenance (bumped Python versions, adjusted for updates to pydantic, mypy, pylint, pytest and GitHub actions) 38 | 39 | ### Fixed 40 | - Fixed a bug where a modified bundle might not be uploaded correctly 41 | 42 | ## [1.0.2] - 4th of November, 2022 43 | 44 | ### Added 45 | - A new exception `BundleNotFound`, raised by `_download_bundle`, to allow differentiation between technical bundle download failures and the simple absence of a bundle 46 | 47 | ### Changed 48 | - A small change in the package detection in setup.py led to a broken PyPI package 49 | - Improved download failure exception semantics and removed incorrect raises annotations 50 | 51 | ## [1.0.1] - 3rd of November, 2022 52 | 53 | ### Added 54 | - Python 3.11 to the list of supported versions 55 | 56 | ## [1.0.0] - 1st of November, 2022 57 | 58 | ### Changed 59 | - Complete rewrite of the library (and dependencies) to use asynchronous and (strictly) typed Python 3. 60 | - Support for different versions of [XEP-0384](https://xmpp.org/extensions/xep-0384.html) via separate backend packages. 61 | - Mostly following [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) now (except for the date format). 62 | 63 | ## [0.14.0] - 12th of March, 2022 64 | 65 | ### Changed 66 | - Adjusted signature of the `SessionManager.encryptRatchetForwardingMessage` method to accept exactly one bare JID + device id pair 67 | - Updated the license in the setup.py, which was desync with the LICENSE file 68 | - Adjusted the copyright year 69 | 70 | ### Removed 71 | - Removed Python 3.4 from the list of supported Python versions 72 | - Removed some mentions of Python 2 from the README 73 | 74 | ## [0.13.0] - 15th of December 2021 75 | 76 | ### Added 77 | - Added a method to retrieve the receiving chain length of a single session form the `SessionManager` 78 | 79 | ### Changed 80 | - The storage interface has been modified to use asyncio coroutines instead of callbacks. 81 | - All methods of the session manager that returned promises previously have been replaced with equivalent asyncio coroutines. 82 | 83 | ### Removed 84 | - Dropped Python 2 support and removed a bit of Python 2 compatibility clutter 85 | - Removed synchronous APIs 86 | - Removed thread-based promise implementation in favor of asyncio futures and coroutines 87 | 88 | ## [0.12.0] - 28th of March, 2020 89 | 90 | ### Changed 91 | - The `JSONFileStorage` now encodes JIDs using hashes, to avoid various issues regarding the file system. **WARNING, THERE ARE KNOWN ISSUES WITH THIS VERSION OF THE STORAGE IMPLEMENTATION.** 92 | - Sending 12 byte IVs instead of 16 now. 93 | - `SessionManager.encryptKeyTransportMessage` now receives the optional plaintext as a parameter directly, instead of using a callback to encrypt external data. If the plaintext is omitted, a shared secret is returned that can be used for purposes external to this library. 94 | - Switched to MIT license with the agreement of all contributors! 95 | 96 | ### Fixed 97 | - Fixed the way key transport messages are sent and received to be compatible with other implementations. 98 | 99 | ## [0.11.0] - 13th of December, 2019 100 | 101 | ### Added 102 | - Added a new method `resetTrust`, which allows going back to the trust level `undecided`. 103 | 104 | ### Changed 105 | - Merged the `trust` and `distrust` methods into `setTrust`. 106 | - `Storage.storeTrust` must now be able to handle the value `None` for the `trust` parameter. 107 | 108 | ### Removed 109 | - Removed the `SessionManagerAsyncIO`, in preparation for the big Python 3 update coming soon™. 110 | 111 | ### Fixed 112 | - Fixed a bug in the `SessionManager`, where the contents of a parameter (passed by reference) were modified. 113 | 114 | ## [0.10.5] - 21st of July, 2019 115 | 116 | ### Fixed 117 | - Fixed two bugs in the `JSONFileStorage` implementation. 118 | - Fixed a type issue in the `__str__` of the `TrustException`. 119 | - Fixed a rare bug where sessions uncapable of encrypting messages would be stored. 120 | 121 | ## [0.10.4] - 1st of February, 2019 122 | 123 | ### Added 124 | - Added an implementation of the storage using a simple directory structure and JSON files. 125 | 126 | ### Changed 127 | - `RatchetForwardingMessages` do not require the recipient to be trusted any more, as they contain no user-generated content. See #22 for information. 128 | - Renamed `UntrustedException` to `TrustException` and added a fourth field `problem` to get the type of problem (untrusted vs. undecided). 129 | 130 | ## [0.10.3] - 29th of December, 2018 131 | 132 | ### Added 133 | - Added a method for requesting trust information from the storage at bulk. This can be overridden for better performance. 134 | - Added a method for requesting sessions from the storage at bulk. This can be overridden for better performance. 135 | - Added a public method to delete an existing session. This is useful to recover from broken sessions. 136 | - Added a public method to retrieve a list of all managed JIDs. 137 | - Added a stresstest, mostly to test recursion depth. 138 | 139 | ### Changed 140 | - Turned the changelog upside-down, so that the first entry is the newest. 141 | - Modified `no_coroutine` in the promise lib to use a loop instead of recursion. 142 | - Modified the promise constructor to run promises in threads. 143 | 144 | ## [0.10.2] - 29th of December, 2018 145 | 146 | ### Added 147 | - Added methods to retrieve trust information from the `SessionManager`: `getTrustForDevice` and `getTrustForJID`. 148 | 149 | ### Changed 150 | - Introduced an exception hierarchy to allow for more fine-grained exception catching and type checking. 151 | - Most exceptions now implement `__str__` to generate human-readable messages. 152 | 153 | ### Fixed 154 | - Fixed a bug that tried to instantiate an object of the wrong class from serialized data. 155 | 156 | ## [0.10.1] - 27th of December, 2018 157 | 158 | ### Added 159 | - Added CHANGELOG. 160 | 161 | ### Changed 162 | - Upon serialization the current library version is added to the serialized structures, to allow for seamless updates in the future. 163 | 164 | [Unreleased]: https://github.com/Syndace/python-omemo/compare/v1.2.0...HEAD 165 | [1.2.0]: https://github.com/Syndace/python-omemo/compare/v1.1.0...v1.2.0 166 | [1.1.0]: https://github.com/Syndace/python-omemo/compare/v1.0.5...v1.1.0 167 | [1.0.5]: https://github.com/Syndace/python-omemo/compare/v1.0.4...v1.0.5 168 | [1.0.4]: https://github.com/Syndace/python-omemo/compare/v1.0.3...v1.0.4 169 | [1.0.3]: https://github.com/Syndace/python-omemo/compare/v1.0.2...v1.0.3 170 | [1.0.2]: https://github.com/Syndace/python-omemo/compare/v1.0.1...v1.0.2 171 | [1.0.1]: https://github.com/Syndace/python-omemo/compare/v1.0.0...v1.0.1 172 | [1.0.0]: https://github.com/Syndace/python-omemo/compare/v0.14.0...v1.0.0 173 | [0.14.0]: https://github.com/Syndace/python-omemo/compare/v0.13.0...v0.14.0 174 | [0.13.0]: https://github.com/Syndace/python-omemo/compare/v0.12.0...v0.13.0 175 | [0.12.0]: https://github.com/Syndace/python-omemo/compare/v0.11.0...v0.12.0 176 | [0.11.0]: https://github.com/Syndace/python-omemo/compare/v0.10.5...v0.11.0 177 | [0.10.5]: https://github.com/Syndace/python-omemo/compare/v0.10.4...v0.10.5 178 | [0.10.4]: https://github.com/Syndace/python-omemo/compare/v0.10.3...v0.10.4 179 | [0.10.3]: https://github.com/Syndace/python-omemo/compare/v0.10.2...v0.10.3 180 | [0.10.2]: https://github.com/Syndace/python-omemo/compare/v0.10.1...v0.10.2 181 | [0.10.1]: https://github.com/Syndace/python-omemo/releases/tag/v0.10.1 182 | -------------------------------------------------------------------------------- /Exceptions.drawio: -------------------------------------------------------------------------------- 1 | 7ZxdV+o4FIZ/DZfOoi0UuDwKOi5BWQdx9NycFdvYRkLSScOXv35SSKElFfWAJKP1QpudlNbnTbKzd6IV52w8v2AgCnvUh7hiV/15xWlXbPHlNsWPxLJYWRpNa2UIGPJXpoxhgF6gNFaldYJ8GOcackoxR1He6FFCoMdzNsAYneWbPVGcf2oEAqgYBh7AqvUf5PNwZW3Wqxv73xAFYfpkqyprxiBtLA1xCHw6y5icTsU5Y5Ty1dV4fgZxAi/lsrrv/JXa9YsxSPh7bvhpXV2NIoCifxfdq/P+7x/B8/DEacmX44v0N4a+ACCLlPGQBpQA3NlYTxmdEB8mH1sVpU2bLqWRMFrC+Aw5X0g1wYRTYQr5GMtaOEf8Prn9r7osPWRq2nP5ycvCIi0QzhaZm5LiQ7Zuc9uylN6nYpLkYjphHtzBJu1ugAWQ72hnr9ol3DIPkCJcQDqG4n1EAwYx4Gia71hA9s9g3W4jobiQKn5A0Vq1VHRfRR2zFLVKRfdVtGaWonap6L6K1o1SVH7uFOCJfFLFdrF4/1MfTcVlkFze9Dq9m87cgxFHlKQNxPMybZSOkZd9FiIOBxFYIpyJJVde4lexTyHjcL4TlKx1UgciF2xpcbZZ/ViutIWZlU/a7uBonZrewdL4g9Fi5cbKZugcfLTY7xwtrlGjxamXku4tacMsSd1S0r0lbZolaaOUdG9JW2ZJ2iwl3VvSNDV1fE0X/WHt5fLnqPXSBqHbmj288JeTUtIPSVrIUFvAX/g2mnNyX0JRbQF/4dtYmpNyX0JSbRF/saSas3JfQlJtYWmxpJrTcl9CUrPCUvnWmbzcAMYxoqQHCAggy2TjNOfdttJulq0772aXC8s3d4jejhUss4ZDubQ8gKZmTXFOubY8gKaGpd7KxeUBNDUs91auLvfX1NaWeyt+bafUdH9Nta2RvJu79uTmtm/fg153xGeNeffu5LsM0y3cB9O4EKreUVrZDgLve/3+JeGQAS8J/s4BwkI93SGgeTFgTSE34JSJwNmguFkntMIMyHeZQP5kvqir80VxKk6XS6jZ7oPD7oazwdNJG5wOfs8vf5WKfkzRQobaFLX6z42Z32PT9i9/et+58Kyzh1LRjylayNCs1FZdcVWnwBtB4pvjqlzj/LurQBuSEaEzcssmMe/CafLXPJqprWM+Sa2p/URqQ6FWcNh3SbANPRRnFphGnvjdBmxXdQNuFiw7EcZDgcVDvgErdQVZUzeyloLsmnYwCtAjhm04RR6MjaPmuLqppecy1AnwGoxhvIRhGrWWdq+Rbmplfa1gguEwwhT4hkTTVtO0ac1SHceKW1t0OJPJaZ/dLNUjSHIQQ4MyONvkatrXKpbqGFbuoItibvR4rWuf52zVO2zYGT5mXe2zna16iR6M4+TP60VUhkhgKrljzna7kl8ZcFdwIcLYEJAAGkKtrtO77jrDrXa3a8rPKRuat/49qnfYdUo6dzxOIGFLZAKOcciO6hR2nUJWkLWFT0hCfgPG5ja0o/qCXed8c9GpPIhpHi3t878aJvQnjxh5bcDBJfEoiUVfg8RbGMeuccyIvth3qm5AoRSHIEouvQnDi1OWpIn527g2bA8Fz33bhdoF7NbtDg9PndzW2XPhPqsMoDiZ36pw7uFJjKYQJ7/PY/KNhzCpIB5byGx79QnTmQJfwOF5sGLepCN4RjFlwkIoSTZbnhDGWyaAUUAS2WCycy8MCWrkAfxDVoyR7y93aoqUzA+Ng/T9rXT+UcPkYv3Uefb/0vmL1kJFnX+dMzw8PHXa/WDn9+H37fxHXWPs2mDOyHdLaQ+QxWCEogj6MhoQoZT+SKC+PfUXTR3NT6K3azM3l+pIe7OhIedRtw9eP9X21kbgKlG5iag+aw9QAVmA+91JkM9kK4qb/3q4rMv870in8x8= -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2024 Tim Henkes (Syndace) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include omemo/py.typed 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PyPI](https://img.shields.io/pypi/v/OMEMO.svg)](https://pypi.org/project/OMEMO/) 2 | [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/OMEMO.svg)](https://pypi.org/project/OMEMO/) 3 | [![Build Status](https://github.com/Syndace/python-omemo/actions/workflows/test-and-publish.yml/badge.svg)](https://github.com/Syndace/python-omemo/actions/workflows/test-and-publish.yml) 4 | [![Documentation Status](https://readthedocs.org/projects/py-omemo/badge/?version=latest)](https://py-omemo.readthedocs.io/) 5 | 6 | # python-omemo # 7 | 8 | A Python implementation of the [OMEMO Multi-End Message and Object Encryption protocol](https://xmpp.org/extensions/xep-0384.html). 9 | 10 | A complete implementation of [XEP-0384](https://xmpp.org/extensions/xep-0384.html) on protocol-level, i.e. more than just the cryptography. python-omemo supports different versions of the specification through so-called backends. A backend for OMEMO in the `urn:xmpp:omemo:2` namespace (the most recent version of the specification) is available in the [python-twomemo](https://github.com/Syndace/python-twomemo) Python package. A backend for (legacy) OMEMO in the `eu.siacs.conversations.axolotl` namespace is available in the [python-oldmemo](https://github.com/Syndace/python-oldmemo) package. Multiple backends can be loaded and used at the same time, the library manages their coexistence transparently. 11 | 12 | ## Installation ## 13 | 14 | Install the latest release using pip (`pip install OMEMO`) or manually from source by running `pip install .` in the cloned repository. 15 | 16 | ## Testing, Type Checks and Linting ## 17 | 18 | python-omemo uses [pytest](https://docs.pytest.org/en/latest/) as its testing framework, [mypy](http://mypy-lang.org/) for static type checks and both [pylint](https://pylint.pycqa.org/en/latest/) and [Flake8](https://flake8.pycqa.org/en/latest/) for linting. All tests/checks can be run locally with the following commands: 19 | 20 | ```sh 21 | $ pip install --upgrade pytest pytest-asyncio pytest-cov mypy pylint flake8 22 | $ pip install --upgrade twisted twomemo[xml] oldmemo[xml] 23 | $ mypy --strict --disable-error-code str-bytes-safe omemo/ setup.py examples/ tests/ 24 | $ pylint omemo/ setup.py examples/ tests/ 25 | $ flake8 omemo/ setup.py examples/ tests/ 26 | $ pytest --cov=omemo --cov-report term-missing:skip-covered 27 | ``` 28 | 29 | ## Getting Started ## 30 | 31 | Refer to the documentation on [readthedocs.io](https://py-omemo.readthedocs.io/), or build/view it locally in the `docs/` directory. To build the docs locally, install the requirements listed in `docs/requirements.txt`, e.g. using `pip install -r docs/requirements.txt`, and then run `make html` from within the `docs/` directory. The documentation can then be found in `docs/_build/html/`. 32 | 33 | The `functionality.md` file contains an overview of supported functionality/use cases, mostly targeted at developers. 34 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = OMEMO 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/_static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Syndace/python-omemo/11199154baab5862e2dedfb10769c96c767becde/docs/_static/.gitkeep -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file does only contain a selection of the most common options. For a full list see 4 | # the documentation: 5 | # http://www.sphinx-doc.org/en/master/config 6 | 7 | # -- Path setup -------------------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, add these 10 | # directories to sys.path here. If the directory is relative to the documentation root, 11 | # use os.path.abspath to make it absolute, like shown here. 12 | import os 13 | import sys 14 | 15 | this_file_path = os.path.dirname(os.path.abspath(__file__)) 16 | sys.path.append(os.path.join(this_file_path, "..", "omemo")) 17 | 18 | from version import __version__ as __version 19 | from project import project as __project 20 | 21 | # -- Project information ----------------------------------------------------------------- 22 | 23 | project = __project["name"] 24 | author = __project["author"] 25 | copyright = f"{__project['year']}, {__project['author']}" 26 | 27 | # The short X.Y version 28 | version = __version["short"] 29 | # The full version, including alpha/beta/rc tags 30 | release = __version["full"] 31 | 32 | # -- General configuration --------------------------------------------------------------- 33 | 34 | # Add any Sphinx extension module names here, as strings. They can be extensions coming 35 | # with Sphinx (named "sphinx.ext.*") or your custom ones. 36 | extensions = [ 37 | "sphinx.ext.autodoc", 38 | "sphinx.ext.viewcode", 39 | "sphinx.ext.napoleon", 40 | "sphinx_autodoc_typehints" 41 | ] 42 | 43 | # Add any paths that contain templates here, relative to this directory. 44 | templates_path = [ "_templates" ] 45 | 46 | # List of patterns, relative to source directory, that match files and directories to 47 | # ignore when looking for source files. 48 | # This pattern also affects html_static_path and html_extra_path. 49 | exclude_patterns = [ "_build", "Thumbs.db", ".DS_Store" ] 50 | 51 | # -- Options for HTML output ------------------------------------------------------------- 52 | 53 | # The theme to use for HTML and HTML Help pages. See the documentation for a list of 54 | # builtin themes. 55 | html_theme = "sphinx_rtd_theme" 56 | 57 | # Add any paths that contain custom static files (such as style sheets) here, relative to 58 | # this directory. They are copied after the builtin static files, so a file named 59 | # "default.css" will overwrite the builtin "default.css". 60 | html_static_path = [ "_static" ] 61 | 62 | # -- Autodoc Configuration --------------------------------------------------------------- 63 | 64 | # The following two options seem to be ignored... 65 | autodoc_typehints = "description" 66 | autodoc_type_aliases = { type_alias: f"{type_alias}" for type_alias in { 67 | "Priv", 68 | "Seed", 69 | "Ed25519Pub", 70 | "JSONType" 71 | } } 72 | 73 | def autodoc_skip_member_handler(app, what, name, obj, skip, options): 74 | # Skip private members, i.e. those that start with double underscores but do not end in underscores 75 | if name.startswith("__") and not name.endswith("_"): 76 | return True 77 | 78 | # Could be achieved using exclude-members, but this is more comfy 79 | if name in { 80 | "__abstractmethods__", 81 | "__dict__", 82 | "__module__", 83 | "__new__", 84 | "__weakref__", 85 | "_abc_impl" 86 | }: return True 87 | 88 | # Skip __init__s without documentation. Those are just used for type hints. 89 | if name == "__init__" and obj.__doc__ is None: 90 | return True 91 | 92 | return None 93 | 94 | def setup(app): 95 | app.connect("autodoc-skip-member", autodoc_skip_member_handler) 96 | -------------------------------------------------------------------------------- /docs/getting_started.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | =============== 3 | 4 | python-omemo only ships the core functionality common to all versions of `XEP-0384 `_ and relies on backends to implement the details of each version. Each backend is uniquely identified by the namespace it implements. 5 | 6 | Backend Selection 7 | ----------------- 8 | 9 | There are two official backends: 10 | 11 | ================================== ==== 12 | Namespace Link 13 | ================================== ==== 14 | ``urn:xmpp:omemo:2`` `python-twomemo `_ 15 | ``eu.siacs.conversations.axolotl`` `python-oldmemo `_ 16 | ================================== ==== 17 | 18 | Both backends (and more) can be loaded at the same time and the library will handle compatibility. You can specify backend priority, which will be used to decide which backend to use for encryption in case a recipient device supports multiple loaded backends. 19 | 20 | Public API and Backends 21 | ----------------------- 22 | 23 | Backends differ in many aspects, from the wire format of the transferred data to the internal cryptographic primitves used. Thus, most parts of the public API take a parameter that specifies the backend to use for the given operation. The core transparently handles all things common to backends and forwards the backend-specific parts to the corresponding backend. 24 | 25 | Trust 26 | ----- 27 | 28 | python-omemo offers trust management. Since it is not always obvious how trust and JID/device id/identity key belong together, this section gives an overview of the trust concept followed by python-omemo. 29 | 30 | Each XMPP account has a pool of identity keys. Each device is assigned one identity key from the pool. Theoretically, this concept allows for one identity key to be assigned to multiple devices, however, the security implications of doing so have not been addressed in the XEP, thus it is not recommended and not supported by this library. 31 | 32 | Trust levels are assigned to identity keys, not devices. I.e. devices are not directly trusted, only implicitly by trusting the identity key assigned to them. 33 | 34 | The library works with two types of trust levels: custom trust levels and core trust levels. Custom trust levels are assigned to identity keys and can be any Python string. There is no limitation on the number of custom trust levels. Custom trust levels are not used directly by the library for decisions requiring trust (e.g. during message encryption), instead they are translated to one of the three core trust levels first: Trusted, Distrusted, Undecided. The translation from custom trust levels to core trust levels has to be supplied by implementing the :meth:`~omemo.session_manager.SessionManager._evaluate_custom_trust_level` method. 35 | 36 | This trust concept allows for the implementation of trust systems like `BTBV `_, `TOFU `_, simple manual trust or more complex systems. 37 | 38 | An example of a BTBV trust system implementation can be found in ``examples/btbv_session_manager.py``. If you happen to aim for BTBV support in your client, feel free to use that code as a starting point. 39 | 40 | Setting it Up 41 | ------------- 42 | 43 | With the backends selected and the trust system chosen, the library can be set up. 44 | 45 | This is done in three steps: 46 | 47 | 1. Create a :class:`~omemo.storage.Storage` implementation 48 | 2. Create a :class:`~omemo.session_manager.SessionManager` implementation 49 | 3. Instantiate your :class:`~omemo.session_manager.SessionManager` implementation 50 | 51 | :class:`~omemo.storage.Storage` Implementation 52 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 53 | 54 | python-omemo uses a simple key-value storage to persist its state. This storage has to be provided to the library by implementing the :class:`~omemo.storage.Storage` interface. Refer to the API documentation of the :class:`~omemo.storage.Storage` interface for details. 55 | 56 | .. WARNING:: 57 | It might be tempting to offer a backup/restore flow for the OMEMO data. However, due to the forward secrecy of OMEMO, restoring old data results in broken sessions. It is strongly recommended to not include OMEMO data in backups, and to at most include it in migration flows that make sure that old data can't be restored over newer data. 58 | 59 | :class:`~omemo.session_manager.SessionManager` Implementation 60 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 61 | 62 | Create a subclass of :class:`~omemo.session_manager.SessionManager`. There are various abstract methods for interaction with XMPP (device lists, bundles etc.) and trust management that you have to fill out to integrate the library with your client/framework. The API documentation of the :class:`~omemo.session_manager.SessionManager` class should contain the necessary information. 63 | 64 | Instantiate the Library 65 | ^^^^^^^^^^^^^^^^^^^^^^^ 66 | 67 | Finally, instantiate the storage, backends and then the :class:`~omemo.session_manager.SessionManager`, which is the class that offers all of the public API for message encryption, decryption, trust and device management etc. To do so, simply call the :meth:`~omemo.session_manager.SessionManager.create` method, passing the backend and storage implementations you've prepared. Refer to the API documentation for details on the configuration options accepted by :meth:`~omemo.session_manager.SessionManager.create`. 68 | 69 | Migration 70 | --------- 71 | 72 | Refer to :ref:`migration_from_legacy` for information about migrating from pre-stable python-omemo to python-omemo 1.0+. Migrations within stable (1.0+) versions are handled automatically. 73 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | OMEMO - A Python implementation of the OMEMO Multi-End Message and Object Encryption protocol. 2 | ============================================================================================== 3 | 4 | A Python implementation of the `OMEMO Multi-End Message and Object Encryption protocol `_. 5 | 6 | A complete implementation of `XEP-0384 `_ on protocol-level, i.e. more than just the cryptography. python-omemo supports different versions of the specification through so-called backends. A backend for OMEMO in the ``urn:xmpp:omemo:2`` namespace (the most recent version of the specification) is available in the `python-twomemo `_ Python package. A backend for (legacy) OMEMO in the ``eu.siacs.conversations.axolotl`` namespace is available in the `python-oldmemo `_ package. Multiple backends can be loaded and used at the same time, the library manages their coexistence transparently. 7 | 8 | .. toctree:: 9 | installation 10 | getting_started 11 | migration_from_legacy 12 | API Documentation 13 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | Install the latest release using pip (``pip install OMEMO``) or manually from source by running ``pip install .`` in the cloned repository. 5 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=OMEMO 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 20 | echo.installed, then set the SPHINXBUILD environment variable to point 21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 22 | echo.may add the Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /docs/migration_from_legacy.rst: -------------------------------------------------------------------------------- 1 | .. _migration_from_legacy: 2 | 3 | Migration from Legacy 4 | ===================== 5 | 6 | Due to the multi-backend approach and storage structure of ``python-omemo``, migrations are provided by backends rather than the core library. For users of legacy ``python-omemo`` (i.e. versions before 1.0.0) with ``python-omemo-backend-signal``, the `python-oldmemo `_ package provides migrations. Please refer to the backend documentation for details. 7 | -------------------------------------------------------------------------------- /docs/omemo/backend.rst: -------------------------------------------------------------------------------- 1 | Module: backend 2 | =============== 3 | 4 | .. automodule:: omemo.backend 5 | :members: 6 | :special-members: 7 | :private-members: 8 | :undoc-members: 9 | :member-order: bysource 10 | :show-inheritance: 11 | -------------------------------------------------------------------------------- /docs/omemo/bundle.rst: -------------------------------------------------------------------------------- 1 | Module: bundle 2 | ============== 3 | 4 | .. automodule:: omemo.bundle 5 | :members: 6 | :special-members: 7 | :private-members: 8 | :undoc-members: 9 | :member-order: bysource 10 | :show-inheritance: 11 | -------------------------------------------------------------------------------- /docs/omemo/identity_key_pair.rst: -------------------------------------------------------------------------------- 1 | Module: identity_key_pair 2 | ========================= 3 | 4 | .. automodule:: omemo.identity_key_pair 5 | :members: 6 | :special-members: 7 | :private-members: 8 | :undoc-members: 9 | :member-order: bysource 10 | :show-inheritance: 11 | -------------------------------------------------------------------------------- /docs/omemo/message.rst: -------------------------------------------------------------------------------- 1 | Module: message 2 | =============== 3 | 4 | .. automodule:: omemo.message 5 | :members: 6 | :undoc-members: 7 | :member-order: bysource 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /docs/omemo/package.rst: -------------------------------------------------------------------------------- 1 | Package: omemo 2 | ============== 3 | 4 | .. toctree:: 5 | Module: backend 6 | Module: bundle 7 | Module: identity_key_pair 8 | Module: message 9 | Module: session 10 | Module: session_manager 11 | Module: storage 12 | Module: types 13 | -------------------------------------------------------------------------------- /docs/omemo/session.rst: -------------------------------------------------------------------------------- 1 | Module: session 2 | =============== 3 | 4 | .. automodule:: omemo.session 5 | :members: 6 | :undoc-members: 7 | :member-order: bysource 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /docs/omemo/session_manager.rst: -------------------------------------------------------------------------------- 1 | Module: session_manager 2 | ======================= 3 | 4 | .. automodule:: omemo.session_manager 5 | :members: 6 | :special-members: 7 | :private-members: 8 | :undoc-members: 9 | :member-order: bysource 10 | :show-inheritance: 11 | -------------------------------------------------------------------------------- /docs/omemo/storage.rst: -------------------------------------------------------------------------------- 1 | Module: storage 2 | =============== 3 | 4 | .. automodule:: omemo.storage 5 | :members: 6 | :special-members: __init__ 7 | :private-members: 8 | :undoc-members: 9 | :member-order: bysource 10 | :show-inheritance: 11 | -------------------------------------------------------------------------------- /docs/omemo/types.rst: -------------------------------------------------------------------------------- 1 | Module: types 2 | ============= 3 | 4 | .. automodule:: omemo.types 5 | :members: 6 | :undoc-members: 7 | :member-order: bysource 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx 2 | sphinx-rtd-theme 3 | sphinx-autodoc-typehints 4 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | To see the library in action, refer to the OMEMO implementations of the following clients: 2 | 3 | - [Libervia](https://repos.goffi.org/libervia-backend/file/tip/sat/plugins/plugin_xep_0384.py) 4 | -------------------------------------------------------------------------------- /examples/btbv_session_manager.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import enum 3 | from typing import FrozenSet, Optional, Set 4 | 5 | from typing_extensions import assert_never 6 | 7 | import omemo 8 | 9 | 10 | __all__ = [ 11 | "BTBVSessionManager", 12 | "BTBVTrustLevel" 13 | ] 14 | 15 | 16 | @enum.unique 17 | class BTBVTrustLevel(enum.Enum): 18 | """ 19 | Trust levels modeling Blind Trust Before Verification (BTBV). 20 | """ 21 | 22 | TRUSTED: str = "TRUSTED" 23 | BLINDLY_TRUSTED: str = "BLINDLY_TRUSTED" 24 | UNDECIDED: str = "UNDECIDED" 25 | DISTRUSTED: str = "DISTRUSTED" 26 | 27 | 28 | # Note that while this is an "example", it is fully functional and can be used as-is. 29 | class BTBVSessionManager(omemo.SessionManager): 30 | """ 31 | Partial :class:`omemo.SessionManager` implementation with BTBV as its trust system. 32 | """ 33 | 34 | async def _evaluate_custom_trust_level(self, device: omemo.DeviceInformation) -> omemo.TrustLevel: 35 | try: 36 | trust_level = BTBVTrustLevel(device.trust_level_name) 37 | except ValueError as e: 38 | raise omemo.UnknownTrustLevel(f"Unknown trust level name: {device.trust_level_name}") from e 39 | 40 | if trust_level is BTBVTrustLevel.TRUSTED or trust_level is BTBVTrustLevel.BLINDLY_TRUSTED: 41 | return omemo.TrustLevel.TRUSTED 42 | if trust_level is BTBVTrustLevel.UNDECIDED: 43 | return omemo.TrustLevel.UNDECIDED 44 | if trust_level is BTBVTrustLevel.DISTRUSTED: 45 | return omemo.TrustLevel.DISTRUSTED 46 | 47 | assert_never(trust_level) 48 | 49 | async def _make_trust_decision( 50 | self, 51 | undecided: FrozenSet[omemo.DeviceInformation], 52 | identifier: Optional[str] 53 | ) -> None: 54 | # For BTBV, affected JIDs can be separated into two pools: one pool of JIDs for which blind trust is 55 | # active, i.e. no manual verification was performed before, and one pool of JIDs to use manual trust 56 | # with instead. 57 | bare_jids = { device.bare_jid for device in undecided } 58 | 59 | blind_trust_bare_jids: Set[str] = set() 60 | manual_trust_bare_jids: Set[str] = set() 61 | 62 | # For each bare JID, decide whether blind trust applies 63 | for bare_jid in bare_jids: 64 | # Get all known devices belonging to the bare JID 65 | devices = await self.get_device_information(bare_jid) 66 | 67 | # If the trust levels of all devices correspond to those used by blind trust, blind trust applies. 68 | # Otherwise, fall back to manual trust. 69 | if all(BTBVTrustLevel(device.trust_level_name) in { 70 | BTBVTrustLevel.UNDECIDED, 71 | BTBVTrustLevel.BLINDLY_TRUSTED 72 | } for device in devices): 73 | blind_trust_bare_jids.add(bare_jid) 74 | else: 75 | manual_trust_bare_jids.add(bare_jid) 76 | 77 | # With the JIDs sorted into their respective pools, the undecided devices can be categorized too 78 | blindly_trusted_devices = { dev for dev in undecided if dev.bare_jid in blind_trust_bare_jids } 79 | manually_trusted_devices = { dev for dev in undecided if dev.bare_jid in manual_trust_bare_jids } 80 | 81 | # Blindly trust devices handled by blind trust 82 | if len(blindly_trusted_devices) > 0: 83 | for device in blindly_trusted_devices: 84 | await self.set_trust( 85 | device.bare_jid, 86 | device.identity_key, 87 | BTBVTrustLevel.BLINDLY_TRUSTED.name 88 | ) 89 | 90 | await self._devices_blindly_trusted(frozenset(blindly_trusted_devices), identifier) 91 | 92 | # Prompt the user for manual trust decisions on the devices handled by manual trust 93 | if len(manually_trusted_devices) > 0: 94 | await self._prompt_manual_trust(frozenset(manually_trusted_devices), identifier) 95 | 96 | async def _devices_blindly_trusted( 97 | self, 98 | blindly_trusted: FrozenSet[omemo.DeviceInformation], 99 | identifier: Optional[str] 100 | ) -> None: 101 | """ 102 | Get notified about newly blindly trusted devices. This method is called automatically by 103 | :meth:`_make_trust_decision` whenever at least one device was blindly trusted. You can use this method 104 | for example to notify the user about the automated change in trust. 105 | 106 | Does nothing by default. 107 | 108 | Args: 109 | blindly_trusted: A set of devices that were blindly trusted. 110 | identifier: Forwarded from :meth:`_make_trust_decision`, refer to its documentation for details. 111 | """ 112 | 113 | @abc.abstractmethod 114 | async def _prompt_manual_trust( 115 | self, 116 | manually_trusted: FrozenSet[omemo.DeviceInformation], 117 | identifier: Optional[str] 118 | ) -> None: 119 | """ 120 | Prompt manual trust decision on a set of undecided identity keys. The trust decisions are expected to 121 | be persisted by calling :meth:`set_trust`. 122 | 123 | Args: 124 | manually_trusted: A set of devices whose trust has to be manually decided by the user. 125 | identifier: Forwarded from :meth:`_make_trust_decision`, refer to its documentation for details. 126 | 127 | Raises: 128 | TrustDecisionFailed: if for any reason the trust decision failed/could not be completed. Feel free 129 | to raise a subclass instead. 130 | 131 | Note: 132 | This is called when the encryption needs to know whether it is allowed to encrypt for these 133 | devices or not. When this method returns, all previously undecided trust levels should have been 134 | replaced by calling :meth:`set_trust` with a different trust level. If they are not replaced or 135 | still evaluate to the undecided trust level after the call, the encryption will fail with an 136 | exception. See :meth:`encrypt` for details. 137 | """ 138 | -------------------------------------------------------------------------------- /functionality.md: -------------------------------------------------------------------------------- 1 | # Functionality/Use Cases # 2 | 3 | - [x] the maximum number of skipped message keys to keep around per session is configurable 4 | - [x] the default is set to 1000 5 | - [x] the value is limited neither upwards nor downwards 6 | - [x] skipped message keys are deleted following LRU once the limit is reached 7 | 8 | - [x] the maximum number of skipped message keys in a single message is configurable 9 | - [x] the default is set to the maximum number of skipped message keys per session 10 | - [x] the value is not limited downwards, altough a value of 0 is forbidden if the maximum number of skipped message keys per session is non-zero 11 | - [x] the value is limited upwards to be lower than or equal to the maximum number of skipped message keys per session 12 | 13 | - [x] device lists are managed 14 | - [x] PEP updates to device lists are handled 15 | - [x] a function is provided to feed PEP updates to device lists into the library 16 | - [x] a PEP downloading mechanism must be provided by the application to download device lists from PEP 17 | - [x] the own device list is managed 18 | - [x] the own device is added to the list if it isn't included 19 | - [x] a label for the own device can optionally be provided 20 | - [x] a PEP publishing mechanism must be provided by the application to update the device list in PEP 21 | - [x] the most recent version of all device lists is cached 22 | - [x] a convenience method is provided to manually trigger the refresh of a device list 23 | - [x] devices that are removed from the device list are marked as "inactive", while devices on the list are marked as "active" 24 | - [x] only active devices are considered during encryption 25 | - [x] a device becoming inactive has no other effect than it being omitted during encryption, i.e. the data corrsponding to the device is never (automatically) deleted 26 | - [x] device lists of different backends are merged. it is assumed that device ids are unique even across backends. the same device id in multiple lists is assumed to represent the same device. 27 | - [x] the backends supported by each device are indicated together with the device id 28 | 29 | - [x] the own bundle is managed 30 | - [x] the identity key is managed 31 | - [x] the signed pre key is managed 32 | - [x] the signed pre key is rotated periodically 33 | - [x] the rotation period is configurable 34 | - [x] a default rotation period of between one week and one month is provided 35 | - [x] the signed pre key of the previous rotation is kept around for the next full period to account for delayed messages 36 | - [x] the pre keys are managed 37 | - [x] the number of pre keys is capped to 100 38 | - [x] the threshold for when to generate new pre keys is configurable 39 | - [x] the threshold can not be configured lower than 25 40 | - [x] the default threshold is 99, which means that every used pre key is replaced right away 41 | - [x] a PEP publishing mechanism must be provided by the application to update the bundle in PEP 42 | - [x] a PEP downloading mechanism must be provided by the application to download a bundle from PEP 43 | - [x] one bundle is managed per backend, only the identity key is shared between all backends/bundles 44 | - [x] care is taken to provide the identity key to each backend in the format required by the backend (i.e. Ed25519 or Curve25519) 45 | 46 | - [x] the own device id is generated 47 | - [x] the device id is shared across all backends 48 | - [x] the current device lists are consulted prior to device id generation to avoid the very unlikely case of a collision 49 | - [x] no efforts are made to detect clashes or avoid races (even on protocol level), due to the very low likeliness of a collision 50 | - [x] this mechanism can not prevent collisions with new backends if backends are added after the device id has been generated 51 | - [x] it is assumed that other clients also share device ids and identity keys across backends 52 | 53 | - [x] trust is managed 54 | - [x] custom trust levels are supported, allowing for different trust systems like BTBV 55 | - [x] a callback must be implemented to translate custom trust levels into core trust levels understood by the library 56 | - [x] the default trust level to assign to new devices must be specified 57 | - [x] trust decisions are always requested in bulk, such that applications can e.g. show one decision dialog for all outstanding trust decisions 58 | - [x] trust is shared across backends 59 | - [x] trust is applied to pairs of identity key and bare JID, device ids are not part of trust 60 | 61 | - [x] sessions can be built 62 | - [x] transparently when sending or receiving encrypted messages 63 | - [x] explicit session building APIs are not provided 64 | - [x] requires own bundle management 65 | - [x] sessions are per-backend 66 | - [x] a PEP downloading mechanism must be provided by the application to download public bundles from PEP 67 | 68 | - [x] messages can be encrypted 69 | - [x] requires session building, device list management and trust management 70 | - [x] multiple recipients are supported 71 | - [x] own devices are automatically added to the list of recipients, the sending device is removed from the list 72 | - [x] messages are only encrypted for devices whose trust level evaluates to "trusted" 73 | - [x] the message is not automatically sent, but a structure containing the encrypted payload and the headers is returned 74 | - [x] the backend(s) to encrypt the message with can be selected explicitly or implicitly 75 | - [x] in the explicit selection, a list of namespaces is given of which the order decides priority 76 | - [x] the type of the message parameter to the encryption methods is generic, and each backend provides a method to serialize the type into a byte string 77 | - [x] this is necessary because different backends require different inputs to message encryption. For example, omemo:1 requires stanzas for SCE and legacy OMEMO requires just text 78 | - [x] when multiple backends are used together, the generic type can be chosen as the lowest common denominator between all backend input types, and implement the serialization methods accordingly 79 | - [x] implicit selection is the default, with the priority order taken from the order of the backends as passed to the constructor 80 | 81 | - [x] empty OMEMO messages can be sent 82 | - [x] transparently when required by the protocol 83 | - [x] explicit API for empty OMEMO messages is not provided 84 | - [x] a mechanism must be provided by the application to send empty OMEMO messages 85 | - [x] trust is not applied for empty OMEMO messages 86 | 87 | - [x] messages can be decrypted 88 | - [x] requires session building and trust management 89 | - [x] the whole OMEMO-encrypted message can be passed to the library, it will select the correct header corresponding the the device 90 | - [x] the type of the decrypted message is generic, each backend provides a method to deserialize the decrypted message body from a byte string into its respective type 91 | - [x] this is necessary because different backends produce different outputs from message decryption. For example, omemo:1 produces stanzas from SCE and legacy OMEMO produces just text 92 | - [x] when multiple backends are used together, the generic type can be chosen as the lowest common denominator between all backend output types, and implement the deserialization methods accordingly 93 | - [x] device lists are automatically refreshed when encountering a message by a device that is not cached 94 | - [x] the backend to decrypt the message with is implicitly selected by looking at the type of the message structure 95 | - [x] messages sent by devices with undecided trust are decrytped 96 | - [x] it is detectable in case the message of an undecided device was decrypted 97 | - [x] duplicate messages are not detected, that task is up to the application 98 | 99 | - [x] opt-out is not handled 100 | 101 | - [x] MUC participant list management is not provided 102 | - [x] message encryption to multiple recipients is supported though 103 | 104 | - [x] passive session initiations are automatically completed 105 | - [x] requires empty OMEMO messages 106 | 107 | - [x] message catch-up is handled 108 | - [x] methods are provided to notify the library about start and end of message catch-up 109 | - [x] the library automatically enters catch-up mode when loaded 110 | - [x] pre keys are retained during catch-up and deleted when the catch-up is done 111 | - [x] delays automated staleness prevention responses 112 | - [x] requires automatic completion of passive session initiations 113 | 114 | - [x] manual per-device session replacement is provided 115 | - [x] requires empty OMEMO messages 116 | 117 | - [x] global or per-JID session replacement is not provided 118 | 119 | - [x] own staleness is prevented 120 | - [x] received messages with a ratchet counter of 53 or higher trigger an automated response 121 | - [x] automated responses are delayed until after catch-up is done and only one message is sent per stale session afterwards 122 | - [x] requires empty OMEMO messages 123 | 124 | - [x] stale devices are not detected 125 | - [x] however, API is offered to query the sending chain length of a session, which is one important piece of information that clients might use for staleness detection 126 | 127 | - [x] account purging is supported 128 | - [x] removes all data related to a bare JID across all backends 129 | - [x] useful e.g. to remove all OMEMO-related data corresponding to an XMPP account that was blocked by the user 130 | 131 | - [x] a convenience method to get the identity key fingerprint is provided 132 | - [x] independent of the backend 133 | 134 | - [x] methods are provided to retrieve information about devices 135 | - [x] information for all devices of a bare JID can be retrieved in bulk 136 | - [x] includes device id, label, identity key, trust information, supported backends, active status 137 | - [x] independent of the backend 138 | 139 | - [x] backends can be provided for different versions of the OMEMO protocol 140 | - [x] the protocol version a backend implements is identified by its namespace 141 | 142 | - [ ] data storage has to be provided by the application 143 | - [x] an asyncio-based storage interface has to be implemented 144 | - [x] this interface transparently handles caching 145 | - [x] the interface represents generic key-value storage with opaque keys and values 146 | - [ ] automatic migrations between storage format versions are provided 147 | - [x] storage consistency is guaranteed 148 | - [x] write operations MUST NOT cache or defer but perform the writing operation right away 149 | - [x] when encrypting or decrypting, changes to the state are only persisted when success is guaranteed 150 | 151 | - [ ] a convenience method to verify consistency (and fix) of the server-side data with the local data is provided 152 | - [ ] these checks are not ran automatically, but the documentation includes a hint and examples run the checks after startup 153 | 154 | # Part of the respective backends 155 | 156 | - [x] a state migration tool/function is provided for migration from legacy python-omemo to the new storage format 157 | - [ ] a state migration tool/function is provided for migration from libsignal to python-omemo 158 | 159 | - [x] convenience functions for XML (de)serialization is provided using the ElementTree API 160 | - [x] this part is fully optional, the application may take care of (de)serialization itself 161 | - [x] installed only when doing `pip install *backend*[xml]` 162 | -------------------------------------------------------------------------------- /omemo/__init__.py: -------------------------------------------------------------------------------- 1 | from .version import __version__ as __version__ 2 | from .project import project as project 3 | 4 | from .backend import ( 5 | Backend as Backend, 6 | BackendException as BackendException, 7 | DecryptionFailed as DecryptionFailed, 8 | KeyExchangeFailed as KeyExchangeFailed, 9 | TooManySkippedMessageKeys as TooManySkippedMessageKeys 10 | ) 11 | from .bundle import Bundle as Bundle 12 | from .message import ( 13 | Content as Content, 14 | EncryptedKeyMaterial as EncryptedKeyMaterial, 15 | KeyExchange as KeyExchange, 16 | Message as Message 17 | ) 18 | 19 | from .session_manager import ( 20 | SessionManagerException as SessionManagerException, 21 | 22 | TrustDecisionFailed as TrustDecisionFailed, 23 | StillUndecided as StillUndecided, 24 | NoEligibleDevices as NoEligibleDevices, 25 | 26 | MessageNotForUs as MessageNotForUs, 27 | SenderNotFound as SenderNotFound, 28 | SenderDistrusted as SenderDistrusted, 29 | NoSession as NoSession, 30 | PublicDataInconsistency as PublicDataInconsistency, 31 | 32 | UnknownTrustLevel as UnknownTrustLevel, 33 | UnknownNamespace as UnknownNamespace, 34 | 35 | XMPPInteractionFailed as XMPPInteractionFailed, 36 | BundleUploadFailed as BundleUploadFailed, 37 | BundleDownloadFailed as BundleDownloadFailed, 38 | BundleNotFound as BundleNotFound, 39 | BundleDeletionFailed as BundleDeletionFailed, 40 | DeviceListUploadFailed as DeviceListUploadFailed, 41 | DeviceListDownloadFailed as DeviceListDownloadFailed, 42 | MessageSendingFailed as MessageSendingFailed, 43 | 44 | SessionManager as SessionManager 45 | ) 46 | 47 | from .storage import ( 48 | Just as Just, 49 | Maybe as Maybe, 50 | Nothing as Nothing, 51 | NothingException as NothingException, 52 | Storage as Storage, 53 | StorageException as StorageException 54 | ) 55 | from .types import ( 56 | AsyncFramework as AsyncFramework, 57 | DeviceInformation as DeviceInformation, 58 | JSONType as JSONType, 59 | OMEMOException as OMEMOException, 60 | TrustLevel as TrustLevel 61 | ) 62 | -------------------------------------------------------------------------------- /omemo/backend.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from typing import Optional, Tuple 3 | 4 | from .bundle import Bundle 5 | from .message import Content, EncryptedKeyMaterial, PlainKeyMaterial, KeyExchange 6 | from .session import Session 7 | from .types import OMEMOException 8 | 9 | 10 | __all__ = [ 11 | "Backend", 12 | "BackendException", 13 | "DecryptionFailed", 14 | "KeyExchangeFailed", 15 | "TooManySkippedMessageKeys" 16 | ] 17 | 18 | 19 | class BackendException(OMEMOException): 20 | """ 21 | Parent type for all exceptions specific to :class:`Backend`. 22 | """ 23 | 24 | 25 | class DecryptionFailed(BackendException): 26 | """ 27 | Raised by various methods of :class:`Backend` in case of backend-specific failures during decryption. 28 | """ 29 | 30 | 31 | class KeyExchangeFailed(BackendException): 32 | """ 33 | Raised by :meth:`Backend.build_session_active` and :meth:`Backend.build_session_passive` in case of an 34 | error during the processing of a key exchange for session building. Known error conditions are: 35 | 36 | * The bundle does not contain and pre keys (active session building) 37 | * The signature of the signed pre key could not be verified (active session building) 38 | * An unkown (signed) pre key was referred to (passive session building) 39 | 40 | Additional backend-specific error conditions might exist. 41 | """ 42 | 43 | 44 | class TooManySkippedMessageKeys(BackendException): 45 | """ 46 | Raised by :meth:`Backend.decrypt_key_material` if a message skips more message keys than allowed. 47 | """ 48 | 49 | 50 | class Backend(ABC): 51 | """ 52 | The base class for all backends. A backend is a unit providing the functionality of a certain OMEMO 53 | version to the core library. 54 | 55 | Warning: 56 | Make sure to call :meth:`__init__` from your subclass to configure per-message and per-session skipped 57 | message key DoS protection thresholds, and respect those thresholds when decrypting key material using 58 | :meth:`decrypt_key_material`. 59 | 60 | Note: 61 | Most methods can raise :class:`~omemo.storage.StorageException` in addition to those exceptions 62 | listed explicitly. 63 | 64 | Note: 65 | All usages of "identity key" in the public API refer to the public part of the identity key pair in 66 | Ed25519 format. Otherwise, "identity key pair" is explicitly used to refer to the full key pair. 67 | 68 | Note: 69 | For backend implementors: as part of your backend implementation, you are expected to subclass various 70 | abstract base classes like :class:`~omemo.session.Session`, :class:`~omemo.message.Content`, 71 | :class:`~omemo.message.PlainKeyMaterial`, :class:`~omemo.message.EncryptedKeyMaterial` and 72 | :class:`~omemo.message.KeyExchange`. Whenever any of these abstract base types appears in a method 73 | signature of the :class:`Backend` class, what's actually meant is an instance of your respective 74 | subclass. This is not correctly expressed through the type system, since I couldn't think of a clean 75 | way to do so. Adding generics for every single of these types seemed not worth the effort. For now, 76 | the recommended way to deal with this type inaccuray is to assert the types of the affected method 77 | parameters, for example:: 78 | 79 | async def store_session(self, session: Session) -> Any: 80 | assert isinstance(session, MySessionImpl) 81 | 82 | ... 83 | 84 | Doing so tells mypy how to deal with the situation. These assertions should never fail. 85 | 86 | Note: 87 | For backend implementors: you can access the identity key pair at any time via 88 | :meth:`omemo.identity_key_pair.IdentityKeyPair.get`. 89 | """ 90 | 91 | def __init__( 92 | self, 93 | max_num_per_session_skipped_keys: int = 1000, 94 | max_num_per_message_skipped_keys: Optional[int] = None 95 | ) -> None: 96 | """ 97 | Args: 98 | max_num_per_session_skipped_keys: The maximum number of skipped message keys to keep around per 99 | session. Once the maximum is reached, old message keys are deleted to make space for newer 100 | ones. Accessible via :attr:`max_num_per_session_skipped_keys`. 101 | max_num_per_message_skipped_keys: The maximum number of skipped message keys to accept in a single 102 | message. When set to ``None`` (the default), this parameter defaults to the per-session 103 | maximum (i.e. the value of the ``max_num_per_session_skipped_keys`` parameter). This parameter 104 | may only be 0 if the per-session maximum is 0, otherwise it must be a number between 1 and the 105 | per-session maximum. Accessible via :attr:`max_num_per_message_skipped_keys`. 106 | """ 107 | 108 | if max_num_per_message_skipped_keys == 0 and max_num_per_session_skipped_keys != 0: 109 | raise ValueError( 110 | "The number of allowed per-message skipped keys must be nonzero if the number of per-session" 111 | " skipped keys to keep is nonzero." 112 | ) 113 | 114 | if max_num_per_message_skipped_keys or 0 > max_num_per_session_skipped_keys: 115 | raise ValueError( 116 | "The number of allowed per-message skipped keys must not be greater than the number of" 117 | " per-session skipped keys to keep." 118 | ) 119 | 120 | self.__max_num_per_session_skipped_keys = max_num_per_session_skipped_keys 121 | self.__max_num_per_message_skipped_keys = max_num_per_session_skipped_keys if \ 122 | max_num_per_message_skipped_keys is None else max_num_per_message_skipped_keys 123 | 124 | @property 125 | def max_num_per_session_skipped_keys(self) -> int: 126 | """ 127 | Returns: 128 | The maximum number of skipped message keys to keep around per session. 129 | """ 130 | 131 | return self.__max_num_per_session_skipped_keys 132 | 133 | @property 134 | def max_num_per_message_skipped_keys(self) -> int: 135 | """ 136 | Returns: 137 | The maximum number of skipped message keys to accept in a single message. 138 | """ 139 | 140 | return self.__max_num_per_message_skipped_keys 141 | 142 | @property 143 | @abstractmethod 144 | def namespace(self) -> str: 145 | """ 146 | Returns: 147 | The namespace provided/handled by this backend implementation. 148 | """ 149 | 150 | @abstractmethod 151 | async def load_session(self, bare_jid: str, device_id: int) -> Optional[Session]: 152 | """ 153 | Args: 154 | bare_jid: The bare JID the device belongs to. 155 | device_id: The id of the device. 156 | 157 | Returns: 158 | The session associated with the device, or `None` if such a session does not exist. 159 | 160 | Warning: 161 | Multiple sessions for the same device can exist in memory, however only one session per device can 162 | exist in storage. Which one of the in-memory sessions is persisted in storage is controlled by 163 | calling the :meth:`store_session` method. 164 | """ 165 | 166 | @abstractmethod 167 | async def store_session(self, session: Session) -> None: 168 | """ 169 | Store a session, overwriting any previously stored session for the bare JID and device id this session 170 | belongs to. 171 | 172 | Args: 173 | session: The session to store. 174 | 175 | Warning: 176 | Multiple sessions for the same device can exist in memory, however only one session per device can 177 | exist in storage. Which one of the in-memory sessions is persisted in storage is controlled by 178 | calling this method. 179 | """ 180 | 181 | @abstractmethod 182 | async def build_session_active( 183 | self, 184 | bare_jid: str, 185 | device_id: int, 186 | bundle: Bundle, 187 | plain_key_material: PlainKeyMaterial 188 | ) -> Tuple[Session, EncryptedKeyMaterial]: 189 | """ 190 | Actively build a session. 191 | 192 | Args: 193 | bare_jid: The bare JID the device belongs to. 194 | device_id: The id of the device. 195 | bundle: The bundle containing the public key material of the other device required for active 196 | session building. 197 | plain_key_material: The key material to encrypt for the recipient as part of the initial key 198 | exchange/session initiation. 199 | 200 | Returns: 201 | The newly built session, the encrypted key material and the key exchange information required by 202 | the other device to complete the passive part of session building. The 203 | :attr:`~omemo.session.Session.initiation` property of the returned session must return 204 | :attr:`~omemo.session.Initiation.ACTIVE`. The :attr:`~omemo.session.Session.key_exchange` property 205 | of the returned session must return the information required by the other party to complete its 206 | part of the key exchange. 207 | 208 | Raises: 209 | KeyExchangeFailed: in case of failure related to the key exchange required for session building. 210 | 211 | Warning: 212 | This method may be called for a device which already has a session. In that case, the original 213 | session must remain in storage and must remain loadable via :meth:`load_session`. Only upon 214 | calling :meth:`store_session`, the old session must be overwritten with the new one. In summary, 215 | multiple sessions for the same device can exist in memory, while only one session per device can 216 | exist in storage, which can be controlled using the :meth:`store_session` method. 217 | """ 218 | 219 | @abstractmethod 220 | async def build_session_passive( 221 | self, 222 | bare_jid: str, 223 | device_id: int, 224 | key_exchange: KeyExchange, 225 | encrypted_key_material: EncryptedKeyMaterial 226 | ) -> Tuple[Session, PlainKeyMaterial]: 227 | """ 228 | Passively build a session. 229 | 230 | Args: 231 | bare_jid: The bare JID the device belongs to. 232 | device_id: The id of the device. 233 | key_exchange: Key exchange information for the passive session building. 234 | encrypted_key_material: The key material to decrypt as part of the initial key exchange/session 235 | initiation. 236 | 237 | Returns: 238 | The newly built session and the decrypted key material. Note that the pre key used to initiate 239 | this session must somehow be associated with the session, such that :meth:`hide_pre_key` and 240 | :meth:`delete_pre_key` can work. 241 | 242 | Raises: 243 | KeyExchangeFailed: in case of failure related to the key exchange required for session building. 244 | DecryptionFailed: in case of backend-specific failures during decryption of the initial message. 245 | 246 | Warning: 247 | This method may be called for a device which already has a session. In that case, the original 248 | session must remain in storage and must remain loadable via :meth:`load_session`. Only upon 249 | calling :meth:`store_session`, the old session must be overwritten with the new one. In summary, 250 | multiple sessions for the same device can exist in memory, while only one session per device can 251 | exist in storage, which can be controlled using the :meth:`store_session` method. 252 | """ 253 | 254 | @abstractmethod 255 | async def encrypt_plaintext(self, plaintext: bytes) -> Tuple[Content, PlainKeyMaterial]: 256 | """ 257 | Encrypt some plaintext symmetrically. 258 | 259 | Args: 260 | plaintext: The plaintext to encrypt symmetrically. 261 | 262 | Returns: 263 | The encrypted plaintext aka content, as well as the key material needed to decrypt it. 264 | """ 265 | 266 | @abstractmethod 267 | async def encrypt_empty(self) -> Tuple[Content, PlainKeyMaterial]: 268 | """ 269 | Encrypt an empty message for the sole purpose of session manangement/ratchet forwarding/key material 270 | transportation. 271 | 272 | Returns: 273 | The symmetrically encrypted empty content, and the key material needed to decrypt it. 274 | """ 275 | 276 | @abstractmethod 277 | async def encrypt_key_material( 278 | self, 279 | session: Session, 280 | plain_key_material: PlainKeyMaterial 281 | ) -> EncryptedKeyMaterial: 282 | """ 283 | Encrypt some key material asymmetrically using the session. 284 | 285 | Args: 286 | session: The session to encrypt the key material with. 287 | plain_key_material: The key material to encrypt asymmetrically for each recipient. 288 | 289 | Returns: 290 | The encrypted key material. 291 | """ 292 | 293 | @abstractmethod 294 | async def decrypt_plaintext(self, content: Content, plain_key_material: PlainKeyMaterial) -> bytes: 295 | """ 296 | Decrypt some symmetrically encrypted plaintext. 297 | 298 | Args: 299 | content: The content to decrypt. Not empty, i.e. :attr:`Content.empty` will return ``False``. 300 | plain_key_material: The key material to decrypt with. 301 | 302 | Returns: 303 | The decrypted plaintext. 304 | 305 | Raises: 306 | DecryptionFailed: in case of backend-specific failures during decryption. 307 | """ 308 | 309 | @abstractmethod 310 | async def decrypt_key_material( 311 | self, 312 | session: Session, 313 | encrypted_key_material: EncryptedKeyMaterial 314 | ) -> PlainKeyMaterial: 315 | """ 316 | Decrypt some key material asymmetrically using the session. 317 | 318 | Args: 319 | session: The session to decrypt the key material with. 320 | encrypted_key_material: The encrypted key material. 321 | 322 | Returns: 323 | The decrypted key material 324 | 325 | Raises: 326 | TooManySkippedMessageKeys: if the number of message keys skipped by this message exceeds the upper 327 | limit enforced by :attr:`max_num_per_message_skipped_keys`. 328 | DecryptionFailed: in case of backend-specific failures during decryption. 329 | 330 | Warning: 331 | Make sure to respect the values of :attr:`max_num_per_session_skipped_keys` and 332 | :attr:`max_num_per_message_skipped_keys`. 333 | 334 | Note: 335 | When the maximum number of skipped message keys for this session, given by 336 | :attr:`max_num_per_session_skipped_keys`, is exceeded, old skipped message keys are deleted to 337 | make space for new ones. 338 | """ 339 | 340 | @abstractmethod 341 | async def signed_pre_key_age(self) -> int: 342 | """ 343 | Returns: 344 | The age of the signed pre key, i.e. the time elapsed since it was last rotated, in seconds. 345 | """ 346 | 347 | @abstractmethod 348 | async def rotate_signed_pre_key(self) -> None: 349 | """ 350 | Rotate the signed pre key. Keep the old signed pre key around for one additional rotation period, i.e. 351 | until this method is called again. 352 | """ 353 | 354 | @abstractmethod 355 | async def hide_pre_key(self, session: Session) -> bool: 356 | """ 357 | Hide a pre key from the bundle returned by :meth:`get_bundle` and pre key count returned by 358 | :meth:`get_num_visible_pre_keys`, but keep the pre key for cryptographic operations. 359 | 360 | Args: 361 | session: A session that was passively built using :meth:`build_session_passive`. Use this session 362 | to identity the pre key to hide. 363 | 364 | Returns: 365 | Whether the pre key was hidden. If the pre key doesn't exist (e.g. because it has already been 366 | deleted), or was already hidden, do not throw an exception, but return `False` instead. 367 | """ 368 | 369 | @abstractmethod 370 | async def delete_pre_key(self, session: Session) -> bool: 371 | """ 372 | Delete a pre key. 373 | 374 | Args: 375 | session: A session that was passively built using :meth:`build_session_passive`. Use this session 376 | to identity the pre key to delete. 377 | 378 | Returns: 379 | Whether the pre key was deleted. If the pre key doesn't exist (e.g. because it has already been 380 | deleted), do not throw an exception, but return `False` instead. 381 | """ 382 | 383 | @abstractmethod 384 | async def delete_hidden_pre_keys(self) -> None: 385 | """ 386 | Delete all pre keys that were previously hidden using :meth:`hide_pre_key`. 387 | """ 388 | 389 | @abstractmethod 390 | async def get_num_visible_pre_keys(self) -> int: 391 | """ 392 | Returns: 393 | The number of visible pre keys available. The number returned here should match the number of pre 394 | keys included in the bundle returned by :meth:`get_bundle`. 395 | """ 396 | 397 | @abstractmethod 398 | async def generate_pre_keys(self, num_pre_keys: int) -> None: 399 | """ 400 | Generate and store pre keys. 401 | 402 | Args: 403 | num_pre_keys: The number of pre keys to generate. 404 | """ 405 | 406 | @abstractmethod 407 | async def get_bundle(self, bare_jid: str, device_id: int) -> Bundle: 408 | """ 409 | Args: 410 | bare_jid: The bare JID of this XMPP account, to be included in the bundle. 411 | device_id: The id of this device, to be included in the bundle. 412 | 413 | Returns: 414 | The bundle containing public information about the cryptographic state of this backend. 415 | 416 | Warning: 417 | Do not include pre keys hidden by :meth:`hide_pre_key` in the bundle! 418 | """ 419 | 420 | @abstractmethod 421 | async def purge(self) -> None: 422 | """ 423 | Remove all data related to this backend from the storage. 424 | """ 425 | 426 | @abstractmethod 427 | async def purge_bare_jid(self, bare_jid: str) -> None: 428 | """ 429 | Delete all data corresponding to an XMPP account. 430 | 431 | Args: 432 | bare_jid: Delete all data corresponding to this bare JID. 433 | """ 434 | -------------------------------------------------------------------------------- /omemo/bundle.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | __all__ = [ 5 | "Bundle" 6 | ] 7 | 8 | 9 | class Bundle(ABC): 10 | """ 11 | The bundle of a device, containing the cryptographic information required for active session building. 12 | 13 | Note: 14 | All usages of "identity key" in the public API refer to the public part of the identity key pair in 15 | Ed25519 format. 16 | """ 17 | 18 | @property 19 | @abstractmethod 20 | def namespace(self) -> str: 21 | pass 22 | 23 | @property 24 | @abstractmethod 25 | def bare_jid(self) -> str: 26 | pass 27 | 28 | @property 29 | @abstractmethod 30 | def device_id(self) -> int: 31 | pass 32 | 33 | @property 34 | @abstractmethod 35 | def identity_key(self) -> bytes: 36 | pass 37 | 38 | @abstractmethod 39 | def __eq__(self, other: object) -> bool: 40 | """ 41 | Check an object for equality with this Bundle instance. 42 | 43 | Args: 44 | other: The object to compare to this instance. 45 | 46 | Returns: 47 | Whether the other object is a bundle with the same contents as this instance. 48 | 49 | Note: 50 | The order in which pre keys are included in the bundles does not matter. 51 | """ 52 | 53 | @abstractmethod 54 | def __hash__(self) -> int: 55 | """ 56 | Hash this instance in a manner that is consistent with :meth:`__eq__`. 57 | 58 | Returns: 59 | An integer value representing this instance. 60 | """ 61 | -------------------------------------------------------------------------------- /omemo/identity_key_pair.py: -------------------------------------------------------------------------------- 1 | # This import from future (theoretically) enables sphinx_autodoc_typehints to handle type aliases better 2 | from __future__ import annotations 3 | 4 | from abc import ABC, abstractmethod 5 | import logging 6 | import secrets 7 | 8 | import xeddsa.bindings as xeddsa 9 | from xeddsa.bindings import Ed25519Pub, Priv, Seed 10 | 11 | from .storage import NothingException, Storage 12 | 13 | 14 | __all__ = [ 15 | "IdentityKeyPair", 16 | "IdentityKeyPairPriv", 17 | "IdentityKeyPairSeed" 18 | ] 19 | 20 | 21 | class IdentityKeyPair(ABC): 22 | """ 23 | The identity key pair associated to this device, shared by all backends. 24 | 25 | There are following requirements for the identity key pair: 26 | 27 | * It must be able to create and verify Ed25519-compatible signatures. 28 | * It must be able to perform X25519-compatible Diffie-Hellman key agreements. 29 | 30 | There are at least two different kinds of key pairs that can fulfill these requirements: Ed25519 key pairs 31 | and Curve25519 key pairs. The birational equivalence of both curves can be used to "convert" one pair to 32 | the other. 33 | 34 | Both types of key pairs share the same private key, however instead of a private key, a seed can be used 35 | which the private key is derived from using SHA-512. This is standard practice for Ed25519, where the 36 | other 32 bytes of the SHA-512 seed hash are used as a nonce during signing. If a new key pair has to be 37 | generated, this implementation generates a seed. 38 | 39 | Note: 40 | This is the only actual cryptographic functionality offered by the core library. Everything else is 41 | backend-specific. 42 | """ 43 | 44 | LOG_TAG = "omemo.core.identity_key_pair" 45 | 46 | @staticmethod 47 | async def get(storage: Storage) -> "IdentityKeyPair": 48 | """ 49 | Get the identity key pair. 50 | 51 | Args: 52 | storage: The storage for all OMEMO-related data. 53 | 54 | Returns: 55 | The identity key pair, which has either been loaded from storage or newly generated. 56 | 57 | Note: 58 | There is only one identity key pair for storage instance. All instances of this class refer to the 59 | same storage locations, thus the same data. 60 | """ 61 | 62 | logging.getLogger(IdentityKeyPair.LOG_TAG).debug(f"Creating instance from storage {storage}.") 63 | 64 | is_seed: bool 65 | key: bytes 66 | try: 67 | # Try to load both is_seed and the key. If any one of the loads fails, generate a new seed. 68 | is_seed = (await storage.load_primitive("/ikp/is_seed", bool)).from_just() 69 | key = (await storage.load_bytes("/ikp/key")).from_just() 70 | 71 | logging.getLogger(IdentityKeyPair.LOG_TAG).debug( 72 | f"Loaded identity key from storage. is_seed={is_seed}" 73 | ) 74 | except NothingException: 75 | # If there's no private key in storage, generate and store a new seed 76 | logging.getLogger(IdentityKeyPair.LOG_TAG).info("Generating identity key.") 77 | 78 | is_seed = True 79 | key = secrets.token_bytes(32) 80 | 81 | await storage.store("/ikp/is_seed", is_seed) 82 | await storage.store_bytes("/ikp/key", key) 83 | 84 | logging.getLogger(IdentityKeyPair.LOG_TAG).debug("New seed generated and stored.") 85 | 86 | logging.getLogger(IdentityKeyPair.LOG_TAG).debug("Identity key prepared.") 87 | 88 | return IdentityKeyPairSeed(key) if is_seed else IdentityKeyPairPriv(key) 89 | 90 | @property 91 | @abstractmethod 92 | def is_seed(self) -> bool: 93 | """ 94 | Returns: 95 | Whether this is a :class:`IdentityKeyPairSeed`. 96 | """ 97 | 98 | @property 99 | @abstractmethod 100 | def is_priv(self) -> bool: 101 | """ 102 | Returns: 103 | Whether this is a :class:`IdentityKeyPairPriv`. 104 | """ 105 | 106 | @abstractmethod 107 | def as_priv(self) -> "IdentityKeyPairPriv": 108 | """ 109 | Returns: 110 | An :class:`IdentityKeyPairPriv` derived from this instance (if necessary). 111 | """ 112 | 113 | @property 114 | @abstractmethod 115 | def identity_key(self) -> Ed25519Pub: 116 | """ 117 | Returns: 118 | The public part of this identity key pair, in Ed25519 format. 119 | """ 120 | 121 | 122 | class IdentityKeyPairSeed(IdentityKeyPair): 123 | """ 124 | An :class:`IdentityKeyPair` represented by a seed. 125 | """ 126 | 127 | def __init__(self, seed: Seed) -> None: 128 | """ 129 | Args: 130 | seed: The Curve25519/Ed25519 seed. 131 | """ 132 | 133 | self.__seed = seed 134 | 135 | @property 136 | def is_seed(self) -> bool: 137 | return True 138 | 139 | @property 140 | def is_priv(self) -> bool: 141 | return False 142 | 143 | def as_priv(self) -> "IdentityKeyPairPriv": 144 | return IdentityKeyPairPriv(xeddsa.seed_to_priv(self.__seed)) 145 | 146 | @property 147 | def identity_key(self) -> Ed25519Pub: 148 | return xeddsa.seed_to_ed25519_pub(self.__seed) 149 | 150 | @property 151 | def seed(self) -> Seed: 152 | """ 153 | Returns: 154 | The Curve25519/Ed25519 seed. 155 | """ 156 | 157 | return self.__seed 158 | 159 | 160 | class IdentityKeyPairPriv(IdentityKeyPair): 161 | """ 162 | An :class:`IdentityKeyPair` represented by a private key. 163 | """ 164 | 165 | def __init__(self, priv: Priv) -> None: 166 | """ 167 | Args: 168 | priv: The Curve25519/Ed25519 private key. 169 | """ 170 | 171 | self.__priv = priv 172 | 173 | @property 174 | def is_seed(self) -> bool: 175 | return False 176 | 177 | @property 178 | def is_priv(self) -> bool: 179 | return True 180 | 181 | def as_priv(self) -> "IdentityKeyPairPriv": 182 | return self 183 | 184 | @property 185 | def identity_key(self) -> Ed25519Pub: 186 | return xeddsa.priv_to_ed25519_pub(self.__priv) 187 | 188 | @property 189 | def priv(self) -> Priv: 190 | """ 191 | Returns: 192 | The Curve25519/Ed25519 private key. 193 | """ 194 | 195 | return self.__priv 196 | -------------------------------------------------------------------------------- /omemo/message.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from typing import FrozenSet, NamedTuple, Optional, Tuple 3 | 4 | 5 | __all__ = [ 6 | "Content", 7 | "EncryptedKeyMaterial", 8 | "KeyExchange", 9 | "Message", 10 | "PlainKeyMaterial" 11 | ] 12 | 13 | 14 | class Content(ABC): 15 | """ 16 | The encrypted content of an OMEMO-encrypted message. Contains for example the ciphertext, but can contain 17 | other backend-specific data that is shared between all recipients. 18 | """ 19 | 20 | @property 21 | @abstractmethod 22 | def empty(self) -> bool: 23 | """ 24 | Returns: 25 | Whether this instance corresponds to an empty OMEMO message purely used for protocol stability 26 | reasons. 27 | """ 28 | 29 | 30 | class PlainKeyMaterial(ABC): 31 | """ 32 | Key material which be used to decrypt the content. Defails are backend-specific. 33 | """ 34 | 35 | 36 | class EncryptedKeyMaterial(ABC): 37 | """ 38 | Encrypted key material. When decrypted, the key material can in turn be used to decrypt the content. One 39 | collection of key material is included in an OMEMO-encrypted message per recipient. Defails are 40 | backend-specific. 41 | """ 42 | 43 | @property 44 | @abstractmethod 45 | def bare_jid(self) -> str: 46 | pass 47 | 48 | @property 49 | @abstractmethod 50 | def device_id(self) -> int: 51 | pass 52 | 53 | 54 | class KeyExchange(ABC): 55 | """ 56 | Key exchange information, generated by the active part of the session building process, then transferred 57 | to and consumed by the passive part of the session building process. Details are backend-specific. 58 | """ 59 | 60 | @property 61 | @abstractmethod 62 | def identity_key(self) -> bytes: 63 | pass 64 | 65 | @abstractmethod 66 | def builds_same_session(self, other: "KeyExchange") -> bool: 67 | """ 68 | Args: 69 | other: The other key exchange instance to compare to this instance. 70 | 71 | Returns: 72 | Whether the key exchange information stored in this instance and the key exchange information 73 | stored in the other instance would build the same session. 74 | """ 75 | 76 | 77 | class Message(NamedTuple): 78 | # pylint: disable=invalid-name 79 | """ 80 | Simple structure representing an OMEMO-encrypted message. 81 | """ 82 | 83 | namespace: str 84 | bare_jid: str 85 | device_id: int 86 | content: Content 87 | keys: FrozenSet[Tuple[EncryptedKeyMaterial, Optional[KeyExchange]]] 88 | -------------------------------------------------------------------------------- /omemo/project.py: -------------------------------------------------------------------------------- 1 | __all__ = [ "project" ] 2 | 3 | project = { 4 | "name" : "OMEMO", 5 | "description" : "A Python implementation of the OMEMO Multi-End Message and Object Encryption protocol.", 6 | "url" : "https://github.com/Syndace/python-omemo", 7 | "year" : "2024", 8 | "author" : "Tim Henkes (Syndace)", 9 | "author_email" : "me@syndace.dev", 10 | "categories" : [ 11 | "Topic :: Communications :: Chat", 12 | "Topic :: Security :: Cryptography" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /omemo/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Syndace/python-omemo/11199154baab5862e2dedfb10769c96c767becde/omemo/py.typed -------------------------------------------------------------------------------- /omemo/session.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | import enum 3 | from typing import Optional 4 | 5 | from .message import KeyExchange 6 | 7 | 8 | __all__ = [ 9 | "Initiation", 10 | "Session" 11 | ] 12 | 13 | 14 | @enum.unique 15 | class Initiation(enum.Enum): 16 | """ 17 | Enumeration identifying whether a session was built through active or passive session initiation. 18 | """ 19 | 20 | ACTIVE: str = "ACTIVE" 21 | PASSIVE: str = "PASSIVE" 22 | 23 | 24 | class Session(ABC): 25 | """ 26 | Class representing an OMEMO session. Used to encrypt/decrypt key material for/from a single 27 | recipient/sender device in a perfectly forwared secure manner. 28 | 29 | Warning: 30 | Changes to a session may only be persisted when :meth:`~omemo.backend.Backend.store_session` is 31 | called. 32 | 33 | Warning: 34 | Multiple sessions for the same device can exist in memory, however only one session per device can 35 | exist in storage. Which one of the in-memory sessions is persisted in storage is controlled by calling 36 | the :meth:`~omemo.backend.Backend.store_session` method. 37 | 38 | Note: 39 | The API of the :class:`Session` class was intentionally kept thin. All "complex" interactions with 40 | session objects happen via methods of :class:`~omemo.backend.Backend`. This allows backend 41 | implementors to have the :class:`Session` class be a simple "stupid" data holding structure type, 42 | while all of the more complex logic is located in the implementation of the 43 | :class:`~omemo.backend.Backend` class itself. Backend implementations are obviously free to implement 44 | logic on their respective :class:`Session` implementations and forward calls to them from the 45 | :class:`~omemo.backend.Backend` methods. 46 | """ 47 | 48 | @property 49 | @abstractmethod 50 | def namespace(self) -> str: 51 | pass 52 | 53 | @property 54 | @abstractmethod 55 | def bare_jid(self) -> str: 56 | pass 57 | 58 | @property 59 | @abstractmethod 60 | def device_id(self) -> int: 61 | pass 62 | 63 | @property 64 | @abstractmethod 65 | def initiation(self) -> Initiation: 66 | """ 67 | Returns: 68 | Whether this session was actively initiated or passively. 69 | """ 70 | 71 | @property 72 | @abstractmethod 73 | def confirmed(self) -> bool: 74 | """ 75 | In case this session was built through active session initiation, this flag should indicate whether 76 | the session initiation has been "confirmed", i.e. at least one message was received and decrypted 77 | using this session. 78 | """ 79 | 80 | @property 81 | @abstractmethod 82 | def key_exchange(self) -> KeyExchange: 83 | """ 84 | Either the key exchange information received during passive session building, or the key exchange 85 | information created as part of active session building. The key exchange information is needed by the 86 | protocol for stability reasons, to make sure that all sides can build the session, even if messages 87 | are lost or received out of order. 88 | 89 | Returns: 90 | The key exchange information associated with this session. 91 | """ 92 | 93 | @property 94 | @abstractmethod 95 | def receiving_chain_length(self) -> Optional[int]: 96 | """ 97 | Returns: 98 | The length of the receiving chain, if it exists, used for own staleness detection. 99 | """ 100 | 101 | @property 102 | @abstractmethod 103 | def sending_chain_length(self) -> int: 104 | """ 105 | Returns: 106 | The length of the sending chain, used for staleness detection of other devices. 107 | """ 108 | -------------------------------------------------------------------------------- /omemo/storage.py: -------------------------------------------------------------------------------- 1 | # This import from future (theoretically) enables sphinx_autodoc_typehints to handle type aliases better 2 | from __future__ import annotations 3 | 4 | from abc import ABC, abstractmethod 5 | import base64 6 | import copy 7 | from typing import Callable, Dict, Generic, List, Optional, Type, TypeVar, Union, cast 8 | 9 | from .types import JSONType, OMEMOException 10 | 11 | 12 | __all__ = [ 13 | "Just", 14 | "Maybe", 15 | "Nothing", 16 | "NothingException", 17 | "Storage", 18 | "StorageException" 19 | ] 20 | 21 | 22 | class StorageException(OMEMOException): 23 | """ 24 | Parent type for all exceptions specifically raised by methods of :class:`Storage`. 25 | """ 26 | 27 | 28 | ValueTypeT = TypeVar("ValueTypeT") 29 | DefaultTypeT = TypeVar("DefaultTypeT") 30 | MappedValueTypeT = TypeVar("MappedValueTypeT") 31 | 32 | 33 | class Maybe(ABC, Generic[ValueTypeT]): 34 | """ 35 | typing's `Optional[A]` is just an alias for `Union[None, A]`, which means if `A` is a union itself that 36 | allows `None`, the `Optional[A]` doesn't add anything. E.g. `Optional[Optional[X]] = Optional[X]` is true 37 | for any type `X`. This Maybe class actually differenciates whether a value is set or not. 38 | 39 | All incoming and outgoing values or cloned using :func:`copy.deepcopy`, such that values stored in a Maybe 40 | instance are not affected by outside application logic. 41 | """ 42 | 43 | @property 44 | @abstractmethod 45 | def is_just(self) -> bool: 46 | """ 47 | Returns: 48 | Whether this is a :class:`Just`. 49 | """ 50 | 51 | @property 52 | @abstractmethod 53 | def is_nothing(self) -> bool: 54 | """ 55 | Returns: 56 | Whether this is a :class:`Nothing`. 57 | """ 58 | 59 | @abstractmethod 60 | def from_just(self) -> ValueTypeT: 61 | """ 62 | Returns: 63 | The value if this is a :class:`Just`. 64 | 65 | Raises: 66 | NothingException: if this is a :class:`Nothing`. 67 | """ 68 | 69 | @abstractmethod 70 | def maybe(self, default: DefaultTypeT) -> Union[ValueTypeT, DefaultTypeT]: 71 | """ 72 | Args: 73 | default: The value to return if this is in instance of :class:`Nothing`. 74 | 75 | Returns: 76 | The value if this is a :class:`Just`, or the default value if this is a :class:`Nothing`. The 77 | default is returned by reference in that case. 78 | """ 79 | 80 | @abstractmethod 81 | def fmap(self, function: Callable[[ValueTypeT], MappedValueTypeT]) -> "Maybe[MappedValueTypeT]": 82 | """ 83 | Apply a mapping function. 84 | 85 | Args: 86 | function: The mapping function. 87 | 88 | Returns: 89 | A new :class:`Just` containing the mapped value if this is a :class:`Just`. A new :class:`Nothing` 90 | if this is a :class:`Nothing`. 91 | """ 92 | 93 | 94 | class NothingException(Exception): 95 | """ 96 | Raised by :meth:`Maybe.from_just`, in case the :class:`Maybe` is a :class:`Nothing`. 97 | """ 98 | 99 | 100 | class Nothing(Maybe[ValueTypeT]): 101 | """ 102 | A :class:`Maybe` that does not hold a value. 103 | """ 104 | 105 | def __init__(self) -> None: 106 | """ 107 | Initialize a :class:`Nothing`, representing an empty :class:`Maybe`. 108 | """ 109 | 110 | @property 111 | def is_just(self) -> bool: 112 | return False 113 | 114 | @property 115 | def is_nothing(self) -> bool: 116 | return True 117 | 118 | def from_just(self) -> ValueTypeT: 119 | raise NothingException("Maybe.fromJust: Nothing") # -- yuck 120 | 121 | def maybe(self, default: DefaultTypeT) -> DefaultTypeT: 122 | return default 123 | 124 | def fmap(self, function: Callable[[ValueTypeT], MappedValueTypeT]) -> "Nothing[MappedValueTypeT]": 125 | return Nothing() 126 | 127 | 128 | class Just(Maybe[ValueTypeT]): 129 | """ 130 | A :class:`Maybe` that does hold a value. 131 | """ 132 | 133 | def __init__(self, value: ValueTypeT) -> None: 134 | """ 135 | Initialize a :class:`Just`, representing a :class:`Maybe` that holds a value. 136 | 137 | Args: 138 | value: The value to store in this :class:`Just`. 139 | """ 140 | 141 | self.__value = copy.deepcopy(value) 142 | 143 | @property 144 | def is_just(self) -> bool: 145 | return True 146 | 147 | @property 148 | def is_nothing(self) -> bool: 149 | return False 150 | 151 | def from_just(self) -> ValueTypeT: 152 | return copy.deepcopy(self.__value) 153 | 154 | def maybe(self, default: DefaultTypeT) -> ValueTypeT: 155 | return copy.deepcopy(self.__value) 156 | 157 | def fmap(self, function: Callable[[ValueTypeT], MappedValueTypeT]) -> "Just[MappedValueTypeT]": 158 | return Just(function(copy.deepcopy(self.__value))) 159 | 160 | 161 | PrimitiveTypeT = TypeVar("PrimitiveTypeT", None, float, int, str, bool) 162 | 163 | 164 | class Storage(ABC): 165 | """ 166 | A simple key/value storage class with optional caching (on by default). Keys can be any Python string, 167 | values any JSON-serializable structure. 168 | 169 | Warning: 170 | Writing (and deletion) operations must be performed right away, before returning from the method. Such 171 | operations must not be cached or otherwise deferred. 172 | 173 | Warning: 174 | All parameters must be treated as immutable unless explicitly noted otherwise. 175 | 176 | Note: 177 | The :class:`Maybe` type performs the additional job of cloning stored and returned values, which 178 | essential to decouple the cached values from the application logic. 179 | """ 180 | 181 | def __init__(self, disable_cache: bool = False): 182 | """ 183 | Configure caching behaviour of the storage. 184 | 185 | Args: 186 | disable_cache: Whether to disable the cache, which is on by default. Use this parameter if your 187 | storage implementation handles caching itself, to avoid pointless double caching. 188 | """ 189 | 190 | self.__cache: Optional[Dict[str, Maybe[JSONType]]] = None if disable_cache else {} 191 | 192 | @abstractmethod 193 | async def _load(self, key: str) -> Maybe[JSONType]: 194 | """ 195 | Load a value. 196 | 197 | Args: 198 | key: The key identifying the value. 199 | 200 | Returns: 201 | The loaded value, if it exists. 202 | 203 | Raises: 204 | StorageException: if any kind of storage operation failed. Feel free to raise a subclass instead. 205 | """ 206 | 207 | @abstractmethod 208 | async def _store(self, key: str, value: JSONType) -> None: 209 | """ 210 | Store a value. 211 | 212 | Args: 213 | key: The key identifying the value. 214 | value: The value to store under the given key. 215 | 216 | Raises: 217 | StorageException: if any kind of storage operation failed. Feel free to raise a subclass instead. 218 | """ 219 | 220 | @abstractmethod 221 | async def _delete(self, key: str) -> None: 222 | """ 223 | Delete a value, if it exists. 224 | 225 | Args: 226 | key: The key identifying the value to delete. 227 | 228 | Raises: 229 | StorageException: if any kind of storage operation failed. Feel free to raise a subclass instead. 230 | Do not raise if the key doesn't exist. 231 | """ 232 | 233 | async def load(self, key: str) -> Maybe[JSONType]: 234 | """ 235 | Load a value. 236 | 237 | Args: 238 | key: The key identifying the value. 239 | 240 | Returns: 241 | The loaded value, if it exists. 242 | 243 | Raises: 244 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_load`. 245 | """ 246 | 247 | if self.__cache is not None and key in self.__cache: 248 | return self.__cache[key] 249 | 250 | value = await self._load(key) 251 | if self.__cache is not None: 252 | self.__cache[key] = value 253 | return value 254 | 255 | async def store(self, key: str, value: JSONType) -> None: 256 | """ 257 | Store a value. 258 | 259 | Args: 260 | key: The key identifying the value. 261 | value: The value to store under the given key. 262 | 263 | Raises: 264 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_store`. 265 | """ 266 | 267 | await self._store(key, value) 268 | 269 | if self.__cache is not None: 270 | self.__cache[key] = Just(value) 271 | 272 | async def delete(self, key: str) -> None: 273 | """ 274 | Delete a value, if it exists. 275 | 276 | Args: 277 | key: The key identifying the value to delete. 278 | 279 | Raises: 280 | StorageException: if any kind of storage operation failed. Does not raise if the key doesn't 281 | exist. Forwarded from :meth:`_delete`. 282 | """ 283 | 284 | await self._delete(key) 285 | 286 | if self.__cache is not None: 287 | self.__cache[key] = Nothing() 288 | 289 | async def store_bytes(self, key: str, value: bytes) -> None: 290 | """ 291 | Variation of :meth:`store` for storing specifically bytes values. 292 | 293 | Args: 294 | key: The key identifying the value. 295 | value: The value to store under the given key. 296 | 297 | Raises: 298 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_store`. 299 | """ 300 | 301 | await self.store(key, base64.urlsafe_b64encode(value).decode("ASCII")) 302 | 303 | async def load_primitive(self, key: str, primitive: Type[PrimitiveTypeT]) -> Maybe[PrimitiveTypeT]: 304 | """ 305 | Variation of :meth:`load` for loading specifically primitive values. 306 | 307 | Args: 308 | key: The key identifying the value. 309 | primitive: The primitive type of the value. 310 | 311 | Returns: 312 | The loaded and type-checked value, if it exists. 313 | 314 | Raises: 315 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_load`. 316 | """ 317 | 318 | def check_type(value: JSONType) -> PrimitiveTypeT: 319 | if isinstance(value, primitive): 320 | return value 321 | raise TypeError(f"The value stored for key {key} is not a {primitive}: {value}") 322 | 323 | return (await self.load(key)).fmap(check_type) 324 | 325 | async def load_bytes(self, key: str) -> Maybe[bytes]: 326 | """ 327 | Variation of :meth:`load` for loading specifically bytes values. 328 | 329 | Args: 330 | key: The key identifying the value. 331 | 332 | Returns: 333 | The loaded and type-checked value, if it exists. 334 | 335 | Raises: 336 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_load`. 337 | """ 338 | 339 | def check_type(value: JSONType) -> bytes: 340 | if isinstance(value, str): 341 | return base64.urlsafe_b64decode(value.encode("ASCII")) 342 | raise TypeError(f"The value stored for key {key} is not a str/bytes: {value}") 343 | 344 | return (await self.load(key)).fmap(check_type) 345 | 346 | async def load_optional( 347 | self, 348 | key: str, 349 | primitive: Type[PrimitiveTypeT] 350 | ) -> Maybe[Optional[PrimitiveTypeT]]: 351 | """ 352 | Variation of :meth:`load` for loading specifically optional primitive values. 353 | 354 | Args: 355 | key: The key identifying the value. 356 | primitive: The primitive type of the optional value. 357 | 358 | Returns: 359 | The loaded and type-checked value, if it exists. 360 | 361 | Raises: 362 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_load`. 363 | """ 364 | 365 | def check_type(value: JSONType) -> Optional[PrimitiveTypeT]: 366 | if value is None or isinstance(value, primitive): 367 | return value 368 | raise TypeError(f"The value stored for key {key} is not an optional {primitive}: {value}") 369 | 370 | return (await self.load(key)).fmap(check_type) 371 | 372 | async def load_list(self, key: str, primitive: Type[PrimitiveTypeT]) -> Maybe[List[PrimitiveTypeT]]: 373 | """ 374 | Variation of :meth:`load` for loading specifically lists of primitive values. 375 | 376 | Args: 377 | key: The key identifying the value. 378 | primitive: The primitive type of the list elements. 379 | 380 | Returns: 381 | The loaded and type-checked value, if it exists. 382 | 383 | Raises: 384 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_load`. 385 | """ 386 | 387 | def check_type(value: JSONType) -> List[PrimitiveTypeT]: 388 | if isinstance(value, list) and all(isinstance(element, primitive) for element in value): 389 | return cast(List[PrimitiveTypeT], value) 390 | raise TypeError(f"The value stored for key {key} is not a list of {primitive}: {value}") 391 | 392 | return (await self.load(key)).fmap(check_type) 393 | 394 | async def load_dict( 395 | self, 396 | key: str, 397 | primitive: Type[PrimitiveTypeT] 398 | ) -> Maybe[Dict[str, PrimitiveTypeT]]: 399 | """ 400 | Variation of :meth:`load` for loading specifically dictionaries of primitive values. 401 | 402 | Args: 403 | key: The key identifying the value. 404 | primitive: The primitive type of the dictionary values. 405 | 406 | Returns: 407 | The loaded and type-checked value, if it exists. 408 | 409 | Raises: 410 | StorageException: if any kind of storage operation failed. Forwarded from :meth:`_load`. 411 | """ 412 | 413 | def check_type(value: JSONType) -> Dict[str, PrimitiveTypeT]: 414 | if isinstance(value, dict) and all(isinstance(v, primitive) for v in value.values()): 415 | return cast(Dict[str, PrimitiveTypeT], value) 416 | 417 | raise TypeError(f"The value stored for key {key} is not a dict of {primitive}: {value}") 418 | 419 | return (await self.load(key)).fmap(check_type) 420 | -------------------------------------------------------------------------------- /omemo/types.py: -------------------------------------------------------------------------------- 1 | # This import from future (theoretically) enables sphinx_autodoc_typehints to handle type aliases better 2 | from __future__ import annotations 3 | 4 | import enum 5 | from typing import FrozenSet, List, Mapping, NamedTuple, Optional, Tuple, Union 6 | 7 | 8 | __all__ = [ 9 | "AsyncFramework", 10 | "DeviceInformation", 11 | "JSONType", 12 | "OMEMOException", 13 | "TrustLevel" 14 | ] 15 | 16 | 17 | @enum.unique 18 | class AsyncFramework(enum.Enum): 19 | """ 20 | Frameworks for asynchronous code supported by python-omemo. 21 | """ 22 | 23 | ASYNCIO: str = "ASYNCIO" 24 | TWISTED: str = "TWISTED" 25 | 26 | 27 | class OMEMOException(Exception): 28 | """ 29 | Parent type for all custom exceptions in this library. 30 | """ 31 | 32 | 33 | class DeviceInformation(NamedTuple): 34 | # pylint: disable=invalid-name 35 | """ 36 | Structure containing information about a single OMEMO device. 37 | """ 38 | 39 | namespaces: FrozenSet[str] 40 | active: FrozenSet[Tuple[str, bool]] 41 | bare_jid: str 42 | device_id: int 43 | identity_key: bytes 44 | trust_level_name: str 45 | label: Optional[str] 46 | 47 | 48 | @enum.unique 49 | class TrustLevel(enum.Enum): 50 | """ 51 | The three core trust levels. 52 | """ 53 | 54 | TRUSTED: str = "TRUSTED" 55 | DISTRUSTED: str = "DISTRUSTED" 56 | UNDECIDED: str = "UNDECIDED" 57 | 58 | 59 | # # Thanks @vanburgerberg - https://github.com/python/typing/issues/182 60 | # if TYPE_CHECKING: 61 | # class JSONArray(list[JSONType], Protocol): # type: ignore 62 | # __class__: Type[list[JSONType]] # type: ignore 63 | # 64 | # class JSONObject(dict[str, JSONType], Protocol): # type: ignore 65 | # __class__: Type[dict[str, JSONType]] # type: ignore 66 | # 67 | # JSONType = Union[None, float, int, str, bool, JSONArray, JSONObject] 68 | 69 | # Sadly @vanburgerberg's solution doesn't seem to like Dict[str, bool], thus for now an incomplete JSON 70 | # type with finite levels of depth. 71 | Primitives = Union[None, float, int, str, bool] 72 | JSONType2 = Union[Primitives, List[Primitives], Mapping[str, Primitives]] 73 | JSONType1 = Union[Primitives, List[JSONType2], Mapping[str, JSONType2]] 74 | JSONType = Union[Primitives, List[JSONType1], Mapping[str, JSONType1]] 75 | -------------------------------------------------------------------------------- /omemo/version.py: -------------------------------------------------------------------------------- 1 | __all__ = [ "__version__" ] 2 | 3 | __version__ = {} 4 | __version__["short"] = "1.2.0" 5 | __version__["tag"] = "stable" 6 | __version__["full"] = f"{__version__['short']}-{__version__['tag']}" 7 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MAIN] 2 | 3 | # Analyse import fallback blocks. This can be used to support both Python 2 and 4 | # 3 compatible code, which means that the block might have code that exists 5 | # only in one or another interpreter, leading to false positives when analysed. 6 | analyse-fallback-blocks=yes 7 | 8 | # Clear in-memory caches upon conclusion of linting. Useful if running pylint 9 | # in a server-like mode. 10 | clear-cache-post-run=no 11 | 12 | # Load and enable all available extensions. Use --list-extensions to see a list 13 | # all available extensions. 14 | #enable-all-extensions= 15 | 16 | # In error mode, messages with a category besides ERROR or FATAL are 17 | # suppressed, and no reports are done by default. Error mode is compatible with 18 | # disabling specific errors. 19 | #errors-only= 20 | 21 | # Always return a 0 (non-error) status code, even if lint errors are found. 22 | # This is primarily useful in continuous integration scripts. 23 | #exit-zero= 24 | 25 | # A comma-separated list of package or module names from where C extensions may 26 | # be loaded. Extensions are loading into the active Python interpreter and may 27 | # run arbitrary code. 28 | extension-pkg-allow-list= 29 | 30 | # Return non-zero exit code if any of these messages/categories are detected, 31 | # even if score is above --fail-under value. Syntax same as enable. Messages 32 | # specified are enabled, while categories only check already-enabled messages. 33 | fail-on= 34 | 35 | # Specify a score threshold under which the program will exit with error. 36 | fail-under=10 37 | 38 | # Interpret the stdin as a python script, whose filename needs to be passed as 39 | # the module_or_package argument. 40 | #from-stdin= 41 | 42 | # Files or directories to be skipped. They should be base names, not paths. 43 | ignore=CVS 44 | 45 | # Add files or directories matching the regular expressions patterns to the 46 | # ignore-list. The regex matches against paths and can be in Posix or Windows 47 | # format. Because '\\' represents the directory delimiter on Windows systems, 48 | # it can't be used as an escape character. 49 | ignore-paths= 50 | 51 | # Files or directories matching the regular expression patterns are skipped. 52 | # The regex matches against base names, not paths. The default value ignores 53 | # Emacs file locks 54 | ignore-patterns= 55 | 56 | # List of module names for which member attributes should not be checked and 57 | # will not be imported (useful for modules/projects where namespaces are 58 | # manipulated during runtime and thus existing member attributes cannot be 59 | # deduced by static analysis). It supports qualified module names, as well as 60 | # Unix pattern matching. 61 | ignored-modules= 62 | 63 | # Python code to execute, usually for sys.path manipulation such as 64 | # pygtk.require(). 65 | #init-hook= 66 | 67 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 68 | # number of processors available to use, and will cap the count on Windows to 69 | # avoid hangs. 70 | jobs=1 71 | 72 | # Control the amount of potential inferred values when inferring a single 73 | # object. This can help the performance when dealing with large functions or 74 | # complex, nested conditions. 75 | limit-inference-results=100 76 | 77 | # List of plugins (as comma separated values of python module names) to load, 78 | # usually to register additional checkers. 79 | load-plugins= 80 | 81 | # Pickle collected data for later comparisons. 82 | persistent=yes 83 | 84 | # Resolve imports to .pyi stubs if available. May reduce no-member messages and 85 | # increase not-an-iterable messages. 86 | prefer-stubs=no 87 | 88 | # Minimum Python version to use for version dependent checks. Will default to 89 | # the version used to run pylint. 90 | py-version=3.9 91 | 92 | # Discover python modules and packages in the file system subtree. 93 | recursive=no 94 | 95 | # Add paths to the list of the source roots. Supports globbing patterns. The 96 | # source root is an absolute path or a path relative to the current working 97 | # directory used to determine a package namespace for modules located under the 98 | # source root. 99 | source-roots= 100 | 101 | # When enabled, pylint would attempt to guess common misconfiguration and emit 102 | # user-friendly hints instead of false-positive error messages. 103 | suggestion-mode=yes 104 | 105 | # Allow loading of arbitrary C extensions. Extensions are imported into the 106 | # active Python interpreter and may run arbitrary code. 107 | unsafe-load-any-extension=no 108 | 109 | # In verbose mode, extra non-checker-related info will be displayed. 110 | #verbose= 111 | 112 | 113 | [BASIC] 114 | 115 | # Naming style matching correct argument names. 116 | argument-naming-style=snake_case 117 | 118 | # Regular expression matching correct argument names. Overrides argument- 119 | # naming-style. If left empty, argument names will be checked with the set 120 | # naming style. 121 | #argument-rgx= 122 | 123 | # Naming style matching correct attribute names. 124 | attr-naming-style=snake_case 125 | 126 | # Regular expression matching correct attribute names. Overrides attr-naming- 127 | # style. If left empty, attribute names will be checked with the set naming 128 | # style. 129 | #attr-rgx= 130 | 131 | # Bad variable names which should always be refused, separated by a comma. 132 | bad-names=foo, 133 | bar, 134 | baz, 135 | toto, 136 | tutu, 137 | tata 138 | 139 | # Bad variable names regexes, separated by a comma. If names match any regex, 140 | # they will always be refused 141 | bad-names-rgxs= 142 | 143 | # Naming style matching correct class attribute names. 144 | class-attribute-naming-style=UPPER_CASE 145 | 146 | # Regular expression matching correct class attribute names. Overrides class- 147 | # attribute-naming-style. If left empty, class attribute names will be checked 148 | # with the set naming style. 149 | #class-attribute-rgx= 150 | 151 | # Naming style matching correct class constant names. 152 | class-const-naming-style=UPPER_CASE 153 | 154 | # Regular expression matching correct class constant names. Overrides class- 155 | # const-naming-style. If left empty, class constant names will be checked with 156 | # the set naming style. 157 | #class-const-rgx= 158 | 159 | # Naming style matching correct class names. 160 | class-naming-style=PascalCase 161 | 162 | # Regular expression matching correct class names. Overrides class-naming- 163 | # style. If left empty, class names will be checked with the set naming style. 164 | #class-rgx= 165 | 166 | # Naming style matching correct constant names. 167 | const-naming-style=any 168 | 169 | # Regular expression matching correct constant names. Overrides const-naming- 170 | # style. If left empty, constant names will be checked with the set naming 171 | # style. 172 | #const-rgx= 173 | 174 | # Minimum line length for functions/classes that require docstrings, shorter 175 | # ones are exempt. 176 | docstring-min-length=-1 177 | 178 | # Naming style matching correct function names. 179 | function-naming-style=snake_case 180 | 181 | # Regular expression matching correct function names. Overrides function- 182 | # naming-style. If left empty, function names will be checked with the set 183 | # naming style. 184 | #function-rgx= 185 | 186 | # Good variable names which should always be accepted, separated by a comma. 187 | good-names=i, 188 | j, 189 | e, # exceptions in except blocks 190 | _ 191 | 192 | # Good variable names regexes, separated by a comma. If names match any regex, 193 | # they will always be accepted 194 | good-names-rgxs= 195 | 196 | # Include a hint for the correct naming format with invalid-name. 197 | include-naming-hint=no 198 | 199 | # Naming style matching correct inline iteration names. 200 | inlinevar-naming-style=any 201 | 202 | # Regular expression matching correct inline iteration names. Overrides 203 | # inlinevar-naming-style. If left empty, inline iteration names will be checked 204 | # with the set naming style. 205 | #inlinevar-rgx= 206 | 207 | # Naming style matching correct method names. 208 | method-naming-style=snake_case 209 | 210 | # Regular expression matching correct method names. Overrides method-naming- 211 | # style. If left empty, method names will be checked with the set naming style. 212 | #method-rgx= 213 | 214 | # Naming style matching correct module names. 215 | module-naming-style=snake_case 216 | 217 | # Regular expression matching correct module names. Overrides module-naming- 218 | # style. If left empty, module names will be checked with the set naming style. 219 | #module-rgx= 220 | 221 | # Colon-delimited sets of names that determine each other's naming style when 222 | # the name regexes allow several styles. 223 | name-group= 224 | 225 | # Regular expression which should only match function or class names that do 226 | # not require a docstring. 227 | no-docstring-rgx= 228 | 229 | # List of decorators that produce properties, such as abc.abstractproperty. Add 230 | # to this list to register other decorators that produce valid properties. 231 | # These decorators are taken in consideration only for invalid-name. 232 | property-classes=abc.abstractproperty 233 | 234 | # Regular expression matching correct type alias names. If left empty, type 235 | # alias names will be checked with the set naming style. 236 | #typealias-rgx= 237 | 238 | # Regular expression matching correct type variable names. If left empty, type 239 | # variable names will be checked with the set naming style. 240 | #typevar-rgx= 241 | 242 | # Naming style matching correct variable names. 243 | variable-naming-style=snake_case 244 | 245 | # Regular expression matching correct variable names. Overrides variable- 246 | # naming-style. If left empty, variable names will be checked with the set 247 | # naming style. 248 | #variable-rgx= 249 | 250 | 251 | [CLASSES] 252 | 253 | # Warn about protected attribute access inside special methods 254 | check-protected-access-in-special-methods=no 255 | 256 | # List of method names used to declare (i.e. assign) instance attributes. 257 | defining-attr-methods=__init__, 258 | __new__, 259 | setUp, 260 | __post_init__, 261 | create 262 | 263 | # List of member names, which should be excluded from the protected access 264 | # warning. 265 | exclude-protected=_asdict, 266 | _fields, 267 | _replace, 268 | _source, 269 | _make 270 | 271 | # List of valid names for the first argument in a class method. 272 | valid-classmethod-first-arg=cls 273 | 274 | # List of valid names for the first argument in a metaclass class method. 275 | valid-metaclass-classmethod-first-arg=cls 276 | 277 | 278 | [DESIGN] 279 | 280 | # List of regular expressions of class ancestor names to ignore when counting 281 | # public methods (see R0903) 282 | exclude-too-few-public-methods= 283 | 284 | # List of qualified class names to ignore when counting class parents (see 285 | # R0901) 286 | ignored-parents= 287 | 288 | # Maximum number of arguments for function / method. 289 | max-args=100 290 | 291 | # Maximum number of attributes for a class (see R0902). 292 | max-attributes=100 293 | 294 | # Maximum number of boolean expressions in an if statement (see R0916). 295 | max-bool-expr=10 296 | 297 | # Maximum number of branch for function / method body. 298 | max-branches=100 299 | 300 | # Maximum number of locals for function / method body. 301 | max-locals=100 302 | 303 | # Maximum number of parents for a class (see R0901). 304 | max-parents=10 305 | 306 | # Maximum number of positional arguments for function / method. 307 | max-positional-arguments=100 308 | 309 | # Maximum number of public methods for a class (see R0904). 310 | max-public-methods=100 311 | 312 | # Maximum number of return / yield for function / method body. 313 | max-returns=100 314 | 315 | # Maximum number of statements in function / method body. 316 | max-statements=1000 317 | 318 | # Minimum number of public methods for a class (see R0903). 319 | min-public-methods=0 320 | 321 | 322 | [EXCEPTIONS] 323 | 324 | # Exceptions that will emit a warning when caught. 325 | overgeneral-exceptions=builtins.BaseException,builtins.Exception 326 | 327 | 328 | [FORMAT] 329 | 330 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 331 | expected-line-ending-format= 332 | 333 | # Regexp for a line that is allowed to be longer than the limit. 334 | ignore-long-lines=^\s*(# )??$ 335 | 336 | # Number of spaces of indent required inside a hanging or continued line. 337 | indent-after-paren=4 338 | 339 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 340 | # tab). 341 | indent-string=' ' 342 | 343 | # Maximum number of characters on a single line. 344 | max-line-length=110 345 | 346 | # Maximum number of lines in a module. 347 | max-module-lines=10000 348 | 349 | # Allow the body of a class to be on the same line as the declaration if body 350 | # contains single statement. 351 | single-line-class-stmt=no 352 | 353 | # Allow the body of an if to be on the same line as the test if there is no 354 | # else. 355 | single-line-if-stmt=yes 356 | 357 | 358 | [IMPORTS] 359 | 360 | # List of modules that can be imported at any level, not just the top level 361 | # one. 362 | allow-any-import-level= 363 | 364 | # Allow explicit reexports by alias from a package __init__. 365 | allow-reexport-from-package=yes 366 | 367 | # Allow wildcard imports from modules that define __all__. 368 | allow-wildcard-with-all=no 369 | 370 | # Deprecated modules which should not be used, separated by a comma. 371 | deprecated-modules=optparse,tkinter.tix 372 | 373 | # Output a graph (.gv or any supported image format) of external dependencies 374 | # to the given file (report RP0402 must not be disabled). 375 | ext-import-graph= 376 | 377 | # Output a graph (.gv or any supported image format) of all (i.e. internal and 378 | # external) dependencies to the given file (report RP0402 must not be 379 | # disabled). 380 | import-graph= 381 | 382 | # Output a graph (.gv or any supported image format) of internal dependencies 383 | # to the given file (report RP0402 must not be disabled). 384 | int-import-graph= 385 | 386 | # Force import order to recognize a module as part of the standard 387 | # compatibility libraries. 388 | known-standard-library= 389 | 390 | # Force import order to recognize a module as part of a third party library. 391 | known-third-party= 392 | 393 | # Couples of modules and preferred modules, separated by a comma. 394 | preferred-modules= 395 | 396 | 397 | [LOGGING] 398 | 399 | # The type of string formatting that logging methods do. `old` means using % 400 | # formatting, `new` is for `{}` formatting. 401 | logging-format-style=new 402 | 403 | # Logging modules to check that the string format arguments are in logging 404 | # function parameter format. 405 | logging-modules=logging 406 | 407 | 408 | [MESSAGES CONTROL] 409 | 410 | # Only show warnings with the listed confidence levels. Leave empty to show 411 | # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, 412 | # UNDEFINED. 413 | confidence=HIGH, 414 | CONTROL_FLOW, 415 | INFERENCE, 416 | INFERENCE_FAILURE, 417 | UNDEFINED 418 | 419 | # Disable the message, report, category or checker with the given id(s). You 420 | # can either give multiple identifiers separated by comma (,) or put this 421 | # option multiple times (only on the command line, not in the configuration 422 | # file where it should appear only once). You can also use "--disable=all" to 423 | # disable everything first and then re-enable specific checks. For example, if 424 | # you want to run only the similarities checker, you can use "--disable=all 425 | # --enable=similarities". If you want to run only the classes checker, but have 426 | # no Warning level messages displayed, use "--disable=all --enable=classes 427 | # --disable=W". 428 | disable=missing-module-docstring, 429 | duplicate-code, 430 | logging-fstring-interpolation 431 | 432 | # Enable the message, report, category or checker with the given id(s). You can 433 | # either give multiple identifier separated by comma (,) or put this option 434 | # multiple time (only on the command line, not in the configuration file where 435 | # it should appear only once). See also the "--disable" option for examples. 436 | enable=useless-suppression 437 | 438 | 439 | [METHOD_ARGS] 440 | 441 | # List of qualified names (i.e., library.method) which require a timeout 442 | # parameter e.g. 'requests.api.get,requests.api.post' 443 | timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request 444 | 445 | 446 | [MISCELLANEOUS] 447 | 448 | # List of note tags to take in consideration, separated by a comma. 449 | notes=FIXME, 450 | XXX, 451 | TODO 452 | 453 | # Regular expression of note tags to take in consideration. 454 | notes-rgx= 455 | 456 | 457 | [REFACTORING] 458 | 459 | # Maximum number of nested blocks for function / method body 460 | max-nested-blocks=5 461 | 462 | # Complete name of functions that never returns. When checking for 463 | # inconsistent-return-statements if a never returning function is called then 464 | # it will be considered as an explicit return statement and no message will be 465 | # printed. 466 | never-returning-functions=sys.exit 467 | 468 | # Let 'consider-using-join' be raised when the separator to join on would be 469 | # non-empty (resulting in expected fixes of the type: ``"- " + " - 470 | # ".join(items)``) 471 | suggest-join-with-non-empty-separator=yes 472 | 473 | 474 | [REPORTS] 475 | 476 | # Python expression which should return a score less than or equal to 10. You 477 | # have access to the variables 'fatal', 'error', 'warning', 'refactor', 478 | # 'convention', and 'info' which contain the number of messages in each 479 | # category, as well as 'statement' which is the total number of statements 480 | # analyzed. This score is used by the global evaluation report (RP0004). 481 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 482 | 483 | # Template used to display messages. This is a python new-style format string 484 | # used to format the message information. See doc for all details. 485 | msg-template= 486 | 487 | # Set the output format. Available formats are: text, parseable, colorized, 488 | # json2 (improved json format), json (old json format) and msvs (visual 489 | # studio). You can also give a reporter class, e.g. 490 | # mypackage.mymodule.MyReporterClass. 491 | #output-format= 492 | 493 | # Tells whether to display a full report or only the messages. 494 | reports=no 495 | 496 | # Activate the evaluation score. 497 | score=yes 498 | 499 | 500 | [SIMILARITIES] 501 | 502 | # Comments are removed from the similarity computation 503 | ignore-comments=yes 504 | 505 | # Docstrings are removed from the similarity computation 506 | ignore-docstrings=yes 507 | 508 | # Imports are removed from the similarity computation 509 | ignore-imports=no 510 | 511 | # Signatures are removed from the similarity computation 512 | ignore-signatures=yes 513 | 514 | # Minimum lines number of a similarity. 515 | min-similarity-lines=4 516 | 517 | 518 | [SPELLING] 519 | 520 | # Limits count of emitted suggestions for spelling mistakes. 521 | max-spelling-suggestions=4 522 | 523 | # Spelling dictionary name. No available dictionaries : You need to install 524 | # both the python package and the system dependency for enchant to work. 525 | spelling-dict= 526 | 527 | # List of comma separated words that should be considered directives if they 528 | # appear at the beginning of a comment and should not be checked. 529 | spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: 530 | 531 | # List of comma separated words that should not be checked. 532 | spelling-ignore-words= 533 | 534 | # A path to a file that contains the private dictionary; one word per line. 535 | spelling-private-dict-file= 536 | 537 | # Tells whether to store unknown words to the private dictionary (see the 538 | # --spelling-private-dict-file option) instead of raising a message. 539 | spelling-store-unknown-words=no 540 | 541 | 542 | [STRING] 543 | 544 | # This flag controls whether inconsistent-quotes generates a warning when the 545 | # character used as a quote delimiter is used inconsistently within a module. 546 | check-quote-consistency=no 547 | 548 | # This flag controls whether the implicit-str-concat should generate a warning 549 | # on implicit string concatenation in sequences defined over several lines. 550 | check-str-concat-over-line-jumps=no 551 | 552 | 553 | [TYPECHECK] 554 | 555 | # List of decorators that produce context managers, such as 556 | # contextlib.contextmanager. Add to this list to register other decorators that 557 | # produce valid context managers. 558 | contextmanager-decorators=contextlib.contextmanager 559 | 560 | # List of members which are set dynamically and missed by pylint inference 561 | # system, and so shouldn't trigger E1101 when accessed. Python regular 562 | # expressions are accepted. 563 | generated-members= 564 | 565 | # Tells whether to warn about missing members when the owner of the attribute 566 | # is inferred to be None. 567 | ignore-none=no 568 | 569 | # This flag controls whether pylint should warn about no-member and similar 570 | # checks whenever an opaque object is returned when inferring. The inference 571 | # can return multiple potential results while evaluating a Python object, but 572 | # some branches might not be evaluated, which results in partial inference. In 573 | # that case, it might be useful to still emit no-member and other checks for 574 | # the rest of the inferred objects. 575 | ignore-on-opaque-inference=no 576 | 577 | # List of symbolic message names to ignore for Mixin members. 578 | ignored-checks-for-mixins=no-member, 579 | not-async-context-manager, 580 | not-context-manager, 581 | attribute-defined-outside-init 582 | 583 | # List of class names for which member attributes should not be checked (useful 584 | # for classes with dynamically set attributes). This supports the use of 585 | # qualified names. 586 | ignored-classes=optparse.Values,thread._local,_thread._local 587 | 588 | # Show a hint with possible names when a member name was not found. The aspect 589 | # of finding the hint is based on edit distance. 590 | missing-member-hint=yes 591 | 592 | # The minimum edit distance a name should have in order to be considered a 593 | # similar match for a missing member name. 594 | missing-member-hint-distance=1 595 | 596 | # The total number of similar names that should be taken in consideration when 597 | # showing a hint for a missing member. 598 | missing-member-max-choices=1 599 | 600 | # Regex pattern to define which classes are considered mixins. 601 | mixin-class-rgx=.*[Mm]ixin 602 | 603 | # List of decorators that change the signature of a decorated function. 604 | signature-mutators= 605 | 606 | 607 | [VARIABLES] 608 | 609 | # List of additional names supposed to be defined in builtins. Remember that 610 | # you should avoid defining new builtins when possible. 611 | additional-builtins= 612 | 613 | # Tells whether unused global variables should be treated as a violation. 614 | allow-global-unused-variables=yes 615 | 616 | # List of names allowed to shadow builtins 617 | allowed-redefined-builtins= 618 | 619 | # List of strings which can identify a callback function by name. A callback 620 | # name must start or end with one of those strings. 621 | callbacks=cb_, 622 | _cb 623 | 624 | # A regular expression matching the name of dummy variables (i.e. expected to 625 | # not be used). 626 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 627 | 628 | # Argument names that match this expression will be ignored. 629 | ignored-argument-names=_.*|^ignored_|^unused_ 630 | 631 | # Tells whether we should check for unused import in __init__ files. 632 | init-import=no 633 | 634 | # List of qualified module names which can have objects that can redefine 635 | # builtins. 636 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 637 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ "setuptools", "wheel" ] 3 | build-backend = "setuptools.build_meta" 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | XEdDSA>=1.0.0,<2 2 | typing-extensions>=4.3.0 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=exec-used 2 | import os 3 | from typing import Dict, Union, List 4 | 5 | from setuptools import setup, find_packages # type: ignore[import-untyped] 6 | 7 | source_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "omemo") 8 | 9 | version_scope: Dict[str, Dict[str, str]] = {} 10 | with open(os.path.join(source_root, "version.py"), encoding="utf-8") as f: 11 | exec(f.read(), version_scope) 12 | version = version_scope["__version__"] 13 | 14 | project_scope: Dict[str, Dict[str, Union[str, List[str]]]] = {} 15 | with open(os.path.join(source_root, "project.py"), encoding="utf-8") as f: 16 | exec(f.read(), project_scope) 17 | project = project_scope["project"] 18 | 19 | with open("README.md", encoding="utf-8") as f: 20 | long_description = f.read() 21 | 22 | classifiers = [ 23 | "Intended Audience :: Developers", 24 | 25 | "License :: OSI Approved :: MIT License", 26 | 27 | "Programming Language :: Python :: 3", 28 | "Programming Language :: Python :: 3 :: Only", 29 | 30 | "Programming Language :: Python :: 3.9", 31 | "Programming Language :: Python :: 3.10", 32 | "Programming Language :: Python :: 3.11", 33 | "Programming Language :: Python :: 3.12", 34 | "Programming Language :: Python :: 3.13", 35 | 36 | "Programming Language :: Python :: Implementation :: CPython", 37 | "Programming Language :: Python :: Implementation :: PyPy" 38 | ] 39 | 40 | classifiers.extend(project["categories"]) 41 | 42 | if version["tag"] == "alpha": 43 | classifiers.append("Development Status :: 3 - Alpha") 44 | 45 | if version["tag"] == "beta": 46 | classifiers.append("Development Status :: 4 - Beta") 47 | 48 | if version["tag"] == "stable": 49 | classifiers.append("Development Status :: 5 - Production/Stable") 50 | 51 | del project["categories"] 52 | del project["year"] 53 | 54 | setup( 55 | version=version["short"], 56 | long_description=long_description, 57 | long_description_content_type="text/markdown", 58 | license="MIT", 59 | packages=find_packages(exclude=["tests"]), 60 | install_requires=[ 61 | "XEdDSA>=1.0.0,<2", 62 | "typing-extensions>=4.3.0" 63 | ], 64 | python_requires=">=3.9", 65 | include_package_data=True, 66 | zip_safe=False, 67 | classifiers=classifiers, 68 | **project 69 | ) 70 | -------------------------------------------------------------------------------- /tests/LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # To make relative imports work 2 | -------------------------------------------------------------------------------- /tests/data.py: -------------------------------------------------------------------------------- 1 | import twomemo 2 | import oldmemo 3 | from typing_extensions import Final 4 | 5 | 6 | __all__ = [ 7 | "NS_TWOMEMO", 8 | "NS_OLDMEMO", 9 | "ALICE_BARE_JID", 10 | "BOB_BARE_JID" 11 | ] 12 | 13 | 14 | NS_TWOMEMO: Final = twomemo.twomemo.NAMESPACE 15 | NS_OLDMEMO: Final = oldmemo.oldmemo.NAMESPACE 16 | 17 | ALICE_BARE_JID: Final = "alice@example.org" 18 | BOB_BARE_JID: Final = "bob@example.org" 19 | -------------------------------------------------------------------------------- /tests/in_memory_storage.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | import omemo 4 | 5 | 6 | __all__ = [ 7 | "InMemoryStorage" 8 | ] 9 | 10 | 11 | class InMemoryStorage(omemo.Storage): 12 | """ 13 | Volatile storage implementation with the values held in memory. 14 | """ 15 | 16 | def __init__(self) -> None: 17 | super().__init__(True) 18 | 19 | self.__storage: Dict[str, omemo.JSONType] = {} 20 | 21 | async def _load(self, key: str) -> omemo.Maybe[omemo.JSONType]: 22 | try: 23 | return omemo.Just(self.__storage[key]) 24 | except KeyError: 25 | return omemo.Nothing() 26 | 27 | async def _store(self, key: str, value: omemo.JSONType) -> None: 28 | self.__storage[key] = value 29 | 30 | async def _delete(self, key: str) -> None: 31 | self.__storage.pop(key, None) 32 | -------------------------------------------------------------------------------- /tests/session_manager_impl.py: -------------------------------------------------------------------------------- 1 | import enum 2 | from typing import Dict, FrozenSet, List, Optional, Tuple, Type 3 | 4 | from typing_extensions import NamedTuple, assert_never 5 | 6 | import omemo 7 | 8 | 9 | __all__ = [ 10 | "TrustLevel", 11 | "BundleStorageKey", 12 | "DeviceListStorageKey", 13 | "BundleStorage", 14 | "DeviceListStorage", 15 | "MessageQueue", 16 | "make_session_manager_impl" 17 | ] 18 | 19 | 20 | @enum.unique 21 | class TrustLevel(enum.Enum): 22 | """ 23 | Trust levels modeling simple manual trust. 24 | """ 25 | 26 | TRUSTED: str = "TRUSTED" 27 | UNDECIDED: str = "UNDECIDED" 28 | DISTRUSTED: str = "DISTRUSTED" 29 | 30 | 31 | class BundleStorageKey(NamedTuple): 32 | # pylint: disable=invalid-name 33 | """ 34 | The key identifying a bundle in the tests. 35 | """ 36 | 37 | namespace: str 38 | bare_jid: str 39 | device_id: int 40 | 41 | 42 | class DeviceListStorageKey(NamedTuple): 43 | # pylint: disable=invalid-name 44 | """ 45 | The key identifying a device list in the tests. 46 | """ 47 | 48 | namespace: str 49 | bare_jid: str 50 | 51 | 52 | BundleStorage = Dict[BundleStorageKey, omemo.Bundle] 53 | DeviceListStorage = Dict[DeviceListStorageKey, Dict[int, Optional[str]]] 54 | MessageQueue = List[Tuple[str, omemo.Message]] 55 | 56 | 57 | def make_session_manager_impl( 58 | own_bare_jid: str, 59 | bundle_storage: BundleStorage, 60 | device_list_storage: DeviceListStorage, 61 | message_queue: MessageQueue 62 | ) -> Type[omemo.SessionManager]: 63 | """ 64 | Args: 65 | own_bare_jid: The bare JID of the account that will be used with the session manager instances created 66 | from this implementation. 67 | bundle_storage: The dictionary to "upload", "download" and delete bundles to/from. 68 | device_list_storage: The dictionary to "upload" and "download" device lists to/from. 69 | message_queue: The list to "send" automated messages to. The first entry of each tuple is the bare JID 70 | of the recipient. The second entry is the message itself. 71 | 72 | Returns: 73 | A session manager implementation which sends/uploads/downloads/deletes data to/from the collections 74 | given as parameters. 75 | """ 76 | 77 | class SessionManagerImpl(omemo.SessionManager): 78 | @staticmethod 79 | async def _upload_bundle(bundle: omemo.Bundle) -> None: 80 | bundle_storage[BundleStorageKey( 81 | namespace=bundle.namespace, 82 | bare_jid=bundle.bare_jid, 83 | device_id=bundle.device_id 84 | )] = bundle 85 | 86 | @staticmethod 87 | async def _download_bundle(namespace: str, bare_jid: str, device_id: int) -> omemo.Bundle: 88 | try: 89 | return bundle_storage[BundleStorageKey( 90 | namespace=namespace, 91 | bare_jid=bare_jid, 92 | device_id=device_id 93 | )] 94 | except KeyError as e: 95 | raise omemo.BundleDownloadFailed() from e 96 | 97 | @staticmethod 98 | async def _delete_bundle(namespace: str, device_id: int) -> None: 99 | try: 100 | bundle_storage.pop(BundleStorageKey( 101 | namespace=namespace, 102 | bare_jid=own_bare_jid, 103 | device_id=device_id 104 | )) 105 | except KeyError as e: 106 | raise omemo.BundleDeletionFailed() from e 107 | 108 | @staticmethod 109 | async def _upload_device_list(namespace: str, device_list: Dict[int, Optional[str]]) -> None: 110 | device_list_storage[DeviceListStorageKey( 111 | namespace=namespace, 112 | bare_jid=own_bare_jid 113 | )] = device_list 114 | 115 | @staticmethod 116 | async def _download_device_list(namespace: str, bare_jid: str) -> Dict[int, Optional[str]]: 117 | try: 118 | return device_list_storage[DeviceListStorageKey( 119 | namespace=namespace, 120 | bare_jid=bare_jid 121 | )] 122 | except KeyError: 123 | return {} 124 | 125 | async def _evaluate_custom_trust_level(self, device: omemo.DeviceInformation) -> omemo.TrustLevel: 126 | try: 127 | trust_level = TrustLevel(device.trust_level_name) 128 | except ValueError as e: 129 | raise omemo.UnknownTrustLevel() from e 130 | 131 | if trust_level is TrustLevel.TRUSTED: 132 | return omemo.TrustLevel.TRUSTED 133 | if trust_level is TrustLevel.UNDECIDED: 134 | return omemo.TrustLevel.UNDECIDED 135 | if trust_level is TrustLevel.DISTRUSTED: 136 | return omemo.TrustLevel.DISTRUSTED 137 | 138 | assert_never(trust_level) 139 | 140 | async def _make_trust_decision( 141 | self, 142 | undecided: FrozenSet[omemo.DeviceInformation], 143 | identifier: Optional[str] 144 | ) -> None: 145 | for device in undecided: 146 | await self.set_trust(device.bare_jid, device.identity_key, TrustLevel.TRUSTED.name) 147 | 148 | @staticmethod 149 | async def _send_message(message: omemo.Message, bare_jid: str) -> None: 150 | message_queue.append((bare_jid, message)) 151 | 152 | return SessionManagerImpl 153 | -------------------------------------------------------------------------------- /tests/test_session_manager.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | import xml.etree.ElementTree as ET 3 | 4 | import oldmemo 5 | import oldmemo.etree 6 | from oldmemo.migrations import migrate 7 | import twomemo 8 | import twomemo.etree 9 | import pytest 10 | 11 | from .data import NS_TWOMEMO, NS_OLDMEMO, ALICE_BARE_JID, BOB_BARE_JID 12 | from .in_memory_storage import InMemoryStorage 13 | from .migration import POST_MIGRATION_TEST_MESSAGE, LegacyStorageImpl, download_bundle 14 | from .session_manager_impl import \ 15 | BundleStorage, DeviceListStorage, MessageQueue, TrustLevel, make_session_manager_impl 16 | 17 | 18 | __all__ = [ 19 | "test_regression0", 20 | "test_oldmemo_migration" 21 | ] 22 | 23 | 24 | pytestmark = pytest.mark.asyncio 25 | 26 | 27 | async def test_regression0() -> None: 28 | """ 29 | Test a specific scenario that caused trouble during Libervia's JET plugin implementation. 30 | """ 31 | 32 | bundle_storage: BundleStorage = {} 33 | device_list_storage: DeviceListStorage = {} 34 | 35 | alice_message_queue: MessageQueue = [] 36 | bob_message_queue: MessageQueue = [] 37 | 38 | AliceSessionManagerImpl = make_session_manager_impl( 39 | ALICE_BARE_JID, 40 | bundle_storage, 41 | device_list_storage, 42 | alice_message_queue 43 | ) 44 | 45 | BobSessionManagerImpl = make_session_manager_impl( 46 | BOB_BARE_JID, 47 | bundle_storage, 48 | device_list_storage, 49 | bob_message_queue 50 | ) 51 | 52 | alice_storage = InMemoryStorage() 53 | bob_storage = InMemoryStorage() 54 | 55 | # Create a session manager for each party 56 | alice_session_manager = await AliceSessionManagerImpl.create( 57 | backends=[ twomemo.Twomemo(alice_storage), oldmemo.Oldmemo(alice_storage) ], 58 | storage=alice_storage, 59 | own_bare_jid=ALICE_BARE_JID, 60 | initial_own_label=None, 61 | undecided_trust_level_name=TrustLevel.UNDECIDED.name 62 | ) 63 | 64 | bob_session_manager = await BobSessionManagerImpl.create( 65 | backends=[ twomemo.Twomemo(bob_storage), oldmemo.Oldmemo(bob_storage) ], 66 | storage=bob_storage, 67 | own_bare_jid=BOB_BARE_JID, 68 | initial_own_label=None, 69 | undecided_trust_level_name=TrustLevel.UNDECIDED.name 70 | ) 71 | 72 | # Exit history synchronization mode 73 | await alice_session_manager.after_history_sync() 74 | await bob_session_manager.after_history_sync() 75 | 76 | # Ask both parties to refresh the device lists of the other party 77 | await alice_session_manager.refresh_device_list(NS_TWOMEMO, BOB_BARE_JID) 78 | await alice_session_manager.refresh_device_list(NS_OLDMEMO, BOB_BARE_JID) 79 | 80 | await bob_session_manager.refresh_device_list(NS_TWOMEMO, ALICE_BARE_JID) 81 | await bob_session_manager.refresh_device_list(NS_OLDMEMO, ALICE_BARE_JID) 82 | 83 | # Have Alice encrypt an initial message to Bob to set up sessions between them 84 | for namespace in [ NS_TWOMEMO, NS_OLDMEMO ]: 85 | messages, encryption_errors = await alice_session_manager.encrypt( 86 | bare_jids=frozenset({ BOB_BARE_JID }), 87 | plaintext={ namespace: b"Hello, Bob!" }, 88 | backend_priority_order=[ namespace ] 89 | ) 90 | 91 | assert len(messages) == 1 92 | assert len(encryption_errors) == 0 93 | 94 | # Have Bob decrypt the message 95 | message = next(iter(messages.keys())) 96 | 97 | plaintext, _, _ = await bob_session_manager.decrypt(message) 98 | assert plaintext == b"Hello, Bob!" 99 | 100 | # Bob should now have an empty message for Alice in his message queue 101 | assert len(bob_message_queue) == 1 102 | bob_queued_message_recipient, bob_queued_message = bob_message_queue.pop() 103 | assert bob_queued_message_recipient == ALICE_BARE_JID 104 | 105 | # Have Alice decrypt the empty message to complete the session intiation 106 | plaintext, _, _ = await alice_session_manager.decrypt(bob_queued_message) 107 | assert plaintext is None 108 | 109 | # The part that caused trouble in the Libervia JET plugin implementation was an attempt at sending an 110 | # oldmemo KeyTransportElement. 32 zero-bytes were used as the plaintext, and the payload was manually 111 | # removed from the serialized XML. This test tests that scenario with both twomemo and oldmemo. 112 | for namespace in [ NS_TWOMEMO, NS_OLDMEMO ]: 113 | messages, encryption_errors = await alice_session_manager.encrypt( 114 | bare_jids=frozenset({ BOB_BARE_JID }), 115 | plaintext={ namespace: b"\x00" * 32 }, 116 | backend_priority_order=[ namespace ] 117 | ) 118 | 119 | assert len(messages) == 1 120 | assert len(encryption_errors) == 0 121 | 122 | message = next(iter(messages.keys())) 123 | 124 | # Serialize the message to XML, remove the payload, and parse it again 125 | encrypted_elt: Optional[ET.Element] = None 126 | if namespace == NS_TWOMEMO: 127 | encrypted_elt = twomemo.etree.serialize_message(message) 128 | if namespace == NS_OLDMEMO: 129 | encrypted_elt = oldmemo.etree.serialize_message(message) 130 | assert encrypted_elt is not None 131 | 132 | for payload_elt in encrypted_elt.findall(f"{{{namespace}}}payload"): 133 | encrypted_elt.remove(payload_elt) 134 | 135 | if namespace == NS_TWOMEMO: 136 | message = twomemo.etree.parse_message(encrypted_elt, ALICE_BARE_JID) 137 | if namespace == NS_OLDMEMO: 138 | message = await oldmemo.etree.parse_message( 139 | encrypted_elt, 140 | ALICE_BARE_JID, 141 | BOB_BARE_JID, 142 | bob_session_manager 143 | ) 144 | 145 | # Decrypt the message on Bob's side 146 | plaintext, _, _ = await bob_session_manager.decrypt(message) 147 | assert plaintext is None 148 | 149 | # At this point, communication between both parties was broken. Try to send two messages back and forth. 150 | for namespace in [ NS_TWOMEMO, NS_OLDMEMO ]: 151 | messages, encryption_errors = await alice_session_manager.encrypt( 152 | bare_jids=frozenset({ BOB_BARE_JID }), 153 | plaintext={ namespace: b"Hello again, Bob!" }, 154 | backend_priority_order=[ namespace ] 155 | ) 156 | assert len(messages) == 1 157 | assert len(encryption_errors) == 0 158 | plaintext, _, _ = await bob_session_manager.decrypt(next(iter(messages.keys()))) 159 | assert plaintext == b"Hello again, Bob!" 160 | 161 | messages, encryption_errors = await bob_session_manager.encrypt( 162 | bare_jids=frozenset({ ALICE_BARE_JID }), 163 | plaintext={ namespace: b"Hello back, Alice!" }, 164 | backend_priority_order=[ namespace ] 165 | ) 166 | assert len(messages) == 1 167 | assert len(encryption_errors) == 0 168 | plaintext, _, _ = await alice_session_manager.decrypt(next(iter(messages.keys()))) 169 | assert plaintext == b"Hello back, Alice!" 170 | 171 | 172 | async def test_oldmemo_migration() -> None: 173 | """ 174 | Tests the migration of the legacy storage format, which is provided by python-oldmemo. 175 | """ 176 | 177 | bundle_storage: BundleStorage = {} 178 | device_list_storage: DeviceListStorage = {} 179 | message_queue: MessageQueue = [] 180 | 181 | SessionManagerImpl = make_session_manager_impl( 182 | ALICE_BARE_JID, 183 | bundle_storage, 184 | device_list_storage, 185 | message_queue 186 | ) 187 | 188 | legacy_storage = LegacyStorageImpl() 189 | storage = InMemoryStorage() 190 | 191 | await migrate( 192 | legacy_storage=legacy_storage, 193 | storage=storage, 194 | trusted_trust_level_name=TrustLevel.TRUSTED.name, 195 | undecided_trust_level_name=TrustLevel.UNDECIDED.name, 196 | untrusted_trust_level_name=TrustLevel.DISTRUSTED.name, 197 | download_bundle=download_bundle 198 | ) 199 | 200 | session_manager = await SessionManagerImpl.create( 201 | backends=[ oldmemo.Oldmemo(storage) ], 202 | storage=storage, 203 | own_bare_jid=ALICE_BARE_JID, 204 | initial_own_label=None, 205 | undecided_trust_level_name=TrustLevel.UNDECIDED.name 206 | ) 207 | 208 | await session_manager.after_history_sync() 209 | 210 | message = await oldmemo.etree.parse_message( 211 | ET.fromstring(POST_MIGRATION_TEST_MESSAGE), 212 | BOB_BARE_JID, 213 | ALICE_BARE_JID, 214 | session_manager 215 | ) 216 | 217 | plaintext, _, _ = await session_manager.decrypt(message) 218 | 219 | assert plaintext == b"This is a test message" 220 | --------------------------------------------------------------------------------