test_client_ips.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from mock import Mock
  17. from twisted.internet import defer
  18. import synapse.rest.admin
  19. from synapse.http.site import XForwardedForRequest
  20. from synapse.rest.client.v1 import login
  21. from tests import unittest
  22. class ClientIpStoreTestCase(unittest.HomeserverTestCase):
  23. def make_homeserver(self, reactor, clock):
  24. hs = self.setup_test_homeserver()
  25. return hs
  26. def prepare(self, hs, reactor, clock):
  27. self.store = self.hs.get_datastore()
  28. def test_insert_new_client_ip(self):
  29. self.reactor.advance(12345678)
  30. user_id = "@user:id"
  31. self.get_success(
  32. self.store.insert_client_ip(
  33. user_id, "access_token", "ip", "user_agent", "device_id"
  34. )
  35. )
  36. # Trigger the storage loop
  37. self.reactor.advance(10)
  38. result = self.get_success(
  39. self.store.get_last_client_ip_by_device(user_id, "device_id")
  40. )
  41. r = result[(user_id, "device_id")]
  42. self.assertDictContainsSubset(
  43. {
  44. "user_id": user_id,
  45. "device_id": "device_id",
  46. "ip": "ip",
  47. "user_agent": "user_agent",
  48. "last_seen": 12345678000,
  49. },
  50. r,
  51. )
  52. def test_insert_new_client_ip_none_device_id(self):
  53. """
  54. An insert with a device ID of NULL will not create a new entry, but
  55. update an existing entry in the user_ips table.
  56. """
  57. self.reactor.advance(12345678)
  58. user_id = "@user:id"
  59. # Add & trigger the storage loop
  60. self.get_success(
  61. self.store.insert_client_ip(
  62. user_id, "access_token", "ip", "user_agent", None
  63. )
  64. )
  65. self.reactor.advance(200)
  66. self.pump(0)
  67. result = self.get_success(
  68. self.store._simple_select_list(
  69. table="user_ips",
  70. keyvalues={"user_id": user_id},
  71. retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
  72. desc="get_user_ip_and_agents",
  73. )
  74. )
  75. self.assertEqual(
  76. result,
  77. [
  78. {
  79. "access_token": "access_token",
  80. "ip": "ip",
  81. "user_agent": "user_agent",
  82. "device_id": None,
  83. "last_seen": 12345678000,
  84. }
  85. ],
  86. )
  87. # Add another & trigger the storage loop
  88. self.get_success(
  89. self.store.insert_client_ip(
  90. user_id, "access_token", "ip", "user_agent", None
  91. )
  92. )
  93. self.reactor.advance(10)
  94. self.pump(0)
  95. result = self.get_success(
  96. self.store._simple_select_list(
  97. table="user_ips",
  98. keyvalues={"user_id": user_id},
  99. retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
  100. desc="get_user_ip_and_agents",
  101. )
  102. )
  103. # Only one result, has been upserted.
  104. self.assertEqual(
  105. result,
  106. [
  107. {
  108. "access_token": "access_token",
  109. "ip": "ip",
  110. "user_agent": "user_agent",
  111. "device_id": None,
  112. "last_seen": 12345878000,
  113. }
  114. ],
  115. )
  116. def test_disabled_monthly_active_user(self):
  117. self.hs.config.limit_usage_by_mau = False
  118. self.hs.config.max_mau_value = 50
  119. user_id = "@user:server"
  120. self.get_success(
  121. self.store.insert_client_ip(
  122. user_id, "access_token", "ip", "user_agent", "device_id"
  123. )
  124. )
  125. active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
  126. self.assertFalse(active)
  127. def test_adding_monthly_active_user_when_full(self):
  128. self.hs.config.limit_usage_by_mau = True
  129. self.hs.config.max_mau_value = 50
  130. lots_of_users = 100
  131. user_id = "@user:server"
  132. self.store.get_monthly_active_count = Mock(
  133. return_value=defer.succeed(lots_of_users)
  134. )
  135. self.get_success(
  136. self.store.insert_client_ip(
  137. user_id, "access_token", "ip", "user_agent", "device_id"
  138. )
  139. )
  140. active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
  141. self.assertFalse(active)
  142. def test_adding_monthly_active_user_when_space(self):
  143. self.hs.config.limit_usage_by_mau = True
  144. self.hs.config.max_mau_value = 50
  145. user_id = "@user:server"
  146. active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
  147. self.assertFalse(active)
  148. # Trigger the saving loop
  149. self.reactor.advance(10)
  150. self.get_success(
  151. self.store.insert_client_ip(
  152. user_id, "access_token", "ip", "user_agent", "device_id"
  153. )
  154. )
  155. active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
  156. self.assertTrue(active)
  157. def test_updating_monthly_active_user_when_space(self):
  158. self.hs.config.limit_usage_by_mau = True
  159. self.hs.config.max_mau_value = 50
  160. user_id = "@user:server"
  161. self.get_success(self.store.register_user(user_id=user_id, password_hash=None))
  162. active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
  163. self.assertFalse(active)
  164. # Trigger the saving loop
  165. self.reactor.advance(10)
  166. self.get_success(
  167. self.store.insert_client_ip(
  168. user_id, "access_token", "ip", "user_agent", "device_id"
  169. )
  170. )
  171. active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
  172. self.assertTrue(active)
  173. def test_devices_last_seen_bg_update(self):
  174. # First make sure we have completed all updates.
  175. while not self.get_success(self.store.has_completed_background_updates()):
  176. self.get_success(self.store.do_next_background_update(100), by=0.1)
  177. # Insert a user IP
  178. user_id = "@user:id"
  179. self.get_success(
  180. self.store.insert_client_ip(
  181. user_id, "access_token", "ip", "user_agent", "device_id"
  182. )
  183. )
  184. # Force persisting to disk
  185. self.reactor.advance(200)
  186. # But clear the associated entry in devices table
  187. self.get_success(
  188. self.store._simple_update(
  189. table="devices",
  190. keyvalues={"user_id": user_id, "device_id": "device_id"},
  191. updatevalues={"last_seen": None, "ip": None, "user_agent": None},
  192. desc="test_devices_last_seen_bg_update",
  193. )
  194. )
  195. # We should now get nulls when querying
  196. result = self.get_success(
  197. self.store.get_last_client_ip_by_device(user_id, "device_id")
  198. )
  199. r = result[(user_id, "device_id")]
  200. self.assertDictContainsSubset(
  201. {
  202. "user_id": user_id,
  203. "device_id": "device_id",
  204. "ip": None,
  205. "user_agent": None,
  206. "last_seen": None,
  207. },
  208. r,
  209. )
  210. # Register the background update to run again.
  211. self.get_success(
  212. self.store._simple_insert(
  213. table="background_updates",
  214. values={
  215. "update_name": "devices_last_seen",
  216. "progress_json": "{}",
  217. "depends_on": None,
  218. },
  219. )
  220. )
  221. # ... and tell the DataStore that it hasn't finished all updates yet
  222. self.store._all_done = False
  223. # Now let's actually drive the updates to completion
  224. while not self.get_success(self.store.has_completed_background_updates()):
  225. self.get_success(self.store.do_next_background_update(100), by=0.1)
  226. # We should now get the correct result again
  227. result = self.get_success(
  228. self.store.get_last_client_ip_by_device(user_id, "device_id")
  229. )
  230. r = result[(user_id, "device_id")]
  231. self.assertDictContainsSubset(
  232. {
  233. "user_id": user_id,
  234. "device_id": "device_id",
  235. "ip": "ip",
  236. "user_agent": "user_agent",
  237. "last_seen": 0,
  238. },
  239. r,
  240. )
  241. def test_old_user_ips_pruned(self):
  242. # First make sure we have completed all updates.
  243. while not self.get_success(self.store.has_completed_background_updates()):
  244. self.get_success(self.store.do_next_background_update(100), by=0.1)
  245. # Insert a user IP
  246. user_id = "@user:id"
  247. self.get_success(
  248. self.store.insert_client_ip(
  249. user_id, "access_token", "ip", "user_agent", "device_id"
  250. )
  251. )
  252. # Force persisting to disk
  253. self.reactor.advance(200)
  254. # We should see that in the DB
  255. result = self.get_success(
  256. self.store._simple_select_list(
  257. table="user_ips",
  258. keyvalues={"user_id": user_id},
  259. retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
  260. desc="get_user_ip_and_agents",
  261. )
  262. )
  263. self.assertEqual(
  264. result,
  265. [
  266. {
  267. "access_token": "access_token",
  268. "ip": "ip",
  269. "user_agent": "user_agent",
  270. "device_id": "device_id",
  271. "last_seen": 0,
  272. }
  273. ],
  274. )
  275. # Now advance by a couple of months
  276. self.reactor.advance(60 * 24 * 60 * 60)
  277. # We should get no results.
  278. result = self.get_success(
  279. self.store._simple_select_list(
  280. table="user_ips",
  281. keyvalues={"user_id": user_id},
  282. retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
  283. desc="get_user_ip_and_agents",
  284. )
  285. )
  286. self.assertEqual(result, [])
  287. # But we should still get the correct values for the device
  288. result = self.get_success(
  289. self.store.get_last_client_ip_by_device(user_id, "device_id")
  290. )
  291. r = result[(user_id, "device_id")]
  292. self.assertDictContainsSubset(
  293. {
  294. "user_id": user_id,
  295. "device_id": "device_id",
  296. "ip": "ip",
  297. "user_agent": "user_agent",
  298. "last_seen": 0,
  299. },
  300. r,
  301. )
  302. class ClientIpAuthTestCase(unittest.HomeserverTestCase):
  303. servlets = [
  304. synapse.rest.admin.register_servlets_for_client_rest_resource,
  305. login.register_servlets,
  306. ]
  307. def make_homeserver(self, reactor, clock):
  308. hs = self.setup_test_homeserver()
  309. return hs
  310. def prepare(self, hs, reactor, clock):
  311. self.store = self.hs.get_datastore()
  312. self.user_id = self.register_user("bob", "abc123", True)
  313. def test_request_with_xforwarded(self):
  314. """
  315. The IP in X-Forwarded-For is entered into the client IPs table.
  316. """
  317. self._runtest(
  318. {b"X-Forwarded-For": b"127.9.0.1"},
  319. "127.9.0.1",
  320. {"request": XForwardedForRequest},
  321. )
  322. def test_request_from_getPeer(self):
  323. """
  324. The IP returned by getPeer is entered into the client IPs table, if
  325. there's no X-Forwarded-For header.
  326. """
  327. self._runtest({}, "127.0.0.1", {})
  328. def _runtest(self, headers, expected_ip, make_request_args):
  329. device_id = "bleb"
  330. access_token = self.login("bob", "abc123", device_id=device_id)
  331. # Advance to a known time
  332. self.reactor.advance(123456 - self.reactor.seconds())
  333. request, channel = self.make_request(
  334. "GET",
  335. "/_matrix/client/r0/admin/users/" + self.user_id,
  336. access_token=access_token,
  337. **make_request_args
  338. )
  339. request.requestHeaders.addRawHeader(b"User-Agent", b"Mozzila pizza")
  340. # Add the optional headers
  341. for h, v in headers.items():
  342. request.requestHeaders.addRawHeader(h, v)
  343. self.render(request)
  344. # Advance so the save loop occurs
  345. self.reactor.advance(100)
  346. result = self.get_success(
  347. self.store.get_last_client_ip_by_device(self.user_id, device_id)
  348. )
  349. r = result[(self.user_id, device_id)]
  350. self.assertDictContainsSubset(
  351. {
  352. "user_id": self.user_id,
  353. "device_id": device_id,
  354. "ip": expected_ip,
  355. "user_agent": "Mozzila pizza",
  356. "last_seen": 123456100,
  357. },
  358. r,
  359. )