test_appservice.py 17 KB

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