test_appservice.py 19 KB

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