File: test_session_manager.py

package info (click to toggle)
python-omemo 2.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 660 kB
  • sloc: python: 3,523; makefile: 16
file content (224 lines) | stat: -rw-r--r-- 8,029 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from typing import Optional
import xml.etree.ElementTree as ET

import oldmemo
import oldmemo.etree
from oldmemo.migrations import migrate
import twomemo
import twomemo.etree
import pytest

from .data import NS_TWOMEMO, NS_OLDMEMO, ALICE_BARE_JID, BOB_BARE_JID
from .in_memory_storage import InMemoryStorage
from .migration import POST_MIGRATION_TEST_MESSAGE, LegacyStorageImpl, download_bundle
from .session_manager_impl import \
    BundleStorage, DeviceListStorage, MessageQueue, TrustLevel, make_session_manager_impl


__all__ = [
    "test_regression0",
    "test_oldmemo_migration"
]


pytestmark = pytest.mark.asyncio


async def test_regression0() -> None:
    """
    Test a specific scenario that caused trouble during Libervia's JET plugin implementation.
    """

    bundle_storage: BundleStorage = {}
    device_list_storage: DeviceListStorage = {}

    alice_message_queue: MessageQueue = []
    bob_message_queue: MessageQueue = []

    AliceSessionManagerImpl = make_session_manager_impl(
        ALICE_BARE_JID,
        bundle_storage,
        device_list_storage,
        alice_message_queue
    )

    BobSessionManagerImpl = make_session_manager_impl(
        BOB_BARE_JID,
        bundle_storage,
        device_list_storage,
        bob_message_queue
    )

    alice_storage = InMemoryStorage()
    bob_storage = InMemoryStorage()

    # Create a session manager for each party
    alice_session_manager = await AliceSessionManagerImpl.create(
        backends=[ twomemo.Twomemo(alice_storage), oldmemo.Oldmemo(alice_storage) ],
        storage=alice_storage,
        own_bare_jid=ALICE_BARE_JID,
        initial_own_label=None,
        undecided_trust_level_name=TrustLevel.UNDECIDED.name
    )

    bob_session_manager = await BobSessionManagerImpl.create(
        backends=[ twomemo.Twomemo(bob_storage), oldmemo.Oldmemo(bob_storage) ],
        storage=bob_storage,
        own_bare_jid=BOB_BARE_JID,
        initial_own_label=None,
        undecided_trust_level_name=TrustLevel.UNDECIDED.name
    )

    # Exit history synchronization mode
    await alice_session_manager.after_history_sync()
    await bob_session_manager.after_history_sync()

    # Ask both parties to refresh the device lists of the other party
    await alice_session_manager.refresh_device_list(NS_TWOMEMO, BOB_BARE_JID)
    await alice_session_manager.refresh_device_list(NS_OLDMEMO, BOB_BARE_JID)

    await bob_session_manager.refresh_device_list(NS_TWOMEMO, ALICE_BARE_JID)
    await bob_session_manager.refresh_device_list(NS_OLDMEMO, ALICE_BARE_JID)

    # Have Alice encrypt an initial message to Bob to set up sessions between them
    for namespace in [ NS_TWOMEMO, NS_OLDMEMO ]:
        messages, encryption_errors = await alice_session_manager.encrypt(
            bare_jids=frozenset({ BOB_BARE_JID }),
            plaintext={ namespace: b"Hello, Bob!" },
            backend_priority_order=[ namespace ]
        )

        assert len(messages) == 1
        assert len(encryption_errors) == 0

        # Have Bob decrypt the message
        message = next(iter(messages.keys()))

        plaintext, _, _ = await bob_session_manager.decrypt(message)
        assert plaintext == b"Hello, Bob!"

        # Bob should now have an empty message for Alice in his message queue
        assert len(bob_message_queue) == 1
        bob_queued_message_recipient, bob_queued_message = bob_message_queue.pop()
        assert bob_queued_message_recipient == ALICE_BARE_JID

        # Have Alice decrypt the empty message to complete the session intiation
        plaintext, _, _ = await alice_session_manager.decrypt(bob_queued_message)
        assert plaintext is None

    # The part that caused trouble in the Libervia JET plugin implementation was an attempt at sending an
    # oldmemo KeyTransportElement. 32 zero-bytes were used as the plaintext, and the payload was manually
    # removed from the serialized XML. This test tests that scenario with both twomemo and oldmemo.
    for namespace in [ NS_TWOMEMO, NS_OLDMEMO ]:
        messages, encryption_errors = await alice_session_manager.encrypt(
            bare_jids=frozenset({ BOB_BARE_JID }),
            plaintext={ namespace: b"\x00" * 32 },
            backend_priority_order=[ namespace ]
        )

        assert len(messages) == 1
        assert len(encryption_errors) == 0

        message = next(iter(messages.keys()))

        # Serialize the message to XML, remove the payload, and parse it again
        encrypted_elt: Optional[ET.Element] = None
        if namespace == NS_TWOMEMO:
            encrypted_elt = twomemo.etree.serialize_message(message)
        if namespace == NS_OLDMEMO:
            encrypted_elt = oldmemo.etree.serialize_message(message)
        assert encrypted_elt is not None

        for payload_elt in encrypted_elt.findall(f"{{{namespace}}}payload"):
            encrypted_elt.remove(payload_elt)

        if namespace == NS_TWOMEMO:
            message = twomemo.etree.parse_message(encrypted_elt, ALICE_BARE_JID)
        if namespace == NS_OLDMEMO:
            message = await oldmemo.etree.parse_message(
                encrypted_elt,
                ALICE_BARE_JID,
                BOB_BARE_JID,
                bob_session_manager
            )

        # Decrypt the message on Bob's side
        plaintext, _, _ = await bob_session_manager.decrypt(message)
        assert plaintext is None

    # At this point, communication between both parties was broken. Try to send two messages back and forth.
    for namespace in [ NS_TWOMEMO, NS_OLDMEMO ]:
        messages, encryption_errors = await alice_session_manager.encrypt(
            bare_jids=frozenset({ BOB_BARE_JID }),
            plaintext={ namespace: b"Hello again, Bob!" },
            backend_priority_order=[ namespace ]
        )
        assert len(messages) == 1
        assert len(encryption_errors) == 0
        plaintext, _, _ = await bob_session_manager.decrypt(next(iter(messages.keys())))
        assert plaintext == b"Hello again, Bob!"

        messages, encryption_errors = await bob_session_manager.encrypt(
            bare_jids=frozenset({ ALICE_BARE_JID }),
            plaintext={ namespace: b"Hello back, Alice!" },
            backend_priority_order=[ namespace ]
        )
        assert len(messages) == 1
        assert len(encryption_errors) == 0
        plaintext, _, _ = await alice_session_manager.decrypt(next(iter(messages.keys())))
        assert plaintext == b"Hello back, Alice!"

    await alice_session_manager.shutdown()
    await bob_session_manager.shutdown()


async def test_oldmemo_migration() -> None:
    """
    Tests the migration of the legacy storage format, which is provided by python-oldmemo.
    """

    bundle_storage: BundleStorage = {}
    device_list_storage: DeviceListStorage = {}
    message_queue: MessageQueue = []

    SessionManagerImpl = make_session_manager_impl(
        ALICE_BARE_JID,
        bundle_storage,
        device_list_storage,
        message_queue
    )

    legacy_storage = LegacyStorageImpl()
    storage = InMemoryStorage()

    await migrate(
        legacy_storage=legacy_storage,
        storage=storage,
        trusted_trust_level_name=TrustLevel.TRUSTED.name,
        undecided_trust_level_name=TrustLevel.UNDECIDED.name,
        untrusted_trust_level_name=TrustLevel.DISTRUSTED.name,
        download_bundle=download_bundle
    )

    session_manager = await SessionManagerImpl.create(
        backends=[ oldmemo.Oldmemo(storage) ],
        storage=storage,
        own_bare_jid=ALICE_BARE_JID,
        initial_own_label=None,
        undecided_trust_level_name=TrustLevel.UNDECIDED.name
    )

    await session_manager.after_history_sync()

    message = await oldmemo.etree.parse_message(
        ET.fromstring(POST_MIGRATION_TEST_MESSAGE),
        BOB_BARE_JID,
        ALICE_BARE_JID,
        session_manager
    )

    plaintext, _, _ = await session_manager.decrypt(message)

    assert plaintext == b"This is a test message"

    await session_manager.shutdown()