1
0

test_appservice.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import os
  16. import tempfile
  17. from unittest.mock import Mock
  18. import yaml
  19. from twisted.internet import defer
  20. from synapse.appservice import ApplicationService, ApplicationServiceState
  21. from synapse.config._base import ConfigError
  22. from synapse.storage.database import DatabasePool, make_conn
  23. from synapse.storage.databases.main.appservice import (
  24. ApplicationServiceStore,
  25. ApplicationServiceTransactionStore,
  26. )
  27. from tests import unittest
  28. from tests.test_utils import make_awaitable
  29. from tests.utils import setup_test_homeserver
  30. class ApplicationServiceStoreTestCase(unittest.TestCase):
  31. @defer.inlineCallbacks
  32. def setUp(self):
  33. self.as_yaml_files = []
  34. hs = yield setup_test_homeserver(
  35. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  36. )
  37. hs.config.appservice.app_service_config_files = self.as_yaml_files
  38. hs.config.caches.event_cache_size = 1
  39. self.as_token = "token1"
  40. self.as_url = "some_url"
  41. self.as_id = "as1"
  42. self._add_appservice(
  43. self.as_token, self.as_id, self.as_url, "some_hs_token", "bob"
  44. )
  45. self._add_appservice("token2", "as2", "some_url", "some_hs_token", "bob")
  46. self._add_appservice("token3", "as3", "some_url", "some_hs_token", "bob")
  47. # must be done after inserts
  48. database = hs.get_datastores().databases[0]
  49. self.store = ApplicationServiceStore(
  50. database, make_conn(database._database_config, database.engine, "test"), hs
  51. )
  52. def tearDown(self):
  53. # TODO: suboptimal that we need to create files for tests!
  54. for f in self.as_yaml_files:
  55. try:
  56. os.remove(f)
  57. except Exception:
  58. pass
  59. def _add_appservice(self, as_token, id, url, hs_token, sender):
  60. as_yaml = {
  61. "url": url,
  62. "as_token": as_token,
  63. "hs_token": hs_token,
  64. "id": id,
  65. "sender_localpart": sender,
  66. "namespaces": {},
  67. }
  68. # use the token as the filename
  69. with open(as_token, "w") as outfile:
  70. outfile.write(yaml.dump(as_yaml))
  71. self.as_yaml_files.append(as_token)
  72. def test_retrieve_unknown_service_token(self):
  73. service = self.store.get_app_service_by_token("invalid_token")
  74. self.assertEquals(service, None)
  75. def test_retrieval_of_service(self):
  76. stored_service = self.store.get_app_service_by_token(self.as_token)
  77. self.assertEquals(stored_service.token, self.as_token)
  78. self.assertEquals(stored_service.id, self.as_id)
  79. self.assertEquals(stored_service.url, self.as_url)
  80. self.assertEquals(stored_service.namespaces[ApplicationService.NS_ALIASES], [])
  81. self.assertEquals(stored_service.namespaces[ApplicationService.NS_ROOMS], [])
  82. self.assertEquals(stored_service.namespaces[ApplicationService.NS_USERS], [])
  83. def test_retrieval_of_all_services(self):
  84. services = self.store.get_app_services()
  85. self.assertEquals(len(services), 3)
  86. class ApplicationServiceTransactionStoreTestCase(unittest.TestCase):
  87. @defer.inlineCallbacks
  88. def setUp(self):
  89. self.as_yaml_files = []
  90. hs = yield setup_test_homeserver(
  91. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  92. )
  93. hs.config.appservice.app_service_config_files = self.as_yaml_files
  94. hs.config.caches.event_cache_size = 1
  95. self.as_list = [
  96. {"token": "token1", "url": "https://matrix-as.org", "id": "id_1"},
  97. {"token": "alpha_tok", "url": "https://alpha.com", "id": "id_alpha"},
  98. {"token": "beta_tok", "url": "https://beta.com", "id": "id_beta"},
  99. {"token": "gamma_tok", "url": "https://gamma.com", "id": "id_gamma"},
  100. ]
  101. for s in self.as_list:
  102. yield self._add_service(s["url"], s["token"], s["id"])
  103. self.as_yaml_files = []
  104. # We assume there is only one database in these tests
  105. database = hs.get_datastores().databases[0]
  106. self.db_pool = database._db_pool
  107. self.engine = database.engine
  108. db_config = hs.config.database.get_single_database()
  109. self.store = TestTransactionStore(
  110. database, make_conn(db_config, self.engine, "test"), hs
  111. )
  112. def _add_service(self, url, as_token, id):
  113. as_yaml = {
  114. "url": url,
  115. "as_token": as_token,
  116. "hs_token": "something",
  117. "id": id,
  118. "sender_localpart": "a_sender",
  119. "namespaces": {},
  120. }
  121. # use the token as the filename
  122. with open(as_token, "w") as outfile:
  123. outfile.write(yaml.dump(as_yaml))
  124. self.as_yaml_files.append(as_token)
  125. def _set_state(self, id, state, txn=None):
  126. return self.db_pool.runOperation(
  127. self.engine.convert_param_style(
  128. "INSERT INTO application_services_state(as_id, state, last_txn) "
  129. "VALUES(?,?,?)"
  130. ),
  131. (id, state, txn),
  132. )
  133. def _insert_txn(self, as_id, txn_id, events):
  134. return self.db_pool.runOperation(
  135. self.engine.convert_param_style(
  136. "INSERT INTO application_services_txns(as_id, txn_id, event_ids) "
  137. "VALUES(?,?,?)"
  138. ),
  139. (as_id, txn_id, json.dumps([e.event_id for e in events])),
  140. )
  141. def _set_last_txn(self, as_id, txn_id):
  142. return self.db_pool.runOperation(
  143. self.engine.convert_param_style(
  144. "INSERT INTO application_services_state(as_id, last_txn, state) "
  145. "VALUES(?,?,?)"
  146. ),
  147. (as_id, txn_id, ApplicationServiceState.UP),
  148. )
  149. @defer.inlineCallbacks
  150. def test_get_appservice_state_none(self):
  151. service = Mock(id="999")
  152. state = yield defer.ensureDeferred(self.store.get_appservice_state(service))
  153. self.assertEquals(None, state)
  154. @defer.inlineCallbacks
  155. def test_get_appservice_state_up(self):
  156. yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
  157. service = Mock(id=self.as_list[0]["id"])
  158. state = yield defer.ensureDeferred(self.store.get_appservice_state(service))
  159. self.assertEquals(ApplicationServiceState.UP, state)
  160. @defer.inlineCallbacks
  161. def test_get_appservice_state_down(self):
  162. yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
  163. yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.DOWN)
  164. yield self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
  165. service = Mock(id=self.as_list[1]["id"])
  166. state = yield defer.ensureDeferred(self.store.get_appservice_state(service))
  167. self.assertEquals(ApplicationServiceState.DOWN, state)
  168. @defer.inlineCallbacks
  169. def test_get_appservices_by_state_none(self):
  170. services = yield defer.ensureDeferred(
  171. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  172. )
  173. self.assertEquals(0, len(services))
  174. @defer.inlineCallbacks
  175. def test_set_appservices_state_down(self):
  176. service = Mock(id=self.as_list[1]["id"])
  177. yield defer.ensureDeferred(
  178. self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  179. )
  180. rows = yield self.db_pool.runQuery(
  181. self.engine.convert_param_style(
  182. "SELECT as_id FROM application_services_state WHERE state=?"
  183. ),
  184. (ApplicationServiceState.DOWN,),
  185. )
  186. self.assertEquals(service.id, rows[0][0])
  187. @defer.inlineCallbacks
  188. def test_set_appservices_state_multiple_up(self):
  189. service = Mock(id=self.as_list[1]["id"])
  190. yield defer.ensureDeferred(
  191. self.store.set_appservice_state(service, ApplicationServiceState.UP)
  192. )
  193. yield defer.ensureDeferred(
  194. self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  195. )
  196. yield defer.ensureDeferred(
  197. self.store.set_appservice_state(service, ApplicationServiceState.UP)
  198. )
  199. rows = yield self.db_pool.runQuery(
  200. self.engine.convert_param_style(
  201. "SELECT as_id FROM application_services_state WHERE state=?"
  202. ),
  203. (ApplicationServiceState.UP,),
  204. )
  205. self.assertEquals(service.id, rows[0][0])
  206. @defer.inlineCallbacks
  207. def test_create_appservice_txn_first(self):
  208. service = Mock(id=self.as_list[0]["id"])
  209. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  210. txn = yield defer.ensureDeferred(
  211. self.store.create_appservice_txn(service, events, [])
  212. )
  213. self.assertEquals(txn.id, 1)
  214. self.assertEquals(txn.events, events)
  215. self.assertEquals(txn.service, service)
  216. @defer.inlineCallbacks
  217. def test_create_appservice_txn_older_last_txn(self):
  218. service = Mock(id=self.as_list[0]["id"])
  219. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  220. yield self._set_last_txn(service.id, 9643) # AS is falling behind
  221. yield self._insert_txn(service.id, 9644, events)
  222. yield self._insert_txn(service.id, 9645, events)
  223. txn = yield defer.ensureDeferred(
  224. self.store.create_appservice_txn(service, events, [])
  225. )
  226. self.assertEquals(txn.id, 9646)
  227. self.assertEquals(txn.events, events)
  228. self.assertEquals(txn.service, service)
  229. @defer.inlineCallbacks
  230. def test_create_appservice_txn_up_to_date_last_txn(self):
  231. service = Mock(id=self.as_list[0]["id"])
  232. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  233. yield self._set_last_txn(service.id, 9643)
  234. txn = yield defer.ensureDeferred(
  235. self.store.create_appservice_txn(service, events, [])
  236. )
  237. self.assertEquals(txn.id, 9644)
  238. self.assertEquals(txn.events, events)
  239. self.assertEquals(txn.service, service)
  240. @defer.inlineCallbacks
  241. def test_create_appservice_txn_up_fuzzing(self):
  242. service = Mock(id=self.as_list[0]["id"])
  243. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  244. yield self._set_last_txn(service.id, 9643)
  245. # dump in rows with higher IDs to make sure the queries aren't wrong.
  246. yield self._set_last_txn(self.as_list[1]["id"], 119643)
  247. yield self._set_last_txn(self.as_list[2]["id"], 9)
  248. yield self._set_last_txn(self.as_list[3]["id"], 9643)
  249. yield self._insert_txn(self.as_list[1]["id"], 119644, events)
  250. yield self._insert_txn(self.as_list[1]["id"], 119645, events)
  251. yield self._insert_txn(self.as_list[1]["id"], 119646, events)
  252. yield self._insert_txn(self.as_list[2]["id"], 10, events)
  253. yield self._insert_txn(self.as_list[3]["id"], 9643, events)
  254. txn = yield defer.ensureDeferred(
  255. self.store.create_appservice_txn(service, events, [])
  256. )
  257. self.assertEquals(txn.id, 9644)
  258. self.assertEquals(txn.events, events)
  259. self.assertEquals(txn.service, service)
  260. @defer.inlineCallbacks
  261. def test_complete_appservice_txn_first_txn(self):
  262. service = Mock(id=self.as_list[0]["id"])
  263. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  264. txn_id = 1
  265. yield self._insert_txn(service.id, txn_id, events)
  266. yield defer.ensureDeferred(
  267. self.store.complete_appservice_txn(txn_id=txn_id, service=service)
  268. )
  269. res = yield self.db_pool.runQuery(
  270. self.engine.convert_param_style(
  271. "SELECT last_txn FROM application_services_state WHERE as_id=?"
  272. ),
  273. (service.id,),
  274. )
  275. self.assertEquals(1, len(res))
  276. self.assertEquals(txn_id, res[0][0])
  277. res = yield self.db_pool.runQuery(
  278. self.engine.convert_param_style(
  279. "SELECT * FROM application_services_txns WHERE txn_id=?"
  280. ),
  281. (txn_id,),
  282. )
  283. self.assertEquals(0, len(res))
  284. @defer.inlineCallbacks
  285. def test_complete_appservice_txn_existing_in_state_table(self):
  286. service = Mock(id=self.as_list[0]["id"])
  287. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  288. txn_id = 5
  289. yield self._set_last_txn(service.id, 4)
  290. yield self._insert_txn(service.id, txn_id, events)
  291. yield defer.ensureDeferred(
  292. self.store.complete_appservice_txn(txn_id=txn_id, service=service)
  293. )
  294. res = yield self.db_pool.runQuery(
  295. self.engine.convert_param_style(
  296. "SELECT last_txn, state FROM application_services_state WHERE as_id=?"
  297. ),
  298. (service.id,),
  299. )
  300. self.assertEquals(1, len(res))
  301. self.assertEquals(txn_id, res[0][0])
  302. self.assertEquals(ApplicationServiceState.UP, res[0][1])
  303. res = yield self.db_pool.runQuery(
  304. self.engine.convert_param_style(
  305. "SELECT * FROM application_services_txns WHERE txn_id=?"
  306. ),
  307. (txn_id,),
  308. )
  309. self.assertEquals(0, len(res))
  310. @defer.inlineCallbacks
  311. def test_get_oldest_unsent_txn_none(self):
  312. service = Mock(id=self.as_list[0]["id"])
  313. txn = yield defer.ensureDeferred(self.store.get_oldest_unsent_txn(service))
  314. self.assertEquals(None, txn)
  315. @defer.inlineCallbacks
  316. def test_get_oldest_unsent_txn(self):
  317. service = Mock(id=self.as_list[0]["id"])
  318. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  319. other_events = [Mock(event_id="e5"), Mock(event_id="e6")]
  320. # we aren't testing store._base stuff here, so mock this out
  321. self.store.get_events_as_list = Mock(return_value=make_awaitable(events))
  322. yield self._insert_txn(self.as_list[1]["id"], 9, other_events)
  323. yield self._insert_txn(service.id, 10, events)
  324. yield self._insert_txn(service.id, 11, other_events)
  325. yield self._insert_txn(service.id, 12, other_events)
  326. txn = yield defer.ensureDeferred(self.store.get_oldest_unsent_txn(service))
  327. self.assertEquals(service, txn.service)
  328. self.assertEquals(10, txn.id)
  329. self.assertEquals(events, txn.events)
  330. @defer.inlineCallbacks
  331. def test_get_appservices_by_state_single(self):
  332. yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
  333. yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
  334. services = yield defer.ensureDeferred(
  335. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  336. )
  337. self.assertEquals(1, len(services))
  338. self.assertEquals(self.as_list[0]["id"], services[0].id)
  339. @defer.inlineCallbacks
  340. def test_get_appservices_by_state_multiple(self):
  341. yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
  342. yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
  343. yield self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
  344. yield self._set_state(self.as_list[3]["id"], ApplicationServiceState.UP)
  345. services = yield defer.ensureDeferred(
  346. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  347. )
  348. self.assertEquals(2, len(services))
  349. self.assertEquals(
  350. {self.as_list[2]["id"], self.as_list[0]["id"]},
  351. {services[0].id, services[1].id},
  352. )
  353. class ApplicationServiceStoreTypeStreamIds(unittest.HomeserverTestCase):
  354. def make_homeserver(self, reactor, clock):
  355. hs = self.setup_test_homeserver()
  356. return hs
  357. def prepare(self, hs, reactor, clock):
  358. self.service = Mock(id="foo")
  359. self.store = self.hs.get_datastore()
  360. self.get_success(self.store.set_appservice_state(self.service, "up"))
  361. def test_get_type_stream_id_for_appservice_no_value(self):
  362. value = self.get_success(
  363. self.store.get_type_stream_id_for_appservice(self.service, "read_receipt")
  364. )
  365. self.assertEquals(value, 0)
  366. value = self.get_success(
  367. self.store.get_type_stream_id_for_appservice(self.service, "presence")
  368. )
  369. self.assertEquals(value, 0)
  370. def test_get_type_stream_id_for_appservice_invalid_type(self):
  371. self.get_failure(
  372. self.store.get_type_stream_id_for_appservice(self.service, "foobar"),
  373. ValueError,
  374. )
  375. def test_set_type_stream_id_for_appservice(self):
  376. read_receipt_value = 1024
  377. self.get_success(
  378. self.store.set_type_stream_id_for_appservice(
  379. self.service, "read_receipt", read_receipt_value
  380. )
  381. )
  382. result = self.get_success(
  383. self.store.get_type_stream_id_for_appservice(self.service, "read_receipt")
  384. )
  385. self.assertEqual(result, read_receipt_value)
  386. self.get_success(
  387. self.store.set_type_stream_id_for_appservice(
  388. self.service, "presence", read_receipt_value
  389. )
  390. )
  391. result = self.get_success(
  392. self.store.get_type_stream_id_for_appservice(self.service, "presence")
  393. )
  394. self.assertEqual(result, read_receipt_value)
  395. def test_set_type_stream_id_for_appservice_invalid_type(self):
  396. self.get_failure(
  397. self.store.set_type_stream_id_for_appservice(self.service, "foobar", 1024),
  398. ValueError,
  399. )
  400. # required for ApplicationServiceTransactionStoreTestCase tests
  401. class TestTransactionStore(ApplicationServiceTransactionStore, ApplicationServiceStore):
  402. def __init__(self, database: DatabasePool, db_conn, hs):
  403. super().__init__(database, db_conn, hs)
  404. class ApplicationServiceStoreConfigTestCase(unittest.TestCase):
  405. def _write_config(self, suffix, **kwargs):
  406. vals = {
  407. "id": "id" + suffix,
  408. "url": "url" + suffix,
  409. "as_token": "as_token" + suffix,
  410. "hs_token": "hs_token" + suffix,
  411. "sender_localpart": "sender_localpart" + suffix,
  412. "namespaces": {},
  413. }
  414. vals.update(kwargs)
  415. _, path = tempfile.mkstemp(prefix="as_config")
  416. with open(path, "w") as f:
  417. f.write(yaml.dump(vals))
  418. return path
  419. @defer.inlineCallbacks
  420. def test_unique_works(self):
  421. f1 = self._write_config(suffix="1")
  422. f2 = self._write_config(suffix="2")
  423. hs = yield setup_test_homeserver(
  424. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  425. )
  426. hs.config.appservice.app_service_config_files = [f1, f2]
  427. hs.config.caches.event_cache_size = 1
  428. database = hs.get_datastores().databases[0]
  429. ApplicationServiceStore(
  430. database, make_conn(database._database_config, database.engine, "test"), hs
  431. )
  432. @defer.inlineCallbacks
  433. def test_duplicate_ids(self):
  434. f1 = self._write_config(id="id", suffix="1")
  435. f2 = self._write_config(id="id", suffix="2")
  436. hs = yield setup_test_homeserver(
  437. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  438. )
  439. hs.config.appservice.app_service_config_files = [f1, f2]
  440. hs.config.caches.event_cache_size = 1
  441. with self.assertRaises(ConfigError) as cm:
  442. database = hs.get_datastores().databases[0]
  443. ApplicationServiceStore(
  444. database,
  445. make_conn(database._database_config, database.engine, "test"),
  446. hs,
  447. )
  448. e = cm.exception
  449. self.assertIn(f1, str(e))
  450. self.assertIn(f2, str(e))
  451. self.assertIn("id", str(e))
  452. @defer.inlineCallbacks
  453. def test_duplicate_as_tokens(self):
  454. f1 = self._write_config(as_token="as_token", suffix="1")
  455. f2 = self._write_config(as_token="as_token", suffix="2")
  456. hs = yield setup_test_homeserver(
  457. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  458. )
  459. hs.config.appservice.app_service_config_files = [f1, f2]
  460. hs.config.caches.event_cache_size = 1
  461. with self.assertRaises(ConfigError) as cm:
  462. database = hs.get_datastores().databases[0]
  463. ApplicationServiceStore(
  464. database,
  465. make_conn(database._database_config, database.engine, "test"),
  466. hs,
  467. )
  468. e = cm.exception
  469. self.assertIn(f1, str(e))
  470. self.assertIn(f2, str(e))
  471. self.assertIn("as_token", str(e))