test_appservice.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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.app_service_config_files = self.as_yaml_files
  38. hs.config.caches.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, "test"), 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.caches.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, "test"), 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 defer.ensureDeferred(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 defer.ensureDeferred(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 defer.ensureDeferred(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 defer.ensureDeferred(
  173. self.store.get_appservices_by_state(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 defer.ensureDeferred(
  180. self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  181. )
  182. rows = yield self.db_pool.runQuery(
  183. self.engine.convert_param_style(
  184. "SELECT as_id FROM application_services_state WHERE state=?"
  185. ),
  186. (ApplicationServiceState.DOWN,),
  187. )
  188. self.assertEquals(service.id, rows[0][0])
  189. @defer.inlineCallbacks
  190. def test_set_appservices_state_multiple_up(self):
  191. service = Mock(id=self.as_list[1]["id"])
  192. yield defer.ensureDeferred(
  193. self.store.set_appservice_state(service, ApplicationServiceState.UP)
  194. )
  195. yield defer.ensureDeferred(
  196. self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  197. )
  198. yield defer.ensureDeferred(
  199. self.store.set_appservice_state(service, ApplicationServiceState.UP)
  200. )
  201. rows = yield self.db_pool.runQuery(
  202. self.engine.convert_param_style(
  203. "SELECT as_id FROM application_services_state WHERE state=?"
  204. ),
  205. (ApplicationServiceState.UP,),
  206. )
  207. self.assertEquals(service.id, rows[0][0])
  208. @defer.inlineCallbacks
  209. def test_create_appservice_txn_first(self):
  210. service = Mock(id=self.as_list[0]["id"])
  211. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  212. txn = yield defer.ensureDeferred(
  213. self.store.create_appservice_txn(service, events, [])
  214. )
  215. self.assertEquals(txn.id, 1)
  216. self.assertEquals(txn.events, events)
  217. self.assertEquals(txn.service, service)
  218. @defer.inlineCallbacks
  219. def test_create_appservice_txn_older_last_txn(self):
  220. service = Mock(id=self.as_list[0]["id"])
  221. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  222. yield self._set_last_txn(service.id, 9643) # AS is falling behind
  223. yield self._insert_txn(service.id, 9644, events)
  224. yield self._insert_txn(service.id, 9645, events)
  225. txn = yield defer.ensureDeferred(
  226. self.store.create_appservice_txn(service, events, [])
  227. )
  228. self.assertEquals(txn.id, 9646)
  229. self.assertEquals(txn.events, events)
  230. self.assertEquals(txn.service, service)
  231. @defer.inlineCallbacks
  232. def test_create_appservice_txn_up_to_date_last_txn(self):
  233. service = Mock(id=self.as_list[0]["id"])
  234. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  235. yield self._set_last_txn(service.id, 9643)
  236. txn = yield defer.ensureDeferred(
  237. self.store.create_appservice_txn(service, events, [])
  238. )
  239. self.assertEquals(txn.id, 9644)
  240. self.assertEquals(txn.events, events)
  241. self.assertEquals(txn.service, service)
  242. @defer.inlineCallbacks
  243. def test_create_appservice_txn_up_fuzzing(self):
  244. service = Mock(id=self.as_list[0]["id"])
  245. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  246. yield self._set_last_txn(service.id, 9643)
  247. # dump in rows with higher IDs to make sure the queries aren't wrong.
  248. yield self._set_last_txn(self.as_list[1]["id"], 119643)
  249. yield self._set_last_txn(self.as_list[2]["id"], 9)
  250. yield self._set_last_txn(self.as_list[3]["id"], 9643)
  251. yield self._insert_txn(self.as_list[1]["id"], 119644, events)
  252. yield self._insert_txn(self.as_list[1]["id"], 119645, events)
  253. yield self._insert_txn(self.as_list[1]["id"], 119646, events)
  254. yield self._insert_txn(self.as_list[2]["id"], 10, events)
  255. yield self._insert_txn(self.as_list[3]["id"], 9643, events)
  256. txn = yield defer.ensureDeferred(
  257. self.store.create_appservice_txn(service, events, [])
  258. )
  259. self.assertEquals(txn.id, 9644)
  260. self.assertEquals(txn.events, events)
  261. self.assertEquals(txn.service, service)
  262. @defer.inlineCallbacks
  263. def test_complete_appservice_txn_first_txn(self):
  264. service = Mock(id=self.as_list[0]["id"])
  265. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  266. txn_id = 1
  267. yield self._insert_txn(service.id, txn_id, events)
  268. yield defer.ensureDeferred(
  269. self.store.complete_appservice_txn(txn_id=txn_id, service=service)
  270. )
  271. res = yield self.db_pool.runQuery(
  272. self.engine.convert_param_style(
  273. "SELECT last_txn FROM application_services_state WHERE as_id=?"
  274. ),
  275. (service.id,),
  276. )
  277. self.assertEquals(1, len(res))
  278. self.assertEquals(txn_id, res[0][0])
  279. res = yield self.db_pool.runQuery(
  280. self.engine.convert_param_style(
  281. "SELECT * FROM application_services_txns WHERE txn_id=?"
  282. ),
  283. (txn_id,),
  284. )
  285. self.assertEquals(0, len(res))
  286. @defer.inlineCallbacks
  287. def test_complete_appservice_txn_existing_in_state_table(self):
  288. service = Mock(id=self.as_list[0]["id"])
  289. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  290. txn_id = 5
  291. yield self._set_last_txn(service.id, 4)
  292. yield self._insert_txn(service.id, txn_id, events)
  293. yield defer.ensureDeferred(
  294. self.store.complete_appservice_txn(txn_id=txn_id, service=service)
  295. )
  296. res = yield self.db_pool.runQuery(
  297. self.engine.convert_param_style(
  298. "SELECT last_txn, state FROM application_services_state WHERE as_id=?"
  299. ),
  300. (service.id,),
  301. )
  302. self.assertEquals(1, len(res))
  303. self.assertEquals(txn_id, res[0][0])
  304. self.assertEquals(ApplicationServiceState.UP, res[0][1])
  305. res = yield self.db_pool.runQuery(
  306. self.engine.convert_param_style(
  307. "SELECT * FROM application_services_txns WHERE txn_id=?"
  308. ),
  309. (txn_id,),
  310. )
  311. self.assertEquals(0, len(res))
  312. @defer.inlineCallbacks
  313. def test_get_oldest_unsent_txn_none(self):
  314. service = Mock(id=self.as_list[0]["id"])
  315. txn = yield defer.ensureDeferred(self.store.get_oldest_unsent_txn(service))
  316. self.assertEquals(None, txn)
  317. @defer.inlineCallbacks
  318. def test_get_oldest_unsent_txn(self):
  319. service = Mock(id=self.as_list[0]["id"])
  320. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  321. other_events = [Mock(event_id="e5"), Mock(event_id="e6")]
  322. # we aren't testing store._base stuff here, so mock this out
  323. self.store.get_events_as_list = Mock(return_value=make_awaitable(events))
  324. yield self._insert_txn(self.as_list[1]["id"], 9, other_events)
  325. yield self._insert_txn(service.id, 10, events)
  326. yield self._insert_txn(service.id, 11, other_events)
  327. yield self._insert_txn(service.id, 12, other_events)
  328. txn = yield defer.ensureDeferred(self.store.get_oldest_unsent_txn(service))
  329. self.assertEquals(service, txn.service)
  330. self.assertEquals(10, txn.id)
  331. self.assertEquals(events, txn.events)
  332. @defer.inlineCallbacks
  333. def test_get_appservices_by_state_single(self):
  334. yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
  335. yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
  336. services = yield defer.ensureDeferred(
  337. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  338. )
  339. self.assertEquals(1, len(services))
  340. self.assertEquals(self.as_list[0]["id"], services[0].id)
  341. @defer.inlineCallbacks
  342. def test_get_appservices_by_state_multiple(self):
  343. yield self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
  344. yield self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
  345. yield self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
  346. yield self._set_state(self.as_list[3]["id"], ApplicationServiceState.UP)
  347. services = yield defer.ensureDeferred(
  348. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  349. )
  350. self.assertEquals(2, len(services))
  351. self.assertEquals(
  352. {self.as_list[2]["id"], self.as_list[0]["id"]},
  353. {services[0].id, services[1].id},
  354. )
  355. class ApplicationServiceStoreTypeStreamIds(unittest.HomeserverTestCase):
  356. def make_homeserver(self, reactor, clock):
  357. hs = self.setup_test_homeserver()
  358. return hs
  359. def prepare(self, hs, reactor, clock):
  360. self.service = Mock(id="foo")
  361. self.store = self.hs.get_datastore()
  362. self.get_success(self.store.set_appservice_state(self.service, "up"))
  363. def test_get_type_stream_id_for_appservice_no_value(self):
  364. value = self.get_success(
  365. self.store.get_type_stream_id_for_appservice(self.service, "read_receipt")
  366. )
  367. self.assertEquals(value, 0)
  368. value = self.get_success(
  369. self.store.get_type_stream_id_for_appservice(self.service, "presence")
  370. )
  371. self.assertEquals(value, 0)
  372. def test_get_type_stream_id_for_appservice_invalid_type(self):
  373. self.get_failure(
  374. self.store.get_type_stream_id_for_appservice(self.service, "foobar"),
  375. ValueError,
  376. )
  377. def test_set_type_stream_id_for_appservice(self):
  378. read_receipt_value = 1024
  379. self.get_success(
  380. self.store.set_type_stream_id_for_appservice(
  381. self.service, "read_receipt", read_receipt_value
  382. )
  383. )
  384. result = self.get_success(
  385. self.store.get_type_stream_id_for_appservice(self.service, "read_receipt")
  386. )
  387. self.assertEqual(result, read_receipt_value)
  388. self.get_success(
  389. self.store.set_type_stream_id_for_appservice(
  390. self.service, "presence", read_receipt_value
  391. )
  392. )
  393. result = self.get_success(
  394. self.store.get_type_stream_id_for_appservice(self.service, "presence")
  395. )
  396. self.assertEqual(result, read_receipt_value)
  397. def test_set_type_stream_id_for_appservice_invalid_type(self):
  398. self.get_failure(
  399. self.store.set_type_stream_id_for_appservice(self.service, "foobar", 1024),
  400. ValueError,
  401. )
  402. # required for ApplicationServiceTransactionStoreTestCase tests
  403. class TestTransactionStore(ApplicationServiceTransactionStore, ApplicationServiceStore):
  404. def __init__(self, database: DatabasePool, db_conn, hs):
  405. super().__init__(database, db_conn, hs)
  406. class ApplicationServiceStoreConfigTestCase(unittest.TestCase):
  407. def _write_config(self, suffix, **kwargs):
  408. vals = {
  409. "id": "id" + suffix,
  410. "url": "url" + suffix,
  411. "as_token": "as_token" + suffix,
  412. "hs_token": "hs_token" + suffix,
  413. "sender_localpart": "sender_localpart" + suffix,
  414. "namespaces": {},
  415. }
  416. vals.update(kwargs)
  417. _, path = tempfile.mkstemp(prefix="as_config")
  418. with open(path, "w") as f:
  419. f.write(yaml.dump(vals))
  420. return path
  421. @defer.inlineCallbacks
  422. def test_unique_works(self):
  423. f1 = self._write_config(suffix="1")
  424. f2 = self._write_config(suffix="2")
  425. hs = yield setup_test_homeserver(
  426. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  427. )
  428. hs.config.app_service_config_files = [f1, f2]
  429. hs.config.caches.event_cache_size = 1
  430. hs.config.password_providers = []
  431. database = hs.get_datastores().databases[0]
  432. ApplicationServiceStore(
  433. database, make_conn(database._database_config, database.engine, "test"), hs
  434. )
  435. @defer.inlineCallbacks
  436. def test_duplicate_ids(self):
  437. f1 = self._write_config(id="id", suffix="1")
  438. f2 = self._write_config(id="id", suffix="2")
  439. hs = yield setup_test_homeserver(
  440. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  441. )
  442. hs.config.app_service_config_files = [f1, f2]
  443. hs.config.caches.event_cache_size = 1
  444. hs.config.password_providers = []
  445. with self.assertRaises(ConfigError) as cm:
  446. database = hs.get_datastores().databases[0]
  447. ApplicationServiceStore(
  448. database,
  449. make_conn(database._database_config, database.engine, "test"),
  450. hs,
  451. )
  452. e = cm.exception
  453. self.assertIn(f1, str(e))
  454. self.assertIn(f2, str(e))
  455. self.assertIn("id", str(e))
  456. @defer.inlineCallbacks
  457. def test_duplicate_as_tokens(self):
  458. f1 = self._write_config(as_token="as_token", suffix="1")
  459. f2 = self._write_config(as_token="as_token", suffix="2")
  460. hs = yield setup_test_homeserver(
  461. self.addCleanup, federation_sender=Mock(), federation_client=Mock()
  462. )
  463. hs.config.app_service_config_files = [f1, f2]
  464. hs.config.caches.event_cache_size = 1
  465. hs.config.password_providers = []
  466. with self.assertRaises(ConfigError) as cm:
  467. database = hs.get_datastores().databases[0]
  468. ApplicationServiceStore(
  469. database,
  470. make_conn(database._database_config, database.engine, "test"),
  471. hs,
  472. )
  473. e = cm.exception
  474. self.assertIn(f1, str(e))
  475. self.assertIn(f2, str(e))
  476. self.assertIn("as_token", str(e))