| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- from __future__ import annotations
- import json
- import shutil
- import sys
- import threading
- import urllib.error
- import urllib.request
- from pathlib import Path
- import pytest
- ROOT = Path(__file__).resolve().parents[2]
- VIEWER_ROOT = ROOT / "tools" / "board-viewer"
- WEB_ROOT = VIEWER_ROOT / "web"
- GENERATED = VIEWER_ROOT / "generated"
- sys.path.insert(0, str(VIEWER_ROOT))
- from board_viewer.assets import AssetIntegrityError # noqa: E402
- from board_viewer.server import create_server # noqa: E402
- class RunningServer:
- def __init__(self, generated: Path) -> None:
- self.server = create_server(WEB_ROOT, generated, port=0, repository_root=ROOT)
- self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
- def __enter__(self) -> str:
- self.thread.start()
- host, port = self.server.server_address[:2]
- return f"http://{host}:{port}"
- def __exit__(self, exc_type, exc, traceback) -> None:
- self.server.shutdown()
- self.server.server_close()
- self.thread.join(timeout=5)
- def request(url: str, *, method: str = "GET") -> tuple[int, bytes, dict[str, str]]:
- req = urllib.request.Request(url, method=method)
- try:
- with urllib.request.urlopen(req, timeout=5) as response:
- return response.status, response.read(), dict(response.headers.items())
- except urllib.error.HTTPError as error:
- return error.code, error.read(), dict(error.headers.items())
- def test_server_binds_loopback_and_serves_only_whitelisted_get_head_paths() -> None:
- with RunningServer(GENERATED) as base:
- status, body, headers = request(base + "/")
- assert status == 200
- assert "电路板选脚查看器" in body.decode("utf-8")
- assert headers["X-Content-Type-Options"] == "nosniff"
- assert "default-src 'self'" in headers["Content-Security-Policy"]
- status, body, _ = request(base + "/generated/board-data.json", method="HEAD")
- assert status == 200
- assert body == b""
- status, body, _ = request(base + "/api/status")
- payload = json.loads(body)
- assert status == 200
- assert payload["status"] == "pass"
- assert payload["recommendationsEnabled"] is True
- assert payload["adcCopyEnabled"] is True
- @pytest.mark.parametrize(
- "path",
- [
- "/../AGENTS.md",
- "/%2e%2e/AGENTS.md",
- "/generated/../web/index.html",
- "/generated/%2e%2e/web/index.html",
- "/C:/Windows/win.ini",
- "/unknown.txt",
- ],
- )
- def test_server_rejects_directory_traversal_and_arbitrary_files(path: str) -> None:
- with RunningServer(GENERATED) as base:
- status, _, _ = request(base + path)
- assert status == 404
- @pytest.mark.parametrize("method", ["POST", "PUT", "PATCH", "DELETE"])
- def test_server_rejects_mutating_methods(method: str) -> None:
- with RunningServer(GENERATED) as base:
- status, _, headers = request(base + "/", method=method)
- assert status == 405
- assert headers["Allow"] == "GET, HEAD"
- def test_server_refuses_non_loopback_bind() -> None:
- with pytest.raises(ValueError, match="127.0.0.1"):
- create_server(WEB_ROOT, GENERATED, host="0.0.0.0", port=0, repository_root=ROOT)
- def test_server_refuses_tampered_generated_asset(tmp_path: Path) -> None:
- copied = tmp_path / "generated"
- shutil.copytree(GENERATED, copied)
- (copied / "board-data.json").write_text("tampered", encoding="utf-8")
- with pytest.raises(AssetIntegrityError, match="board-data.json"):
- create_server(WEB_ROOT, copied, port=0, repository_root=ROOT)
- def test_server_starts_read_only_but_disables_recommendations_when_sources_are_stale(tmp_path: Path) -> None:
- copied = tmp_path / "generated"
- shutil.copytree(GENERATED, copied)
- build_info_path = copied / "build-info.json"
- build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
- build_info["sources"]["annotations"]["path"] = "config/does-not-exist.json"
- build_info_path.write_text(json.dumps(build_info), encoding="utf-8")
- with RunningServer(copied) as base:
- status, body, _ = request(base + "/api/status")
- payload = json.loads(body)
- assert status == 200
- assert payload["status"] == "stale_sources"
- assert payload["recommendationsEnabled"] is False
- assert payload["adcCopyEnabled"] is False
- assert payload["staleSources"] == ["missing:annotations"]
|