test_appservice.py 17 KB

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