1
0

test_appservice.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 typing import List, cast
  18. from unittest.mock import Mock
  19. import yaml
  20. from twisted.internet import defer
  21. from twisted.test.proto_helpers import MemoryReactor
  22. from synapse.appservice import ApplicationService, ApplicationServiceState
  23. from synapse.config._base import ConfigError
  24. from synapse.events import EventBase
  25. from synapse.server import HomeServer
  26. from synapse.storage.database import DatabasePool, make_conn
  27. from synapse.storage.databases.main.appservice import (
  28. ApplicationServiceStore,
  29. ApplicationServiceTransactionStore,
  30. )
  31. from synapse.types import DeviceListUpdates
  32. from synapse.util import Clock
  33. from tests import unittest
  34. from tests.test_utils import make_awaitable
  35. class ApplicationServiceStoreTestCase(unittest.HomeserverTestCase):
  36. def setUp(self):
  37. super(ApplicationServiceStoreTestCase, self).setUp()
  38. self.as_yaml_files: List[str] = []
  39. self.hs.config.appservice.app_service_config_files = self.as_yaml_files
  40. self.hs.config.caches.event_cache_size = 1
  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 = self.hs.get_datastores().databases[0]
  51. self.store = ApplicationServiceStore(
  52. database,
  53. make_conn(database._database_config, database.engine, "test"),
  54. self.hs,
  55. )
  56. def tearDown(self) -> None:
  57. # TODO: suboptimal that we need to create files for tests!
  58. for f in self.as_yaml_files:
  59. try:
  60. os.remove(f)
  61. except Exception:
  62. pass
  63. super(ApplicationServiceStoreTestCase, self).tearDown()
  64. def _add_appservice(self, as_token, id, url, hs_token, sender) -> None:
  65. as_yaml = {
  66. "url": url,
  67. "as_token": as_token,
  68. "hs_token": hs_token,
  69. "id": id,
  70. "sender_localpart": sender,
  71. "namespaces": {},
  72. }
  73. # use the token as the filename
  74. with open(as_token, "w") as outfile:
  75. outfile.write(yaml.dump(as_yaml))
  76. self.as_yaml_files.append(as_token)
  77. def test_retrieve_unknown_service_token(self) -> None:
  78. service = self.store.get_app_service_by_token("invalid_token")
  79. self.assertEqual(service, None)
  80. def test_retrieval_of_service(self) -> None:
  81. stored_service = self.store.get_app_service_by_token(self.as_token)
  82. assert stored_service is not None
  83. self.assertEqual(stored_service.token, self.as_token)
  84. self.assertEqual(stored_service.id, self.as_id)
  85. self.assertEqual(stored_service.url, self.as_url)
  86. self.assertEqual(stored_service.namespaces[ApplicationService.NS_ALIASES], [])
  87. self.assertEqual(stored_service.namespaces[ApplicationService.NS_ROOMS], [])
  88. self.assertEqual(stored_service.namespaces[ApplicationService.NS_USERS], [])
  89. def test_retrieval_of_all_services(self) -> None:
  90. services = self.store.get_app_services()
  91. self.assertEqual(len(services), 3)
  92. class ApplicationServiceTransactionStoreTestCase(unittest.HomeserverTestCase):
  93. def setUp(self) -> None:
  94. super(ApplicationServiceTransactionStoreTestCase, self).setUp()
  95. self.as_yaml_files: List[str] = []
  96. self.hs.config.appservice.app_service_config_files = self.as_yaml_files
  97. self.hs.config.caches.event_cache_size = 1
  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. 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 = self.hs.get_datastores().databases[0]
  109. self.db_pool = database._db_pool
  110. self.engine = database.engine
  111. db_config = self.hs.config.database.get_single_database()
  112. self.store = TestTransactionStore(
  113. database, make_conn(db_config, self.engine, "test"), self.hs
  114. )
  115. def _add_service(self, url, as_token, id) -> None:
  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: str, state: ApplicationServiceState):
  129. return self.db_pool.runOperation(
  130. self.engine.convert_param_style(
  131. "INSERT INTO application_services_state(as_id, state) VALUES(?,?)"
  132. ),
  133. (id, state.value),
  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 test_get_appservice_state_none(
  144. self,
  145. ) -> None:
  146. service = Mock(id="999")
  147. state = self.get_success(self.store.get_appservice_state(service))
  148. self.assertEqual(None, state)
  149. def test_get_appservice_state_up(
  150. self,
  151. ) -> None:
  152. self.get_success(
  153. self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
  154. )
  155. service = Mock(id=self.as_list[0]["id"])
  156. state = self.get_success(
  157. defer.ensureDeferred(self.store.get_appservice_state(service))
  158. )
  159. self.assertEqual(ApplicationServiceState.UP, state)
  160. def test_get_appservice_state_down(
  161. self,
  162. ) -> None:
  163. self.get_success(
  164. self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
  165. )
  166. self.get_success(
  167. self._set_state(self.as_list[1]["id"], ApplicationServiceState.DOWN)
  168. )
  169. self.get_success(
  170. self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
  171. )
  172. service = Mock(id=self.as_list[1]["id"])
  173. state = self.get_success(self.store.get_appservice_state(service))
  174. self.assertEqual(ApplicationServiceState.DOWN, state)
  175. def test_get_appservices_by_state_none(
  176. self,
  177. ) -> None:
  178. services = self.get_success(
  179. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  180. )
  181. self.assertEqual(0, len(services))
  182. def test_set_appservices_state_down(
  183. self,
  184. ) -> None:
  185. service = Mock(id=self.as_list[1]["id"])
  186. self.get_success(
  187. self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  188. )
  189. rows = self.get_success(
  190. self.db_pool.runQuery(
  191. self.engine.convert_param_style(
  192. "SELECT as_id FROM application_services_state WHERE state=?"
  193. ),
  194. (ApplicationServiceState.DOWN.value,),
  195. )
  196. )
  197. self.assertEqual(service.id, rows[0][0])
  198. def test_set_appservices_state_multiple_up(
  199. self,
  200. ) -> None:
  201. service = Mock(id=self.as_list[1]["id"])
  202. self.get_success(
  203. self.store.set_appservice_state(service, ApplicationServiceState.UP)
  204. )
  205. self.get_success(
  206. self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  207. )
  208. self.get_success(
  209. self.store.set_appservice_state(service, ApplicationServiceState.UP)
  210. )
  211. rows = self.get_success(
  212. self.db_pool.runQuery(
  213. self.engine.convert_param_style(
  214. "SELECT as_id FROM application_services_state WHERE state=?"
  215. ),
  216. (ApplicationServiceState.UP.value,),
  217. )
  218. )
  219. self.assertEqual(service.id, rows[0][0])
  220. def test_create_appservice_txn_first(
  221. self,
  222. ) -> None:
  223. service = Mock(id=self.as_list[0]["id"])
  224. events = cast(List[EventBase], [Mock(event_id="e1"), Mock(event_id="e2")])
  225. txn = self.get_success(
  226. defer.ensureDeferred(
  227. self.store.create_appservice_txn(
  228. service, events, [], [], {}, {}, DeviceListUpdates()
  229. )
  230. )
  231. )
  232. self.assertEqual(txn.id, 1)
  233. self.assertEqual(txn.events, events)
  234. self.assertEqual(txn.service, service)
  235. def test_complete_appservice_txn_first_txn(
  236. self,
  237. ) -> None:
  238. service = Mock(id=self.as_list[0]["id"])
  239. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  240. txn_id = 1
  241. self.get_success(self._insert_txn(service.id, txn_id, events))
  242. self.get_success(
  243. self.store.complete_appservice_txn(txn_id=txn_id, service=service)
  244. )
  245. res = self.get_success(
  246. self.db_pool.runQuery(
  247. self.engine.convert_param_style(
  248. "SELECT * FROM application_services_txns WHERE txn_id=?"
  249. ),
  250. (txn_id,),
  251. )
  252. )
  253. self.assertEqual(0, len(res))
  254. def test_complete_appservice_txn_updates_last_txn_state(
  255. self,
  256. ) -> None:
  257. service = Mock(id=self.as_list[0]["id"])
  258. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  259. txn_id = 5
  260. self._set_state(self.as_list[0]["id"], ApplicationServiceState.UP)
  261. self.get_success(self._insert_txn(service.id, txn_id, events))
  262. self.get_success(
  263. self.store.complete_appservice_txn(txn_id=txn_id, service=service)
  264. )
  265. res = self.get_success(
  266. self.db_pool.runQuery(
  267. self.engine.convert_param_style(
  268. "SELECT state FROM application_services_state WHERE as_id=?"
  269. ),
  270. (service.id,),
  271. )
  272. )
  273. self.assertEqual(1, len(res))
  274. self.assertEqual(ApplicationServiceState.UP.value, res[0][0])
  275. res = self.get_success(
  276. 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. )
  283. self.assertEqual(0, len(res))
  284. def test_get_oldest_unsent_txn_none(
  285. self,
  286. ) -> None:
  287. service = Mock(id=self.as_list[0]["id"])
  288. txn = self.get_success(self.store.get_oldest_unsent_txn(service))
  289. self.assertEqual(None, txn)
  290. def test_get_oldest_unsent_txn(self) -> None:
  291. service = Mock(id=self.as_list[0]["id"])
  292. events = [Mock(event_id="e1"), Mock(event_id="e2")]
  293. other_events = [Mock(event_id="e5"), Mock(event_id="e6")]
  294. # we aren't testing store._base stuff here, so mock this out
  295. # (ignore needed because Mypy won't allow us to assign to a method otherwise)
  296. self.store.get_events_as_list = Mock(return_value=make_awaitable(events)) # type: ignore[assignment]
  297. self.get_success(self._insert_txn(self.as_list[1]["id"], 9, other_events))
  298. self.get_success(self._insert_txn(service.id, 10, events))
  299. self.get_success(self._insert_txn(service.id, 11, other_events))
  300. self.get_success(self._insert_txn(service.id, 12, other_events))
  301. txn = self.get_success(self.store.get_oldest_unsent_txn(service))
  302. assert txn is not None
  303. self.assertEqual(service, txn.service)
  304. self.assertEqual(10, txn.id)
  305. self.assertEqual(events, txn.events)
  306. def test_get_appservices_by_state_single(
  307. self,
  308. ) -> None:
  309. self.get_success(
  310. self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
  311. )
  312. self.get_success(
  313. self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
  314. )
  315. services = self.get_success(
  316. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  317. )
  318. self.assertEqual(1, len(services))
  319. self.assertEqual(self.as_list[0]["id"], services[0].id)
  320. def test_get_appservices_by_state_multiple(
  321. self,
  322. ) -> None:
  323. self.get_success(
  324. self._set_state(self.as_list[0]["id"], ApplicationServiceState.DOWN)
  325. )
  326. self.get_success(
  327. self._set_state(self.as_list[1]["id"], ApplicationServiceState.UP)
  328. )
  329. self.get_success(
  330. self._set_state(self.as_list[2]["id"], ApplicationServiceState.DOWN)
  331. )
  332. self.get_success(
  333. self._set_state(self.as_list[3]["id"], ApplicationServiceState.UP)
  334. )
  335. services = self.get_success(
  336. self.store.get_appservices_by_state(ApplicationServiceState.DOWN)
  337. )
  338. self.assertEqual(2, len(services))
  339. self.assertEqual(
  340. {self.as_list[2]["id"], self.as_list[0]["id"]},
  341. {services[0].id, services[1].id},
  342. )
  343. class ApplicationServiceStoreTypeStreamIds(unittest.HomeserverTestCase):
  344. def prepare(
  345. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  346. ) -> None:
  347. self.service = Mock(id="foo")
  348. self.store = self.hs.get_datastores().main
  349. self.get_success(
  350. self.store.set_appservice_state(self.service, ApplicationServiceState.UP)
  351. )
  352. def test_get_type_stream_id_for_appservice_no_value(self) -> None:
  353. value = self.get_success(
  354. self.store.get_type_stream_id_for_appservice(self.service, "read_receipt")
  355. )
  356. self.assertEqual(value, 1)
  357. value = self.get_success(
  358. self.store.get_type_stream_id_for_appservice(self.service, "presence")
  359. )
  360. self.assertEqual(value, 1)
  361. def test_get_type_stream_id_for_appservice_invalid_type(self) -> None:
  362. self.get_failure(
  363. self.store.get_type_stream_id_for_appservice(self.service, "foobar"),
  364. ValueError,
  365. )
  366. def test_set_appservice_stream_type_pos(self) -> None:
  367. read_receipt_value = 1024
  368. self.get_success(
  369. self.store.set_appservice_stream_type_pos(
  370. self.service, "read_receipt", read_receipt_value
  371. )
  372. )
  373. result = self.get_success(
  374. self.store.get_type_stream_id_for_appservice(self.service, "read_receipt")
  375. )
  376. self.assertEqual(result, read_receipt_value)
  377. self.get_success(
  378. self.store.set_appservice_stream_type_pos(
  379. self.service, "presence", read_receipt_value
  380. )
  381. )
  382. result = self.get_success(
  383. self.store.get_type_stream_id_for_appservice(self.service, "presence")
  384. )
  385. self.assertEqual(result, read_receipt_value)
  386. def test_set_appservice_stream_type_pos_invalid_type(self) -> None:
  387. self.get_failure(
  388. self.store.set_appservice_stream_type_pos(self.service, "foobar", 1024),
  389. ValueError,
  390. )
  391. # required for ApplicationServiceTransactionStoreTestCase tests
  392. class TestTransactionStore(ApplicationServiceTransactionStore, ApplicationServiceStore):
  393. def __init__(self, database: DatabasePool, db_conn, hs) -> None:
  394. super().__init__(database, db_conn, hs)
  395. class ApplicationServiceStoreConfigTestCase(unittest.HomeserverTestCase):
  396. def _write_config(self, suffix, **kwargs) -> str:
  397. vals = {
  398. "id": "id" + suffix,
  399. "url": "url" + suffix,
  400. "as_token": "as_token" + suffix,
  401. "hs_token": "hs_token" + suffix,
  402. "sender_localpart": "sender_localpart" + suffix,
  403. "namespaces": {},
  404. }
  405. vals.update(kwargs)
  406. _, path = tempfile.mkstemp(prefix="as_config")
  407. with open(path, "w") as f:
  408. f.write(yaml.dump(vals))
  409. return path
  410. def test_unique_works(self) -> None:
  411. f1 = self._write_config(suffix="1")
  412. f2 = self._write_config(suffix="2")
  413. self.hs.config.appservice.app_service_config_files = [f1, f2]
  414. self.hs.config.caches.event_cache_size = 1
  415. database = self.hs.get_datastores().databases[0]
  416. ApplicationServiceStore(
  417. database,
  418. make_conn(database._database_config, database.engine, "test"),
  419. self.hs,
  420. )
  421. def test_duplicate_ids(self) -> None:
  422. f1 = self._write_config(id="id", suffix="1")
  423. f2 = self._write_config(id="id", suffix="2")
  424. self.hs.config.appservice.app_service_config_files = [f1, f2]
  425. self.hs.config.caches.event_cache_size = 1
  426. with self.assertRaises(ConfigError) as cm:
  427. database = self.hs.get_datastores().databases[0]
  428. ApplicationServiceStore(
  429. database,
  430. make_conn(database._database_config, database.engine, "test"),
  431. self.hs,
  432. )
  433. e = cm.exception
  434. self.assertIn(f1, str(e))
  435. self.assertIn(f2, str(e))
  436. self.assertIn("id", str(e))
  437. def test_duplicate_as_tokens(self) -> None:
  438. f1 = self._write_config(as_token="as_token", suffix="1")
  439. f2 = self._write_config(as_token="as_token", suffix="2")
  440. self.hs.config.appservice.app_service_config_files = [f1, f2]
  441. self.hs.config.caches.event_cache_size = 1
  442. with self.assertRaises(ConfigError) as cm:
  443. database = self.hs.get_datastores().databases[0]
  444. ApplicationServiceStore(
  445. database,
  446. make_conn(database._database_config, database.engine, "test"),
  447. self.hs,
  448. )
  449. e = cm.exception
  450. self.assertIn(f1, str(e))
  451. self.assertIn(f2, str(e))
  452. self.assertIn("as_token", str(e))