smoke.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """End-to-end smoke test of the LYNX SHARE server (share links + relay).
  2. python3 server/tests/smoke.py # the live server (api./relay.lynx-share.com)
  3. python3 server/tests/smoke.py http://127.0.0.1:8081 ws://127.0.0.1:8082 # local services
  4. Needs aiohttp (pip install aiohttp, or apt install python3-aiohttp). Creates one small share and one room, checks
  5. them, and deletes both. Exit code 0 = all good.
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. import hashlib
  10. import io
  11. import json
  12. import os
  13. import sys
  14. import zipfile
  15. import aiohttp
  16. API = sys.argv[1] if len(sys.argv) > 1 else "https://api.lynx-share.com"
  17. RELAY = sys.argv[2] if len(sys.argv) > 2 else "wss://relay.lynx-share.com"
  18. RELAY_HTTP = RELAY.replace("wss://", "https://").replace("ws://", "http://")
  19. failures = 0
  20. def check(cond: bool, what: str) -> None:
  21. global failures
  22. print(("ok " if cond else "FAIL ") + what)
  23. if not cond:
  24. failures += 1
  25. def make_pack(size: int) -> bytes:
  26. buf = io.BytesIO()
  27. with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as z:
  28. z.writestr("project.lynx", json.dumps({"smoke": True}))
  29. z.writestr("Samples/noise.bin", os.urandom(size))
  30. return buf.getvalue()
  31. async def shares(s: aiohttp.ClientSession) -> None:
  32. async with s.get(f"{API}/health") as r:
  33. h = await r.json()
  34. check(r.status == 200 and h.get("ok") and h.get("service") == "lynx-api", f"api /health {r.status} {h}")
  35. pack = make_pack(3 * 1024 * 1024 + 123)
  36. sha = hashlib.sha256(pack).hexdigest()
  37. # bad requests are refused
  38. async with s.post(f"{API}/v1/shares", json={"name": "x.exe", "size": 10}) as r:
  39. check(r.status == 400, f"wrong extension refused ({r.status})")
  40. async with s.post(f"{API}/v1/shares", json={"name": "big.lynxpack", "size": 3 * 1024 ** 3}) as r:
  41. check(r.status == 413, f"over 2 GB refused ({r.status})")
  42. async with s.post(f"{API}/v1/shares", json={"name": "Smoke test.lynxpack", "size": len(pack), "days": 1,
  43. "sha256": sha}) as r:
  44. c = await r.json()
  45. check(r.status == 201 and len(c["id"]) == 26 and c["token"], f"create {r.status}")
  46. sid, tok = c["id"], c["token"]
  47. auth = {"Authorization": f"Bearer {tok}"}
  48. async with s.get(f"{API}/v1/shares/{sid}/download") as r:
  49. check(r.status == 409, f"download before upload finished refused ({r.status})")
  50. async with s.patch(c["uploadUrl"], data=pack[:100], headers={"Upload-Offset": "0"}) as r:
  51. check(r.status == 401, f"upload without token refused ({r.status})")
  52. async with s.patch(c["uploadUrl"], data=b"MZ" + pack[2:100], headers={**auth, "Upload-Offset": "0"}) as r:
  53. check(r.status == 415, f"non-zip refused ({r.status})")
  54. # resumable upload in two parts, with a wrong offset in between
  55. half = len(pack) // 2
  56. async with s.patch(c["uploadUrl"], data=pack[:half], headers={**auth, "Upload-Offset": "0"}) as r:
  57. j = await r.json()
  58. check(r.status == 200 and j["offset"] == half and not j["complete"], f"part 1 ({r.status})")
  59. async with s.patch(c["uploadUrl"], data=pack[half:], headers={**auth, "Upload-Offset": "0"}) as r:
  60. check(r.status == 409 and r.headers.get("Upload-Offset") == str(half), f"wrong offset refused ({r.status})")
  61. async with s.get(f"{API}/v1/shares/{sid}") as r:
  62. j = await r.json()
  63. check(j["received"] == half, f"received after part 1 = {j['received']}")
  64. async with s.patch(c["uploadUrl"], data=pack[half:], headers={**auth, "Upload-Offset": str(half)}) as r:
  65. j = await r.json()
  66. check(r.status == 200 and j["complete"] and j["sha256"] == sha, f"part 2 completes, sha256 ok ({r.status})")
  67. async with s.get(j["downloadUrl"]) as r:
  68. body = await r.read()
  69. check(r.status == 200 and body == pack, f"download identical ({len(body)} bytes)")
  70. check("attachment" in r.headers.get("Content-Disposition", ""), "download is an attachment")
  71. async with s.get(j["downloadUrl"], headers={"Range": "bytes=10-19"}) as r:
  72. body = await r.read()
  73. check(r.status == 206 and body == pack[10:20], f"range request ({r.status})")
  74. async with s.get(j["url"]) as r:
  75. text = await r.text()
  76. check(r.status == 200 and "Smoke test.lynxpack" in text and "Download" in text, f"link page ({r.status})")
  77. async with s.get(f"{API}/v1/shares/{'a' * 26}") as r:
  78. check(r.status == 404, f"unknown id 404 ({r.status})")
  79. async with s.get(f"{API}/v1/shares/") as r:
  80. check(r.status == 404, f"no listing ({r.status})")
  81. async with s.delete(f"{API}/v1/shares/{sid}") as r:
  82. check(r.status == 401, f"delete without token refused ({r.status})")
  83. async with s.delete(f"{API}/v1/shares/{sid}", headers=auth) as r:
  84. check(r.status == 204, f"delete ({r.status})")
  85. async with s.get(j["downloadUrl"]) as r:
  86. check(r.status == 404, f"gone after delete ({r.status})")
  87. async def relay(s: aiohttp.ClientSession) -> None:
  88. async with s.get(f"{RELAY_HTTP}/health") as r:
  89. h = await r.json()
  90. check(r.status == 200 and h.get("service") == "lynx-relay", f"relay /health {r.status} {h}")
  91. limits = h.get("limits", {})
  92. check(limits.get("frame", 0) >= 1024 * 1024 and limits.get("roomBytes", 0) > 8 * 1024 ** 3
  93. and limits.get("clientBytesDay", 0) >= limits.get("roomBytes", 0) and 1 <= limits.get("roomsPerClient", 0) <= 20
  94. and limits.get("roomHours", 0) >= 24 and limits.get("idleHours", 0) >= 1,
  95. f"relay limits (round 190ah) {limits}")
  96. async with s.post(f"{RELAY_HTTP}/v1/rooms") as r:
  97. room = await r.json()
  98. check(r.status == 201 and room["maxPeers"] == 4, f"room created ({r.status})")
  99. url = f"{RELAY}/v1/rooms/{room['room']}/ws"
  100. auth = {"Authorization": f"Bearer {room['token']}"}
  101. try:
  102. async with s.ws_connect(url, headers={"Authorization": "Bearer wrong"}):
  103. check(False, "wrong room token refused")
  104. except aiohttp.WSServerHandshakeError as e:
  105. check(e.status == 401, f"wrong room token refused ({e.status})")
  106. peers = []
  107. for i in range(4):
  108. if i == 3: # the browser way: token as a second subprotocol
  109. ws = await s.ws_connect(url, protocols=("lynx-relay.v1", "token." + room["token"]))
  110. else:
  111. ws = await s.ws_connect(url, headers=auth, protocols=("lynx-relay.v1",))
  112. w = await ws.receive_json(timeout=5)
  113. check(w["type"] == "welcome" and w["peer"] == i + 1, f"peer {i + 1} welcome {w}")
  114. peers.append(ws)
  115. try:
  116. async with s.ws_connect(url, headers=auth):
  117. check(False, "5th peer refused")
  118. except aiohttp.WSServerHandshakeError as e:
  119. check(e.status == 409, f"5th peer refused ({e.status})")
  120. async def next_binary(ws):
  121. while True:
  122. m = await ws.receive(timeout=5)
  123. if m.type == aiohttp.WSMsgType.BINARY:
  124. return m.data
  125. # echo (destination = own peer id), unicast, broadcast
  126. await peers[0].send_bytes(bytes([1]) + b"echo")
  127. check(await next_binary(peers[0]) == bytes([1]) + b"echo", "echo to self")
  128. await peers[0].send_bytes(bytes([3]) + b"to three")
  129. check(await next_binary(peers[2]) == bytes([1]) + b"to three", "peer 1 -> peer 3")
  130. big = os.urandom(512 * 1024)
  131. await peers[1].send_bytes(bytes([0]) + big)
  132. got = [await next_binary(p) for p in (peers[0], peers[2], peers[3])]
  133. check(all(g == bytes([2]) + big for g in got), "peer 2 broadcast 512 KB to the 3 others")
  134. # control (text) messages are small: a long one is refused and the connection goes on
  135. await peers[3].send_json({"type": "x" * 5000})
  136. while True:
  137. m = await peers[3].receive_json(timeout=5)
  138. if m["type"] == "error":
  139. break
  140. check("too long" in m["error"], f"an over-long control message is refused ({m['error']})")
  141. await peers[3].send_json({"type": "ping", "t": 7})
  142. while True:
  143. m = await peers[3].receive_json(timeout=5)
  144. if m["type"] == "pong":
  145. break
  146. check(m["t"] == 7, "ping/pong")
  147. # a room whose token the host chose (LYNX derives it from the invite code): not echoed back, and it works
  148. chosen = "lynx-smoke-" + os.urandom(24).hex()
  149. async with s.post(f"{RELAY_HTTP}/v1/rooms", json={"token": "short"}) as r:
  150. check(r.status == 400, f"a too short chosen token refused ({r.status})")
  151. async with s.post(f"{RELAY_HTTP}/v1/rooms", json={"token": chosen}) as r:
  152. room2 = await r.json()
  153. check(r.status == 201 and room2["token"] == "", f"room with a chosen token ({r.status})")
  154. url2 = f"{RELAY}/v1/rooms/{room2['room']}/ws"
  155. try:
  156. async with s.ws_connect(url2, headers=auth):
  157. check(False, "the other room's token refused")
  158. except aiohttp.WSServerHandshakeError as e:
  159. check(e.status == 401, f"the other room's token refused ({e.status})")
  160. ws2 = await s.ws_connect(url2, headers={"Authorization": f"Bearer {chosen}"}, protocols=("lynx-relay.v1",))
  161. w = await ws2.receive_json(timeout=5)
  162. check(w["type"] == "welcome" and w["peer"] == 1, f"chosen token connects {w}")
  163. async with s.delete(f"{RELAY_HTTP}/v1/rooms/{room2['room']}",
  164. headers={"Authorization": f"Bearer {room2['hostToken']}"}) as r:
  165. check(r.status == 204, f"room 2 closed ({r.status})")
  166. await ws2.close()
  167. # a frame over the size limit (1 MiB) closes only the connection that sent it; nothing of it is relayed
  168. async with s.post(f"{RELAY_HTTP}/v1/rooms") as r:
  169. room3 = await r.json()
  170. check(r.status == 201, f"room 3 created ({r.status})")
  171. url3 = f"{RELAY}/v1/rooms/{room3['room']}/ws"
  172. auth3 = {"Authorization": f"Bearer {room3['token']}"}
  173. a = await s.ws_connect(url3, headers=auth3, protocols=("lynx-relay.v1",), max_msg_size=8 * 1024 * 1024)
  174. b = await s.ws_connect(url3, headers=auth3, protocols=("lynx-relay.v1",), max_msg_size=8 * 1024 * 1024)
  175. await a.receive_json(timeout=5)
  176. await b.receive_json(timeout=5)
  177. await a.send_bytes(bytes([0]) + os.urandom(1024 * 1024 + 4096))
  178. closed, leaked = False, False
  179. for _ in range(20):
  180. m = await a.receive(timeout=5)
  181. if m.type in (aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.ERROR):
  182. closed = True
  183. break
  184. for _ in range(5):
  185. try:
  186. m = await b.receive(timeout=1)
  187. except asyncio.TimeoutError:
  188. break
  189. if m.type == aiohttp.WSMsgType.BINARY:
  190. leaked = True
  191. if m.type == aiohttp.WSMsgType.TEXT and '"leave"' in m.data:
  192. break
  193. check(closed and not leaked, f"a frame over 1 MiB closes its sender ({closed}) and is not relayed ({not leaked})")
  194. await b.send_bytes(bytes([2]) + b"still here")
  195. check(await next_binary(b) == bytes([2]) + b"still here", "the other peer's connection goes on")
  196. await a.close()
  197. await b.close()
  198. async with s.delete(f"{RELAY_HTTP}/v1/rooms/{room3['room']}",
  199. headers={"Authorization": f"Bearer {room3['hostToken']}"}) as r:
  200. check(r.status == 204, f"room 3 closed ({r.status})")
  201. async with s.delete(f"{RELAY_HTTP}/v1/rooms/{room['room']}") as r:
  202. check(r.status == 401, f"close without host token refused ({r.status})")
  203. async with s.delete(f"{RELAY_HTTP}/v1/rooms/{room['room']}",
  204. headers={"Authorization": f"Bearer {room['hostToken']}"}) as r:
  205. check(r.status == 204, f"room closed by host ({r.status})")
  206. for ws in peers:
  207. while (await ws.receive(timeout=5)).type not in (aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED,
  208. aiohttp.WSMsgType.CLOSING):
  209. pass
  210. await ws.close()
  211. check(all(ws.closed for ws in peers), "every peer disconnected")
  212. async def main() -> int:
  213. async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120)) as s:
  214. await shares(s)
  215. await relay(s)
  216. print("FAILURES:", failures)
  217. return 1 if failures else 0
  218. if __name__ == "__main__":
  219. sys.exit(asyncio.run(main()))