test_security.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. """Offline regressions: python3 -m unittest discover -s server/tests -p 'test_*.py'."""
  2. import asyncio
  3. import sys
  4. import tempfile
  5. import unittest
  6. from pathlib import Path
  7. from types import SimpleNamespace
  8. from unittest.mock import patch
  9. sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "app"))
  10. import lynx_api as api
  11. import lynx_common as common
  12. import lynx_relay as relay
  13. def request(ip):
  14. return SimpleNamespace(headers={"X-Forwarded-For": ip}, remote="127.0.0.1")
  15. class ClientKeyTests(unittest.TestCase):
  16. def test_ipv6_same_network_and_equivalent_notation(self):
  17. key = common.client_key(request("2001:db8::1"))
  18. self.assertEqual(key, common.client_key(request("2001:db8::2")))
  19. self.assertEqual(key, common.client_key(request("2001:0db8:0000:0000::2")))
  20. self.assertNotEqual(key, common.client_key(request("2001:db8:0:1::1")))
  21. def test_mapped_ipv4_and_proxy_chain(self):
  22. key = common.client_key(request("192.0.2.1"))
  23. self.assertEqual(key, common.client_key(request("::ffff:192.0.2.1")))
  24. self.assertEqual(key, common.client_key(request("198.51.100.1, 192.0.2.1")))
  25. self.assertNotEqual(key, common.client_key(request("192.0.2.2")))
  26. def test_invalid_address_falls_back_to_peer(self):
  27. self.assertEqual(common.client_key(request("bad")), common.client_key(request("127.0.0.1")))
  28. class RateLimiterTests(unittest.TestCase):
  29. def test_idle_buckets_expire_before_the_table_fills(self):
  30. limiter = common.RateLimiter(2, 60)
  31. with patch.object(common.time, "monotonic", return_value=0):
  32. self.assertTrue(limiter.allow("old"))
  33. with patch.object(common.time, "monotonic", return_value=60):
  34. self.assertTrue(limiter.allow("new"))
  35. self.assertEqual(list(limiter.buckets), ["new"])
  36. def test_burst_refill_and_denials_preserve_tokens(self):
  37. limiter = common.RateLimiter(2, 60)
  38. with patch.object(common.time, "monotonic", return_value=0):
  39. self.assertTrue(limiter.allow("a"))
  40. self.assertTrue(limiter.allow("a"))
  41. self.assertFalse(limiter.allow("a"))
  42. with patch.object(common.time, "monotonic", return_value=15):
  43. self.assertFalse(limiter.allow("a"))
  44. with patch.object(common.time, "monotonic", return_value=30):
  45. self.assertTrue(limiter.allow("a"))
  46. def test_capacity_fails_closed_then_idle_clients_expire(self):
  47. limiter = common.RateLimiter(2, 60)
  48. with patch.object(common, "MAX_CLIENTS", 2), patch.object(common.time, "monotonic", return_value=0):
  49. self.assertTrue(limiter.allow("a"))
  50. self.assertTrue(limiter.allow("b"))
  51. self.assertFalse(limiter.allow("c"))
  52. self.assertTrue(limiter.allow("a"))
  53. self.assertFalse(limiter.allow("a"))
  54. self.assertEqual(len(limiter.buckets), 2)
  55. with patch.object(common.time, "monotonic", return_value=60):
  56. self.assertTrue(limiter.allow("c"))
  57. self.assertEqual(list(limiter.buckets), ["c"])
  58. def test_recent_denial_does_not_expire_before_older_clients(self):
  59. limiter = common.RateLimiter(1, 60)
  60. with patch.object(common.time, "monotonic", return_value=0):
  61. limiter.allow("a")
  62. limiter.allow("b")
  63. with patch.object(common.time, "monotonic", return_value=30):
  64. self.assertFalse(limiter.allow("a"))
  65. with patch.object(common.time, "monotonic", return_value=60):
  66. self.assertTrue(limiter.allow("c"))
  67. self.assertEqual(list(limiter.buckets), ["a", "c"])
  68. class HandlerTests(unittest.IsolatedAsyncioTestCase):
  69. async def test_concurrent_creates_respect_room_capacity(self):
  70. release, both_waiting = asyncio.Event(), asyncio.Event()
  71. waiting = 0
  72. class Request:
  73. headers = {}
  74. remote = "127.0.0.1"
  75. can_read_body = True
  76. async def json(self):
  77. nonlocal waiting
  78. waiting += 1
  79. if waiting == 2:
  80. both_waiting.set()
  81. await release.wait()
  82. return {}
  83. with patch.object(relay, "MAX_ROOMS", 1), patch.object(relay, "rooms", {}), \
  84. patch.object(relay, "room_limiter", common.RateLimiter(10, 3600)):
  85. tasks = [asyncio.create_task(relay.create_room(Request())) for _ in range(2)]
  86. try:
  87. await asyncio.wait_for(both_waiting.wait(), timeout=3)
  88. release.set()
  89. responses = await asyncio.gather(*tasks)
  90. self.assertEqual(sorted(r.status for r in responses), [201, 503])
  91. self.assertEqual(len(relay.rooms), 1)
  92. finally:
  93. for task in tasks:
  94. task.cancel()
  95. await asyncio.gather(*tasks, return_exceptions=True)
  96. async def test_daily_accounting_is_bounded_and_resets_at_midnight(self):
  97. class Request:
  98. headers = {}
  99. remote = "127.0.0.1"
  100. async def json(self):
  101. return {"name": "test.lynxpack", "size": 4}
  102. with tempfile.TemporaryDirectory() as folder, \
  103. patch.object(api, "DATA_DIR", folder), patch.object(api, "SHARES_DIR", folder), \
  104. patch.object(api, "MIN_FREE_BYTES", 0), patch.object(api, "MAX_CLIENTS", 1), \
  105. patch.object(api, "daily_bytes", {"other": 4}), patch.object(api, "daily_day", "2000-01-01"), \
  106. patch.object(api, "create_limiter", common.RateLimiter(10, 3600)), \
  107. patch.object(api.time, "strftime", return_value="2000-01-01") as day:
  108. self.assertEqual((await api.create_share(Request())).status, 503)
  109. self.assertEqual(len(api.daily_bytes), 1)
  110. day.return_value = "2000-01-02"
  111. self.assertEqual((await api.create_share(Request())).status, 201)
  112. self.assertEqual(len(api.daily_bytes), 1)
  113. self.assertEqual(sum(api.daily_bytes.values()), 4)
  114. self.assertEqual(api.daily_day, "2000-01-02")
  115. class RelayLimitTests(unittest.IsolatedAsyncioTestCase):
  116. """Round 190ah: the relay cannot be filled or used as a free tunnel."""
  117. def test_day_budget_counts_a_window_per_client(self):
  118. budget = relay.DayBudget(100, 60)
  119. with patch.object(relay.time, "monotonic", return_value=0):
  120. self.assertTrue(budget.spend("a", 60))
  121. self.assertTrue(budget.spend("a", 40))
  122. self.assertFalse(budget.spend("a", 1))
  123. self.assertTrue(budget.spend("b", 100))
  124. with patch.object(relay.time, "monotonic", return_value=59):
  125. self.assertFalse(budget.spend("a", 1))
  126. with patch.object(relay.time, "monotonic", return_value=61):
  127. self.assertTrue(budget.spend("a", 100)) # a new window
  128. budget.sweep()
  129. self.assertEqual(list(budget.used), ["a"])
  130. def test_room_limits(self):
  131. with patch.object(relay, "ROOM_BYTES", 1000), patch.object(relay, "ROOM_MAX_HOURS", 72), \
  132. patch.object(relay, "ROOM_IDLE_HOURS", 12):
  133. room = relay.Room("abcdefghij", "t" * 43, "h" * 43, "client")
  134. now = room.created
  135. self.assertEqual(room.over_limit(now), "")
  136. room.bytes = 1001
  137. self.assertEqual(room.over_limit(now), "traffic limit")
  138. room.bytes = 0
  139. self.assertEqual(room.over_limit(now + 73 * 3600), "open too long")
  140. # silent for 13 h: only a room somebody is connected to is closed for it (an empty one just expires)
  141. self.assertEqual(room.over_limit(now + 13 * 3600), "")
  142. room.peers[1] = object()
  143. self.assertEqual(room.over_limit(now + 13 * 3600), "idle too long")
  144. room.last_frame = now + 12 * 3600
  145. self.assertEqual(room.over_limit(now + 13 * 3600), "")
  146. async def test_rooms_open_per_client(self):
  147. class Request:
  148. headers = {"X-Forwarded-For": "192.0.2.7"}
  149. remote = "127.0.0.1"
  150. can_read_body = False
  151. class Other(Request):
  152. headers = {"X-Forwarded-For": "192.0.2.8"}
  153. with patch.object(relay, "ROOMS_PER_CLIENT", 2), patch.object(relay, "rooms", {}), \
  154. patch.object(relay, "room_limiter", common.RateLimiter(100, 3600)):
  155. self.assertEqual((await relay.create_room(Request())).status, 201)
  156. self.assertEqual((await relay.create_room(Request())).status, 201)
  157. self.assertEqual((await relay.create_room(Request())).status, 429)
  158. self.assertEqual((await relay.create_room(Other())).status, 201) # somebody else is not affected
  159. # closing one frees a place
  160. relay.rooms.pop(next(k for k, r in relay.rooms.items() if r.creator == common.client_key(Request())))
  161. self.assertEqual((await relay.create_room(Request())).status, 201)
  162. async def test_sweep_closes_rooms_over_a_limit_with_the_limit_code(self):
  163. closed = []
  164. class Socket:
  165. closed = False
  166. async def close(self, code=1000, message=b""):
  167. closed.append((code, message))
  168. with patch.object(relay, "rooms", {}), patch.object(relay, "ROOM_BYTES", 10), patch.object(relay, "limits_hit", 0):
  169. busy = relay.Room("aaaaaaaaaa", "t" * 43, "h" * 43)
  170. busy.peers[1] = Socket()
  171. busy.bytes = 11
  172. fine = relay.Room("bbbbbbbbbb", "t" * 43, "h" * 43)
  173. fine.peers[1] = Socket()
  174. empty = relay.Room("cccccccccc", "t" * 43, "h" * 43)
  175. relay.rooms.update({r.id: r for r in (busy, fine, empty)})
  176. await relay.sweep(busy.created + 1)
  177. self.assertEqual(sorted(relay.rooms), ["bbbbbbbbbb", "cccccccccc"])
  178. self.assertEqual(closed, [(relay.CLOSE_LIMIT, b"traffic limit")])
  179. self.assertEqual(relay.limits_hit, 1)
  180. # an empty room nobody came back to is forgotten after ROOM_HOURS, as before
  181. await relay.sweep(empty.created + relay.ROOM_HOURS * 3600 + 1)
  182. self.assertNotIn("cccccccccc", relay.rooms)
  183. class RelayOutboxTests(unittest.IsolatedAsyncioTestCase):
  184. """Round 190oh: a peer that reads slowly holds up nobody else (no head-of-line blocking) and is closed past its limit."""
  185. class Socket:
  186. def __init__(self, gate=None):
  187. self.closed = False
  188. self.got = []
  189. self.gate = gate
  190. self.close_code = None
  191. async def send_bytes(self, data):
  192. if self.gate is not None:
  193. await self.gate.wait()
  194. self.got.append(data)
  195. async def send_str(self, text):
  196. self.got.append(text)
  197. async def close(self, code=1000, message=b""):
  198. self.closed = True
  199. self.close_code = code
  200. async def test_a_slow_reader_does_not_delay_the_others(self):
  201. gate = asyncio.Event()
  202. slow, fast = self.Socket(gate), self.Socket()
  203. slow_box, fast_box = relay.Outbox(slow, limit=10_000), relay.Outbox(fast, limit=10_000)
  204. for i in range(5):
  205. self.assertTrue(slow_box.put(b"m" * 1000)) # never waits, even though nothing is read
  206. self.assertTrue(fast_box.put(bytes([i]) * 10))
  207. await asyncio.sleep(0.05)
  208. self.assertEqual(len(fast.got), 5) # all of them, in order
  209. self.assertEqual([g[0] for g in fast.got], [0, 1, 2, 3, 4])
  210. self.assertEqual(slow.got, [])
  211. gate.set()
  212. await asyncio.sleep(0.05)
  213. self.assertEqual(len(slow.got), 5)
  214. self.assertEqual(slow_box.waiting, 0)
  215. await slow_box.finish()
  216. await fast_box.finish()
  217. async def test_a_peer_over_its_queue_limit_is_closed(self):
  218. gate = asyncio.Event()
  219. slow = self.Socket(gate)
  220. box = relay.Outbox(slow, limit=2500)
  221. self.assertTrue(box.put(b"x" * 1000))
  222. self.assertTrue(box.put(b"x" * 1000))
  223. self.assertFalse(box.put(b"x" * 1000)) # over 2500 waiting: closed as too slow
  224. await asyncio.sleep(0.01)
  225. self.assertTrue(slow.closed)
  226. self.assertEqual(slow.close_code, relay.CLOSE_SLOW)
  227. self.assertFalse(box.put(b"y"))
  228. gate.set()
  229. await box.finish()
  230. async def test_control_messages_keep_their_place_among_frames(self):
  231. sock = self.Socket()
  232. room = relay.Room("abcdefghij", "t" * 43, "h" * 43, "client")
  233. room.peers[2] = sock
  234. room.outboxes[2] = relay.Outbox(sock)
  235. room.outboxes[2].put(b"frame-1")
  236. await relay.broadcast(room, {"type": "join", "peer": 3})
  237. room.outboxes[2].put(b"frame-2")
  238. await asyncio.sleep(0.02)
  239. self.assertEqual(sock.got[0], b"frame-1")
  240. self.assertIn('"join"', sock.got[1])
  241. self.assertEqual(sock.got[2], b"frame-2")
  242. await room.outboxes[2].finish()
  243. class RelayKickTests(unittest.IsolatedAsyncioTestCase):
  244. """Round 190on: the host removes a guest (POST /v1/rooms/<room>/kick): its slot is freed, its address stays out of
  245. the room, and the room token can change for new joins while the peers already in stay connected."""
  246. async def asyncSetUp(self):
  247. from aiohttp.test_utils import TestClient, TestServer
  248. self.patches = [patch.object(relay, "rooms", {}), patch.object(relay, "room_limiter", common.RateLimiter(100, 3600)),
  249. patch.object(relay, "connect_limiter", common.RateLimiter(1000, 60))]
  250. for p in self.patches:
  251. p.start()
  252. self.client = TestClient(TestServer(relay.make_app()))
  253. await self.client.start_server()
  254. async def asyncTearDown(self):
  255. await self.client.close()
  256. for p in reversed(self.patches):
  257. p.stop()
  258. async def open_room(self, token):
  259. r = await self.client.post("/v1/rooms", json={"token": token}, headers={"X-Forwarded-For": "192.0.2.1"})
  260. self.assertEqual(r.status, 201)
  261. body = await r.json()
  262. return body["room"], body["hostToken"]
  263. async def join(self, room, token, ip):
  264. ws = await self.client.ws_connect(f"/v1/rooms/{room}/ws", protocols=(relay.SUBPROTOCOL,),
  265. headers={"Authorization": f"Bearer {token}", "X-Forwarded-For": ip})
  266. welcome = await ws.receive_json(timeout=3)
  267. self.assertEqual(welcome["type"], "welcome")
  268. return ws, welcome["peer"]
  269. async def try_join(self, room, token, ip):
  270. from aiohttp import WSServerHandshakeError
  271. try:
  272. ws, _ = await self.join(room, token, ip)
  273. except WSServerHandshakeError as e:
  274. return e.status
  275. await ws.close()
  276. return 101
  277. async def kick(self, room, host_token, body, ip="192.0.2.1"):
  278. r = await self.client.post(f"/v1/rooms/{room}/kick", json=body,
  279. headers={"Authorization": f"Bearer {host_token}", "X-Forwarded-For": ip})
  280. return r.status, (await r.json() if r.status == 200 else None)
  281. async def next_binary(self, ws):
  282. while True:
  283. msg = await ws.receive(timeout=3)
  284. if msg.type.name == "BINARY":
  285. return msg.data
  286. if msg.type.name in ("CLOSE", "CLOSED", "CLOSING", "ERROR"):
  287. return None
  288. async def test_remove_with_a_new_code_for_new_joins_only(self):
  289. old, new = "a" * 43, "b" * 43
  290. room, host_token = await self.open_room(old)
  291. host, host_peer = await self.join(room, old, "192.0.2.1")
  292. ana, ana_peer = await self.join(room, old, "198.51.100.7")
  293. lia, lia_peer = await self.join(room, old, "203.0.113.9")
  294. self.assertEqual(await self.kick(room, "x" * 43, {"peer": ana_peer}), (401, None))
  295. status, body = await self.kick(room, host_token, {"peer": ana_peer, "token": new})
  296. self.assertEqual(status, 200)
  297. self.assertTrue(body["removed"])
  298. # Ana's socket is closed with 4003; her slot is free at once
  299. while True:
  300. msg = await ana.receive(timeout=3)
  301. if msg.type.name in ("CLOSE", "CLOSED"):
  302. break
  303. self.assertEqual(ana.close_code, relay.CLOSE_REMOVED)
  304. for _ in range(100): # (the relay's side of the connection ends right after)
  305. if ana_peer not in relay.rooms[room].peers:
  306. break
  307. await asyncio.sleep(0.01)
  308. self.assertNotIn(ana_peer, relay.rooms[room].peers)
  309. # the host and Lia stay connected and still reach each other
  310. await host.send_bytes(bytes([lia_peer]) + b"still here")
  311. self.assertEqual(await self.next_binary(lia), bytes([host_peer]) + b"still here")
  312. # the old code no longer lets anybody in; Ana is refused with the new one too (her address)
  313. self.assertEqual(await self.try_join(room, old, "192.0.2.200"), 401)
  314. self.assertEqual(await self.try_join(room, new, "198.51.100.7"), 403)
  315. # somebody new with the new code takes the free slot
  316. mia, mia_peer = await self.join(room, new, "192.0.2.77")
  317. self.assertEqual(mia_peer, ana_peer)
  318. for ws in (host, lia, mia):
  319. await ws.close()
  320. async def test_remove_keeping_the_code(self):
  321. code = "c" * 43
  322. room, host_token = await self.open_room(code)
  323. host, _ = await self.join(room, code, "192.0.2.1")
  324. ana, ana_peer = await self.join(room, code, "198.51.100.7")
  325. self.assertEqual((await self.kick(room, host_token, {"peer": ana_peer}))[0], 200)
  326. await ana.receive(timeout=3)
  327. # the code still works for others, not for the removed guest's address
  328. self.assertEqual(await self.try_join(room, code, "198.51.100.7"), 403)
  329. self.assertEqual(await self.try_join(room, code, "203.0.113.50"), 101)
  330. # without "ban" the guest may come back (the host only freed the slot)
  331. lia, lia_peer = await self.join(room, code, "203.0.113.9")
  332. self.assertEqual((await self.kick(room, host_token, {"peer": lia_peer, "ban": False}))[0], 200)
  333. await lia.receive(timeout=3)
  334. self.assertEqual(await self.try_join(room, code, "203.0.113.9"), 101)
  335. await host.close()
  336. async def test_a_guest_on_the_hosts_network_is_removed_without_locking_the_host_out(self):
  337. code = "d" * 43
  338. room, host_token = await self.open_room(code)
  339. host, _ = await self.join(room, code, "192.0.2.1")
  340. same, same_peer = await self.join(room, code, "192.0.2.1")
  341. self.assertEqual((await self.kick(room, host_token, {"peer": same_peer}))[0], 200)
  342. await same.receive(timeout=3)
  343. self.assertEqual(relay.rooms[room].banned, set())
  344. self.assertEqual(await self.try_join(room, code, "192.0.2.1"), 101)
  345. await host.close()
  346. async def test_kick_rejects_bad_bodies(self):
  347. room, host_token = await self.open_room("e" * 43)
  348. for body in ({"peer": "1"}, {"peer": 9}, {"peer": -1}, {"peer": True}, {"peer": 1, "ban": "yes"}, {"peer": 1, "token": "short"}):
  349. self.assertEqual((await self.kick(room, host_token, body))[0], 400, body)
  350. self.assertEqual((await self.kick("zzzzzzzzzz", host_token, {"peer": 1}))[0], 404)
  351. # peer 0 with a token only changes the token; nobody is removed
  352. status, body = await self.kick(room, host_token, {"peer": 0, "token": "f" * 43})
  353. self.assertEqual((status, body["removed"]), (200, False))
  354. self.assertEqual(await self.try_join(room, "e" * 43, "203.0.113.1"), 401)
  355. self.assertEqual(await self.try_join(room, "f" * 43, "203.0.113.1"), 101)
  356. if __name__ == "__main__":
  357. unittest.main()