Исправить обработку некорректных параметров API

This commit is contained in:
2026-11-18 17:37:08 +03:00
parent d12159a8cc
commit 7da2caf3ca
+15 -2
View File
@@ -10,6 +10,7 @@ from datetime import datetime, timezone
import asyncpg
from fastapi import FastAPI, Header, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
@@ -64,6 +65,15 @@ async def api_error_handler(request: Request, exc: ApiError):
return _error_response(exc, getattr(request.state, "request_id", uuid.uuid4().hex))
@app.exception_handler(RequestValidationError)
async def request_validation_error_handler(request: Request, exc: RequestValidationError):
"""Keep FastAPI's query/path validation inside the public error contract."""
return _error_response(
bad_request("invalid request parameters"),
getattr(request.state, "request_id", uuid.uuid4().hex),
)
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
@@ -109,7 +119,10 @@ def decode_cursor(value: str) -> dict:
try:
padded = value + "=" * (-len(value) % 4)
raw = base64.urlsafe_b64decode(padded.encode())
return json.loads(raw)
payload = json.loads(raw)
if not isinstance(payload, dict):
raise bad_request("malformed cursor")
return payload
except (binascii.Error, ValueError, UnicodeDecodeError):
raise bad_request("malformed cursor")
@@ -208,7 +221,7 @@ async def health_ready():
@app.post("/api/v1/users", status_code=201)
async def register_user(request: Request):
body = await parse_body(request, CreateUser)
if not USERNAME_RE.match(body.username):
if not USERNAME_RE.fullmatch(body.username):
raise bad_request("username must match ^[a-z0-9_]{3,32}$")
if not body.display_name.strip():
raise bad_request("display_name must not be blank")