test_server.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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"]