test_appservice.py 18 KB

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