test_appservice.py 22 KB

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