test_server.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. from __future__ import annotations
  2. import json
  3. import shutil
  4. import sys
  5. import threading
  6. import urllib.error
  7. import urllib.request
  8. from pathlib import Path
  9. import pytest
  10. ROOT = Path(__file__).resolve().parents[2]
  11. VIEWER_ROOT = ROOT / "tools" / "board-viewer"
  12. WEB_ROOT = VIEWER_ROOT / "web"
  13. GENERATED = VIEWER_ROOT / "generated"
  14. sys.path.insert(0, str(VIEWER_ROOT))
  15. from board_viewer.assets import AssetIntegrityError # noqa: E402
  16. from board_viewer.server import create_server # noqa: E402
  17. class RunningServer:
  18. def __init__(self, generated: Path) -> None:
  19. self.server = create_server(WEB_ROOT, generated, port=0, repository_root=ROOT)
  20. self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
  21. def __enter__(self) -> str:
  22. self.thread.start()
  23. host, port = self.server.server_address[:2]
  24. return f"http://{host}:{port}"
  25. def __exit__(self, exc_type, exc, traceback) -> None:
  26. self.server.shutdown()
  27. self.server.server_close()
  28. self.thread.join(timeout=5)
  29. def request(url: str, *, method: str = "GET") -> tuple[int, bytes, dict[str, str]]:
  30. req = urllib.request.Request(url, method=method)
  31. try:
  32. with urllib.request.urlopen(req, timeout=5) as response:
  33. return response.status, response.read(), dict(response.headers.items())
  34. except urllib.error.HTTPError as error:
  35. return error.code, error.read(), dict(error.headers.items())
  36. def test_server_binds_loopback_and_serves_only_whitelisted_get_head_paths() -> None:
  37. with RunningServer(GENERATED) as base:
  38. status, body, headers = request(base + "/")
  39. assert status == 200
  40. assert "电路板选脚查看器" in body.decode("utf-8")
  41. assert headers["X-Content-Type-Options"] == "nosniff"
  42. assert "default-src 'self'" in headers["Content-Security-Policy"]
  43. status, body, _ = request(base + "/generated/board-data.json", method="HEAD")
  44. assert status == 200
  45. assert body == b""
  46. status, body, _ = request(base + "/api/status")
  47. payload = json.loads(body)
  48. assert status == 200
  49. assert payload["status"] == "pass"
  50. assert payload["recommendationsEnabled"] is True
  51. assert payload["adcCopyEnabled"] is True
  52. @pytest.mark.parametrize(
  53. "path",
  54. [
  55. "/../AGENTS.md",
  56. "/%2e%2e/AGENTS.md",
  57. "/generated/../web/index.html",
  58. "/generated/%2e%2e/web/index.html",
  59. "/C:/Windows/win.ini",
  60. "/unknown.txt",
  61. ],
  62. )
  63. def test_server_rejects_directory_traversal_and_arbitrary_files(path: str) -> None:
  64. with RunningServer(GENERATED) as base:
  65. status, _, _ = request(base + path)
  66. assert status == 404
  67. @pytest.mark.parametrize("method", ["POST", "PUT", "PATCH", "DELETE"])
  68. def test_server_rejects_mutating_methods(method: str) -> None:
  69. with RunningServer(GENERATED) as base:
  70. status, _, headers = request(base + "/", method=method)
  71. assert status == 405
  72. assert headers["Allow"] == "GET, HEAD"
  73. def test_server_refuses_non_loopback_bind() -> None:
  74. with pytest.raises(ValueError, match="127.0.0.1"):
  75. create_server(WEB_ROOT, GENERATED, host="0.0.0.0", port=0, repository_root=ROOT)
  76. def test_server_refuses_tampered_generated_asset(tmp_path: Path) -> None:
  77. copied = tmp_path / "generated"
  78. shutil.copytree(GENERATED, copied)
  79. (copied / "board-data.json").write_text("tampered", encoding="utf-8")
  80. with pytest.raises(AssetIntegrityError, match="board-data.json"):
  81. create_server(WEB_ROOT, copied, port=0, repository_root=ROOT)
  82. def test_server_starts_read_only_but_disables_recommendations_when_sources_are_stale(tmp_path: Path) -> None:
  83. copied = tmp_path / "generated"
  84. shutil.copytree(GENERATED, copied)
  85. build_info_path = copied / "build-info.json"
  86. build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
  87. build_info["sources"]["annotations"]["path"] = "config/does-not-exist.json"
  88. build_info_path.write_text(json.dumps(build_info), encoding="utf-8")
  89. with RunningServer(copied) as base:
  90. status, body, _ = request(base + "/api/status")
  91. payload = json.loads(body)
  92. assert status == 200
  93. assert payload["status"] == "stale_sources"
  94. assert payload["recommendationsEnabled"] is False
  95. assert payload["adcCopyEnabled"] is False
  96. assert payload["staleSources"] == ["missing:annotations"]
  97. def test_server_serves_v2_0_mainboard_and_fan_board_assets() -> None:
  98. with RunningServer(GENERATED) as base:
  99. # V2.0 Mainboard status and board data
  100. status, body, _ = request(base + "/api/status?version=v2_0")
  101. assert status == 200
  102. payload = json.loads(body)
  103. assert payload["status"] == "pass"
  104. assert payload["version"] == "v2_0"
  105. assert payload["counts"]["footprints"] == 1457
  106. assert payload["counts"]["touchpoints"] == 74
  107. assert payload["counts"]["pads"] == 493
  108. assert payload["counts"]["resistors"] == 730
  109. status, body, _ = request(base + "/generated-v2_0/board-data.json")
  110. assert status == 200
  111. data = json.loads(body)
  112. assert data["schema"] == "board-viewer-data-v2"
  113. assert data["board"]["id"] == "fcb_fpga_mcu_v2_0_20260914"
  114. con_refs = {tp["reference"] for tp in data["touchpoints"]}
  115. assert {
  116. "CON12", "CON134", "CON77", "CON147", "CON148", "CON149", "CON150",
  117. "CON154", "CON155", "CON164", "CON165", "CON170", "CON172", "CON173", "CON174",
  118. "J3", "J19", "J25", "TP32", "TP33", "TP34",
  119. }.issubset(con_refs)
  120. res_refs = {r["reference"] for r in data["resistors"]}
  121. assert {"R1875", "R1876", "R818", "R819", "R1225", "R1226", "R1898", "R1899", "R1920", "R1921"}.issubset(res_refs)
  122. # Check CON12 Host TTL CPLD ball mapping
  123. con12 = next(tp for tp in data["touchpoints"] if tp["reference"] == "CON12")
  124. pins12 = {str(p["number"]): p for p in con12["pins"]}
  125. assert pins12["3"]["fpga"]["ball"] == "K2"
  126. assert pins12["4"]["fpga"]["ball"] == "J4"
  127. # Check CON134 Host RS232 CPLD ball mapping
  128. con134 = next(tp for tp in data["touchpoints"] if tp["reference"] == "CON134")
  129. pins134 = {str(p["number"]): p for p in con134["pins"]}
  130. assert pins134["1"]["fpga"]["ball"] == "T14"
  131. assert pins134["2"]["fpga"]["ball"] == "R13"
  132. # Check CON77 BMC RS232 CPLD ball mapping
  133. con77 = next(tp for tp in data["touchpoints"] if tp["reference"] == "CON77")
  134. pins77 = {str(p["number"]): p for p in con77["pins"]}
  135. assert pins77["1"]["fpga"]["ball"] == "L10"
  136. assert pins77["2"]["fpga"]["ball"] == "M9"
  137. # V2.0 Fan Board status and board data
  138. status, body, _ = request(base + "/api/status?version=v2_0_fan")
  139. assert status == 200
  140. fan_payload = json.loads(body)
  141. assert fan_payload["status"] == "pass"
  142. assert fan_payload["version"] == "v2_0_fan"
  143. assert fan_payload["counts"]["footprints"] == 33
  144. assert fan_payload["counts"]["touchpoints"] == 7
  145. assert fan_payload["counts"]["pads"] == 66
  146. status, body, _ = request(base + "/generated-v2_0_fan/board-data.json")
  147. assert status == 200
  148. fan_data = json.loads(body)
  149. assert fan_data["board"]["id"] == "fcb_fan_v2_0_20260914"
  150. fan_refs = {tp["reference"] for tp in fan_data["touchpoints"]}
  151. assert {"CON168", "CON8", "CON169", "CON170", "CON171", "CON2", "CON172"}.issubset(fan_refs)
  152. # Documents and schematics
  153. status, _, headers = request(base + "/schematics/fcb_fpga_mcu_v2_0.pdf", method="HEAD")
  154. assert status == 200
  155. assert headers["Content-Type"] == "application/pdf"
  156. status, _, headers = request(base + "/docs/FCB_FAN_V2_0_ANALYSIS.md", method="HEAD")
  157. assert status == 200
  158. assert "text/markdown" in headers["Content-Type"]
  159. status, body, headers = request(base + "/cpld-arch-data.mjs")
  160. assert status == 200
  161. assert "text/javascript" in headers["Content-Type"]
  162. assert "CPLD_MENU_TREE" in body.decode("utf-8")
  163. status, body, headers = request(base + "/wasm-engine.mjs")
  164. assert status == 200
  165. assert "text/javascript" in headers["Content-Type"]
  166. assert "BoardWasmAccelerator" in body.decode("utf-8")
  167. status, body, headers = request(base + "/board-accel.wasm")
  168. assert status == 200
  169. assert headers["Content-Type"] == "application/wasm"
  170. assert body[:4] == b"\x00asm"
  171. # Verify Gzip RAM pre-compression shrinks 3.8MB board-data.json by >85% for low-resource clients
  172. gz_req = urllib.request.Request(
  173. base + "/generated-v2_0/board-data.json",
  174. headers={"Accept-Encoding": "gzip"},
  175. )
  176. with urllib.request.urlopen(gz_req, timeout=5) as gz_resp:
  177. gz_bytes = gz_resp.read()
  178. assert gz_resp.headers.get("Content-Encoding") == "gzip"
  179. assert len(gz_bytes) < 450_000