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.
86 lines
3.0 KiB
Python
86 lines
3.0 KiB
Python
"""Request-scoped in-process API credentials never reach browser HTML."""
|
|
|
|
import secrets
|
|
from contextlib import asynccontextmanager
|
|
|
|
import httpx
|
|
|
|
from ..error_handling import error_headers, log, request_id
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status: int, data: dict):
|
|
self.status = status
|
|
detail = {"code": "api_error", "message": "Ошибка API", "request_id": request_id()}
|
|
detail.update(data.get("error", {}))
|
|
self.data = {**data, "error": detail}
|
|
super().__init__(detail["message"])
|
|
|
|
def annotate(self, result):
|
|
result.headers.update(error_headers(self.data["error"]))
|
|
result.headers["X-Admin-Error"] = "1"
|
|
return result
|
|
|
|
|
|
class AdminApi:
|
|
def __init__(self, client):
|
|
self.client = client
|
|
|
|
async def call(self, method, path, data=None):
|
|
try:
|
|
response = await self.client.request(method, "/admin/api/v1" + path, json=data)
|
|
except httpx.RequestError:
|
|
log.exception(
|
|
"api_unavailable request_id=%s method=%s path=%s", request_id(), method, path
|
|
)
|
|
raise ApiError(
|
|
503,
|
|
{
|
|
"error": {
|
|
"code": "api_unavailable",
|
|
"message": "API недоступен. Проверьте текущую версию перед повтором.",
|
|
}
|
|
},
|
|
) from None
|
|
try:
|
|
payload = response.json()
|
|
if response.status_code >= 400:
|
|
detail = payload["error"]
|
|
if not isinstance(detail["code"], str) or not isinstance(detail["message"], str):
|
|
raise ValueError("Invalid API error contract")
|
|
except (ValueError, KeyError, TypeError):
|
|
log.exception(
|
|
"invalid_api_response request_id=%s method=%s path=%s status=%s",
|
|
request_id(),
|
|
method,
|
|
path,
|
|
response.status_code,
|
|
)
|
|
raise ApiError(
|
|
502,
|
|
{
|
|
"error": {
|
|
"code": "invalid_api_response",
|
|
"message": "API вернул некорректный ответ. Проверьте текущую версию перед повтором.",
|
|
}
|
|
},
|
|
) from None
|
|
if response.status_code >= 400:
|
|
raise ApiError(response.status_code, payload)
|
|
return payload
|
|
|
|
|
|
@asynccontextmanager
|
|
async def api_for(request, cookie, ip):
|
|
token = secrets.token_urlsafe(32)
|
|
request.app.state.api_credentials[token] = (cookie, ip)
|
|
try:
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.ASGITransport(app=request.app),
|
|
base_url="http://internal",
|
|
headers={"Authorization": "Bearer " + token},
|
|
) as client:
|
|
yield AdminApi(client)
|
|
finally:
|
|
request.app.state.api_credentials.pop(token, None)
|