summary refs log tree commit diff
path: root/tests/storage/test_appservice.py
blob: ef296e7dab141038ed6076256bfcefe8ca2153e9 (plain) (blame)
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import tempfile

from mock import Mock

import yaml

from twisted.internet import defer

from synapse.appservice import ApplicationService, ApplicationServiceState
from synapse.config._base import ConfigError
from synapse.storage.data_stores.main.appservice import (
    ApplicationServiceStore,
    ApplicationServiceTransactionStore,
)
from synapse.storage.database import Database, make_conn

from tests import unittest
from tests.utils import setup_test_homeserver


class ApplicationServiceStoreTestCase(unittest.TestCase):
    @defer.inlineCallbacks
    def setUp(self):
        self.as_yaml_files = []
        hs = yield setup_test_homeserver(
            self.addCleanup, federation_sender=Mock(), federation_client=Mock()
        )

        hs.config.app_service_config_files = self.as_yaml_files
        hs.config.caches.event_cache_size = 1
        hs.config.password_providers = []

        self.as_token = "token1"
        self.as_url = "some_url"
        self.as_id = "as1"
        self._add_appservice(
            self.as_token, self.as_id, self.as_url, "some_hs_token", "bob"
        )
        self._add_appservice("token2", "as2", "some_url", "some_hs_token", "bob")
        self._add_appservice("token3", "as3", "some_url", "some_hs_token", "bob")
        # must be done after inserts
        database = hs.get_datastores().databases[0]
        self.store = ApplicationServiceStore(
            database, make_conn(database._database_config, database.engine), hs
        )

    def tearDown(self):
        # TODO: suboptimal that we need to create files for tests!
        for f in self.as_yaml_files:
            try:
                os.remove(f)
            except Exception:
                pass

    def _add_appservice(self, as_token, id, url, hs_token, sender):
        as_yaml = {
            "url": url,
            "as_token": as_token,
            "hs_token": hs_token,
            "id": id,
            "sender_localpart": sender,
            "namespaces": {},
        }
        # use the token as the filename
        with open(as_token, "w") as outfile:
            outfile.write(yaml.dump(as_yaml))
            self.as_yaml_files.append(as_token)

    def test_retrieve_unknown_service_token(self):
        service = self.store.get_app_service_by_token("invalid_token")
        self.assertEquals(service, None)

    def test_retrieval_of_service(self):
        stored_service = self.store.get_app_service_by_token(self.as_token)
        self.assertEquals(stored_service.token, self.as_token)
        self.assertEquals(stored_service.id, self.as_id)
        self.assertEquals(stored_service.url, self.as_url)
        self.assertEquals(stored_service.namespaces[ApplicationService.NS_ALIASES], [])
        self.assertEquals(stored_service.namespaces[ApplicationService.NS_ROOMS], [])
        self.assertEquals(stored_service.namespaces[ApplicationService.NS_USERS], [])

    def test_retrieval_of_all_services(self):
        services = self.store.get_app_services()
        self.assertEquals(len(services), 3)


class ApplicationServiceTransactionStoreTestCase(unittest.TestCase):
    @defer.inlineCallbacks
    def setUp(self):
        self.as_yaml_files = []

        hs = yield setup_test_homeserver(
            self.addCleanup, federation_sender=Mock(), federation_client=Mock()
        )

        hs.config.app_service_config_files = self.as_yaml_files
        hs.config.caches.event_cache_size = 1
        hs.config.password_providers = []

        self.as_list = [
            {"token": "token1", "url": "https://matrix-as.org", "id": "id_1"},
            {"token": "alpha_tok", "url": "https://alpha.com", "id": "id_alpha"},
            {"token": "beta_tok", "url": "https://beta.com", "id": "id_beta"},
            {"token": "gamma_tok", "url": "https://gamma.com", "id": "id_gamma"},
        ]
        for s in self.as_list:
            yield self._add_service(s["url"], s["token"], s["id"])

        self.as_yaml_files = []

        # We assume there is only one database in these tests
        database = hs.get_datastores().databases[0]
        self.db_pool = database._db_pool
        self.engine = database.engine

        db_config = hs.config.get_single_database()
        self.store = TestTransactionStore(
            database, make_conn(db_config, self.engine), hs
        )

    def _add_service(self, url, as_token, id):
        as_yaml = {
            "url": url,
            "as_token": as_token,
            "hs_token": "something",
            "id": id,
            "sender_localpart": "a_sender",
            "namespaces": {},
        }
        # use the token as the filename
        with open(as_token, "w") as outfile:
            outfile.write(yaml.dump(as_yaml))
            self.as_yaml_files.append(as_token)

    def _set_state(self, id, state, txn=None):
        return self.db_pool.runOperation(
            self.engine.convert_param_style(
                "INSERT INTO application_services_state(as_id, state, last_txn) "
                "VALUES(?,?,?)"
            ),
            (id, state, txn),
        )

    def _insert_txn(self, as_id, txn_id, events):
        return self.db_pool.runOperation(
            self.engine.convert_param_style(
                "INSERT INTO application_services_txns(as_id, txn_id, event_ids) "
                "VALUES(?,?,?)"
            ),
            (as_id, txn_id, json.dumps([e.event_id for e in events])),
        )

    def _set_last_txn(self, as_id, txn_id):
        return self.db_pool.runOperation(
            self.engine.convert_param_style(
                "INSERT INTO application_services_state(as_id, last_txn, state) "
                "VALUES(?,?,?)"
            ),
            (as_id, txn_id, ApplicationServiceState.UP),
        )

    @defer.inlineCallbacks
    def test_get_appservice_state_none(self):
        service = Mock(id="999")
        state = yield self.store.get_appservice_state(service)
        self.assertEquals(None, state)

    @defer.inlineCallbacks
    def test_get_appservice_state_up(self):
        yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
        service = Mock(id=self.as_list[0]["id"])
        state = yield self.store.get_appservice_state(service)
        self.assertEquals(ApplicationServiceState.UP, state)

    @defer.inlineCallbacks
    def test_get_appservice_state_down(self):
        yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
        yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.DOWN)
        yield self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
        service = Mock(id=self.as_list[1]["id"])
        state = yield self.store.get_appservice_state(service)
        self.assertEquals(ApplicationServiceState.DOWN, state)

    @defer.inlineCallbacks
    def test_get_appservices_by_state_none(self):
        services = yield self.store.get_appservices_by_state(
            ApplicationServiceState.DOWN
        )
        self.assertEquals(0, len(services))

    @defer.inlineCallbacks
    def test_set_appservices_state_down(self):
        service = Mock(id=self.as_list[1]["id"])
        yield self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
        rows = yield self.db_pool.runQuery(
            self.engine.convert_param_style(
                "SELECT as_id FROM application_services_state WHERE state=?"
            ),
            (ApplicationServiceState.DOWN,),
        )
        self.assertEquals(service.id, rows[0][0])

    @defer.inlineCallbacks
    def test_set_appservices_state_multiple_up(self):
        service = Mock(id=self.as_list[1]["id"])
        yield self.store.set_appservice_state(service, ApplicationServiceState.UP)
        yield self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
        yield self.store.set_appservice_state(service, ApplicationServiceState.UP)
        rows = yield self.db_pool.runQuery(
            self.engine.convert_param_style(
                "SELECT as_id FROM application_services_state WHERE state=?"
            ),
            (ApplicationServiceState.UP,),
        )
        self.assertEquals(service.id, rows[0][0])

    @defer.inlineCallbacks
    def test_create_appservice_txn_first(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        txn = yield self.store.create_appservice_txn(service, events)
        self.assertEquals(txn.id, 1)
        self.assertEquals(txn.events, events)
        self.assertEquals(txn.service, service)

    @defer.inlineCallbacks
    def test_create_appservice_txn_older_last_txn(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        yield self._set_last_txn(service.id, 9643)  # AS is falling behind
        yield self._insert_txn(service.id, 9644, events)
        yield self._insert_txn(service.id, 9645, events)
        txn = yield self.store.create_appservice_txn(service, events)
        self.assertEquals(txn.id, 9646)
        self.assertEquals(txn.events, events)
        self.assertEquals(txn.service, service)

    @defer.inlineCallbacks
    def test_create_appservice_txn_up_to_date_last_txn(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        yield self._set_last_txn(service.id, 9643)
        txn = yield self.store.create_appservice_txn(service, events)
        self.assertEquals(txn.id, 9644)
        self.assertEquals(txn.events, events)
        self.assertEquals(txn.service, service)

    @defer.inlineCallbacks
    def test_create_appservice_txn_up_fuzzing(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        yield self._set_last_txn(service.id, 9643)

        # dump in rows with higher IDs to make sure the queries aren't wrong.
        yield self._set_last_txn(self.as_list[1]["id"], 119643)
        yield self._set_last_txn(self.as_list[2]["id"], 9)
        yield self._set_last_txn(self.as_list[3]["id"], 9643)
        yield self._insert_txn(self.as_list[1]["id"], 119644, events)
        yield self._insert_txn(self.as_list[1]["id"], 119645, events)
        yield self._insert_txn(self.as_list[1]["id"], 119646, events)
        yield self._insert_txn(self.as_list[2]["id"], 10, events)
        yield self._insert_txn(self.as_list[3]["id"], 9643, events)

        txn = yield self.store.create_appservice_txn(service, events)
        self.assertEquals(txn.id, 9644)
        self.assertEquals(txn.events, events)
        self.assertEquals(txn.service, service)

    @defer.inlineCallbacks
    def test_complete_appservice_txn_first_txn(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        txn_id = 1

        yield self._insert_txn(service.id, txn_id, events)
        yield self.store.complete_appservice_txn(txn_id=txn_id, service=service)

        res = yield self.db_pool.runQuery(
            self.engine.convert_param_style(
                "SELECT last_txn FROM application_services_state WHERE as_id=?"
            ),
            (service.id,),
        )
        self.assertEquals(1, len(res))
        self.assertEquals(txn_id, res[0][0])

        res = yield self.db_pool.runQuery(
            self.engine.convert_param_style(
                "SELECT * FROM application_services_txns WHERE txn_id=?"
            ),
            (txn_id,),
        )
        self.assertEquals(0, len(res))

    @defer.inlineCallbacks
    def test_complete_appservice_txn_existing_in_state_table(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        txn_id = 5
        yield self._set_last_txn(service.id, 4)
        yield self._insert_txn(service.id, txn_id, events)
        yield self.store.complete_appservice_txn(txn_id=txn_id, service=service)

        res = yield self.db_pool.runQuery(
            self.engine.convert_param_style(
                "SELECT last_txn, state FROM application_services_state WHERE as_id=?"
            ),
            (service.id,),
        )
        self.assertEquals(1, len(res))
        self.assertEquals(txn_id, res[0][0])
        self.assertEquals(ApplicationServiceState.UP, res[0][1])

        res = yield self.db_pool.runQuery(
            self.engine.convert_param_style(
                "SELECT * FROM application_services_txns WHERE txn_id=?"
            ),
            (txn_id,),
        )
        self.assertEquals(0, len(res))

    @defer.inlineCallbacks
    def test_get_oldest_unsent_txn_none(self):
        service = Mock(id=self.as_list[0]["id"])

        txn = yield self.store.get_oldest_unsent_txn(service)
        self.assertEquals(None, txn)

    @defer.inlineCallbacks
    def test_get_oldest_unsent_txn(self):
        service = Mock(id=self.as_list[0]["id"])
        events = [Mock(event_id="e1"), Mock(event_id="e2")]
        other_events = [Mock(event_id="e5"), Mock(event_id="e6")]

        # we aren't testing store._base stuff here, so mock this out
        self.store.get_events_as_list = Mock(return_value=events)

        yield self._insert_txn(self.as_list[1]["id"], 9, other_events)
        yield self._insert_txn(service.id, 10, events)
        yield self._insert_txn(service.id, 11, other_events)
        yield self._insert_txn(service.id, 12, other_events)

        txn = yield self.store.get_oldest_unsent_txn(service)
        self.assertEquals(service, txn.service)
        self.assertEquals(10, txn.id)
        self.assertEquals(events, txn.events)

    @defer.inlineCallbacks
    def test_get_appservices_by_state_single(self):
        yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
        yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)

        services = yield self.store.get_appservices_by_state(
            ApplicationServiceState.DOWN
        )
        self.assertEquals(1, len(services))
        self.assertEquals(self.as_list[0]["id"], services[0].id)

    @defer.inlineCallbacks
    def test_get_appservices_by_state_multiple(self):
        yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
        yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
        yield self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
        yield self._set_state(self.as_list[3]["id"], ApplicationServiceState.UP)

        services = yield self.store.get_appservices_by_state(
            ApplicationServiceState.DOWN
        )
        self.assertEquals(2, len(services))
        self.assertEquals(
            {self.as_list[2]["id"], self.as_list[0]["id"]},
            {services[0].id, services[1].id},
        )


# required for ApplicationServiceTransactionStoreTestCase tests
class TestTransactionStore(ApplicationServiceTransactionStore, ApplicationServiceStore):
    def __init__(self, database: Database, db_conn, hs):
        super(TestTransactionStore, self).__init__(database, db_conn, hs)


class ApplicationServiceStoreConfigTestCase(unittest.TestCase):
    def _write_config(self, suffix, **kwargs):
        vals = {
            "id": "id" + suffix,
            "url": "url" + suffix,
            "as_token": "as_token" + suffix,
            "hs_token": "hs_token" + suffix,
            "sender_localpart": "sender_localpart" + suffix,
            "namespaces": {},
        }
        vals.update(kwargs)

        _, path = tempfile.mkstemp(prefix="as_config")
        with open(path, "w") as f:
            f.write(yaml.dump(vals))
        return path

    @defer.inlineCallbacks
    def test_unique_works(self):
        f1 = self._write_config(suffix="1")
        f2 = self._write_config(suffix="2")

        hs = yield setup_test_homeserver(
            self.addCleanup, federation_sender=Mock(), federation_client=Mock()
        )

        hs.config.app_service_config_files = [f1, f2]
        hs.config.caches.event_cache_size = 1
        hs.config.password_providers = []

        database = hs.get_datastores().databases[0]
        ApplicationServiceStore(
            database, make_conn(database._database_config, database.engine), hs
        )

    @defer.inlineCallbacks
    def test_duplicate_ids(self):
        f1 = self._write_config(id="id", suffix="1")
        f2 = self._write_config(id="id", suffix="2")

        hs = yield setup_test_homeserver(
            self.addCleanup, federation_sender=Mock(), federation_client=Mock()
        )

        hs.config.app_service_config_files = [f1, f2]
        hs.config.caches.event_cache_size = 1
        hs.config.password_providers = []

        with self.assertRaises(ConfigError) as cm:
            database = hs.get_datastores().databases[0]
            ApplicationServiceStore(
                database, make_conn(database._database_config, database.engine), hs
            )

        e = cm.exception
        self.assertIn(f1, str(e))
        self.assertIn(f2, str(e))
        self.assertIn("id", str(e))

    @defer.inlineCallbacks
    def test_duplicate_as_tokens(self):
        f1 = self._write_config(as_token="as_token", suffix="1")
        f2 = self._write_config(as_token="as_token", suffix="2")

        hs = yield setup_test_homeserver(
            self.addCleanup, federation_sender=Mock(), federation_client=Mock()
        )

        hs.config.app_service_config_files = [f1, f2]
        hs.config.caches.event_cache_size = 1
        hs.config.password_providers = []

        with self.assertRaises(ConfigError) as cm:
            database = hs.get_datastores().databases[0]
            ApplicationServiceStore(
                database, make_conn(database._database_config, database.engine), hs
            )

        e = cm.exception
        self.assertIn(f1, str(e))
        self.assertIn(f2, str(e))
        self.assertIn("as_token", str(e))