"""SPA 静态托管 404 收敛(安全)。 合法 URL/API 之外的未知路径一律 404:前端无路径路由(仅 query 传参), SPA 回退仅覆盖根路径 /;已注册 API 与存在的静态文件照常响应。 """ from __future__ import annotations import pytest @pytest.fixture() def spa_client(flask_app, tmp_path, monkeypatch): """临时 dist(index.html + assets/app.js),不依赖开发机构建产物。""" (tmp_path / "index.html").write_text("index", encoding="utf-8") assets = tmp_path / "assets" assets.mkdir() (assets / "app.js").write_text("console.log(1)", encoding="utf-8") import app as app_module monkeypatch.setattr(app_module, "FRONTEND_DIST", tmp_path) return flask_app.test_client() def test_root_serves_index(spa_client): response = spa_client.get("/") assert response.status_code == 200 assert b"index" in response.data def test_existing_asset_served(spa_client): assert spa_client.get("/assets/app.js").status_code == 200 def test_health_still_ok(spa_client): assert spa_client.get("/api/health").status_code == 200 @pytest.mark.parametrize( "path", [ "/admin.php", "/wp-login", "/index2.html", "/.env", "/api/v1/not-implemented", "/api/v2/evil", # 畸形路径字符(Windows 非法字符、NUL):不得异常,统一 404 "/%3Cscript%3E", "/a|b", "/c:d", "/%00", ], ) def test_unknown_paths_return_404(spa_client, path): response = spa_client.get(path) assert response.status_code == 404