RepoPulse: update "backend/app/main.py" and "backend/tests/test_frontend_routes.py"

Public changes compared with the previous published export:
2 files changed.

Affected areas:
- backend/app: 1 file
- tests: 1 file

Changed files:
- Updated: "backend/app/main.py"
- Added: "backend/tests/test_frontend_routes.py"

Export provenance/manifests refreshed; excluded from the change summary.

Publish curated RepoPulse source from 1201120636c6141d94a4aee81b48b5b001cea045
This commit is contained in:
Public Source Publisher committed 2026-11-20 05:43:52 +00:00
1 parent 787a2b1dc3
commit 131096340e
4 files changed
+83 -5

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
# Public source export
This source snapshot was generated from the private canonical repository at revision `7a60c53ee2c1daebecd66a01656e323f1db72e56`. It contains no private Git history or operational evidence. Changes are published from the canonical repository.
This source snapshot was generated from the private canonical repository at revision `1201120636c6141d94a4aee81b48b5b001cea045`. It contains no private Git history or operational evidence. Changes are published from the canonical repository.
+8 -3
View File
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceRevision": "7a60c53ee2c1daebecd66a01656e323f1db72e56",
"sourceRevision": "1201120636c6141d94a4aee81b48b5b001cea045",
"files": [
{
"path": ".dockerignore",
@@ -74,8 +74,8 @@
},
{
"path": "backend/app/main.py",
"sha256": "06eb422e6a3a42add652557852e2a6ab55c1b63f843490c6788069e0317ecd52",
"bytes": 21812
"sha256": "76590ed2cc36a66aa66612fdd2bda7a75a30e6604ce991e30885f273ecb45d8d",
"bytes": 23006
},
{
"path": "backend/app/models.py",
@@ -147,6 +147,11 @@
"sha256": "e2bf645f1e61d7a986f18066127e32f8ea512f40ad90ec84b22aba1914ad4980",
"bytes": 3651
},
{
"path": "backend/tests/test_frontend_routes.py",
"sha256": "53e22a66df51d559f0ed246dc25556ddb0c918faaa8584946be78f9c7281f041",
"bytes": 2057
},
{
"path": "backend/tests/test_gitea.py",
"sha256": "33a4761b7982cf1cfe492ce27174e7bf8a9b4f73bb0c6a1e41ad32357c092300",
+23 -1
View File
@@ -14,6 +14,7 @@ from fastapi.concurrency import run_in_threadpool
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.types import Scope
from .acquisition import GitAcquirer
@@ -524,10 +525,31 @@ def export_scan(scan_id: str, format: str = Query(default="html", pattern="^(htm
class _FrontendStaticFiles(StaticFiles):
"""Serve the SPA; content-hashed build assets are immutable and cached long-term."""
"""Serve the SPA; content-hashed build assets are immutable and cached long-term.
Client-side routes such as ``/repositories/{id}/findings`` have no file on disk. They
fall back to ``index.html`` so a refresh or a shared link opens the right view, while
API paths, build assets and anything that looks like a file keep an honest 404.
"""
@staticmethod
def _is_client_route(path: str) -> bool:
normalized = path.replace("\\", "/").strip("/")
if not normalized or normalized.split("/", 1)[0] in {"api", "assets", "health"}:
return False
return "." not in normalized.rsplit("/", 1)[-1]
async def get_response(self, path: str, scope: Scope) -> Response:
try:
response = await super().get_response(path, scope)
except (StarletteHTTPException, OSError) as exc:
# Route segments such as "gitea:64" are not valid file names on every platform.
missing = isinstance(exc, OSError) or exc.status_code == 404
if not missing or scope.get("method") not in {"GET", "HEAD"} or not self._is_client_route(path):
if isinstance(exc, OSError):
raise StarletteHTTPException(status_code=404) from exc
raise
response = await super().get_response("index.html", scope)
if response.status_code == 200:
if path.replace("\\", "/").startswith("assets/"):
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
+51
View File
@@ -0,0 +1,51 @@
from __future__ import annotations
from pathlib import Path
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.main import _FrontendStaticFiles
def _client(tmp_path: Path) -> TestClient:
static = tmp_path / "static"
(static / "assets").mkdir(parents=True)
(static / "index.html").write_text("<!doctype html><div id=root></div>", encoding="utf-8")
(static / "assets" / "index-abc123.js").write_text("console.log(1)", encoding="utf-8")
(static / "favicon.svg").write_text("<svg/>", encoding="utf-8")
app = FastAPI()
@app.get("/api/v1/ping")
def ping() -> dict[str, str]:
return {"status": "ok"}
app.mount("/", _FrontendStaticFiles(directory=static, html=True), name="frontend")
return TestClient(app)
def test_client_routes_fall_back_to_the_spa_shell(tmp_path: Path) -> None:
client = _client(tmp_path)
for path in ("/repositories", "/activity", "/queue", "/settings", "/repositories/gitea%3A64/findings"):
response = client.get(path)
assert response.status_code == 200, path
assert "id=root" in response.text
assert response.headers["cache-control"] == "no-cache"
def test_api_assets_and_missing_files_keep_an_honest_404(tmp_path: Path) -> None:
client = _client(tmp_path)
assert client.get("/api/v1/ping").json() == {"status": "ok"}
assert client.get("/api/v1/unknown").status_code == 404
assert client.get("/assets/missing-chunk.js").status_code == 404
assert client.get("/robots.txt").status_code == 404
assert client.post("/repositories").status_code in {404, 405}
def test_hashed_assets_stay_immutable_and_files_are_served_directly(tmp_path: Path) -> None:
client = _client(tmp_path)
asset = client.get("/assets/index-abc123.js")
assert asset.status_code == 200
assert asset.headers["cache-control"] == "public, max-age=31536000, immutable"
assert client.get("/favicon.svg").headers["cache-control"] == "no-cache"
assert client.get("/").headers["cache-control"] == "no-cache"