Make admin and API errors visible and traceable

Return structured JSON errors with request IDs, log unexpected exceptions with tracebacks, and show HTTP and network failures in the admin UI without losing unsaved source.

Preserve publication errors when release listing also fails, handle cancelled preview promises, and add regression tests, browser failure scenarios, and updated API documentation.
This commit is contained in:
2026-11-13 09:55:55 +03:00
parent 88ac95dd19
commit 231490bb7c
19 changed files with 1714 additions and 67 deletions
+98
View File
@@ -52,6 +52,104 @@ class ApiTests(SiteTestCase):
def source(self):
return self.api("GET", "/pages/index/source").json()
def test_unexpected_publish_error_has_json_code_request_id_and_traceback(self):
with (
patch("site_engine.web.api.routes.publish", side_effect=RuntimeError("publish probe")),
self.assertLogs("uvicorn.error", level="ERROR") as captured,
):
response = self.api("POST", "/publish")
self.assertEqual(response.status_code, 500)
detail = response.json()["error"]
self.assertEqual(detail["code"], "internal_error")
self.assertTrue(detail["message"])
self.assertRegex(detail["request_id"], r"^[a-f0-9]{32}$")
self.assertEqual(response.headers["x-request-id"], detail["request_id"])
self.assertIn("no-store", response.headers["cache-control"])
self.assertNotIn("publish probe", response.text)
output = "\n".join(captured.output)
self.assertIn(detail["request_id"], output)
self.assertIn("POST", output)
self.assertIn("/admin/api/v1/publish", output)
self.assertIn("RuntimeError: publish probe", output)
self.assertTrue(any(record.exc_info for record in captured.records))
self.assertNotIn(self.password, output)
self.assertNotIn("test-credential", output)
def test_real_publish_storage_failure_reaches_html_and_logs(self):
# A file instead of the release directory causes a real filesystem failure on every OS.
self.out.write_text("occupied by a file")
with self.assertLogs("uvicorn.error", level="ERROR") as captured:
response = self.client.post(
"/admin/publish",
data={"csrf": self.csrf},
headers={"Origin": "http://testserver", "HX-Request": "true", "HX-Boosted": "true"},
)
self.assertEqual(response.status_code, 500)
self.assertEqual(response.headers["x-error-code"], "storage_error")
self.assertEqual(response.headers["x-admin-error"], "1")
self.assertIn("Ошибка доступа к файлам", response.text)
self.assertIn(response.headers["x-request-id"], response.text)
self.assertIn(response.headers["x-request-id"], "\n".join(captured.output))
self.assertIn("FileExistsError", "\n".join(captured.output))
self.assertEqual(self.out.read_text(), "occupied by a file")
def test_publish_error_keeps_original_error_if_release_listing_also_fails(self):
from site_engine.web.admin.api_client import AdminApi, ApiError
original = AdminApi.call
async def failing(api, method, path, data=None):
if path == "/publish":
raise ApiError(
500, {"error": {"code": "publish_failed", "message": "Publish failure"}}
)
if path == "/releases" and getattr(api, "listed", False):
raise ApiError(
500, {"error": {"code": "list_failed", "message": "Listing failure"}}
)
if path == "/releases":
api.listed = True
return await original(api, method, path, data)
with patch.object(AdminApi, "call", failing):
response = self.client.post(
"/admin/publish", data={"csrf": self.csrf}, headers={"Origin": "http://testserver"}
)
self.assertEqual(response.status_code, 500)
self.assertIn("Publish failure", response.text)
self.assertNotIn("Listing failure", response.text)
self.assertIn("Список релизов недоступен", response.text)
self.assertEqual(response.headers["x-error-code"], "publish_failed")
def test_validation_and_http_errors_include_correlation(self):
for response in (
self.api("POST", "/pages", {}),
self.api("DELETE", "/publish"),
self.api("GET", "/preview/" + "a" * 32 + "/html"),
self.client.get("/admin/api/v1/site"),
):
self.assertGreaterEqual(response.status_code, 400)
detail = response.json()["error"]
self.assertTrue(detail["code"])
self.assertTrue(detail["message"])
self.assertEqual(response.headers["x-request-id"], detail["request_id"])
def test_unexpected_login_error_is_visible_and_logged(self):
with (
patch.object(self.app.state.auth, "login", side_effect=RuntimeError("login probe")),
self.assertLogs("uvicorn.error", level="ERROR") as captured,
):
response = self.client.post(
"/admin/login",
data={"login": "admin", "password": self.password},
headers={"Origin": "http://testserver"},
)
self.assertEqual(response.status_code, 500)
self.assertIn("internal_error", response.text)
self.assertIn(response.headers["x-request-id"], response.text)
self.assertIn("RuntimeError: login probe", "\n".join(captured.output))
self.assertNotIn(self.password, "\n".join(captured.output))
def test_fragment_names_and_descriptions_reach_catalog_through_api(self):
fragments = self.source()["schema"]["fragments"]
expected = {
+49
View File
@@ -0,0 +1,49 @@
"""Failures in the UI-to-API transport must remain actionable API errors."""
import unittest
import httpx
from site_engine.web.admin.api_client import AdminApi, ApiError
class ApiClientTests(unittest.IsolatedAsyncioTestCase):
async def test_invalid_error_payloads_do_not_expose_raw_response(self):
for raw in (
b"sensitive upstream response",
b"null",
b"[]",
b'{"error":{"message":"missing code"}}',
):
with self.subTest(raw=raw):
transport = httpx.MockTransport(
lambda request, raw=raw: httpx.Response(500, content=raw)
)
async with httpx.AsyncClient(
transport=transport, base_url="http://internal"
) as client:
with (
self.assertLogs("uvicorn.error", level="ERROR") as logs,
self.assertRaises(ApiError) as captured,
):
await AdminApi(client).call("POST", "/publish")
self.assertEqual(captured.exception.status, 502)
self.assertEqual(captured.exception.data["error"]["code"], "invalid_api_response")
self.assertNotIn(raw.decode(), str(captured.exception))
self.assertNotIn("sensitive upstream response", "\n".join(logs.output))
async def test_api_transport_failure_becomes_service_unavailable(self):
def unavailable(request):
raise httpx.ConnectError("connection probe", request=request)
async with httpx.AsyncClient(
transport=httpx.MockTransport(unavailable), base_url="http://internal"
) as client:
with (
self.assertLogs("uvicorn.error", level="ERROR") as logs,
self.assertRaises(ApiError) as captured,
):
await AdminApi(client).call("POST", "/publish")
self.assertEqual(captured.exception.status, 503)
self.assertEqual(captured.exception.data["error"]["code"], "api_unavailable")
self.assertIn("ConnectError", "\n".join(logs.output))