fix: reject tampered cursors and non-canonical UUIDs
decode_cursor checked only for KeyError, TypeError and ValueError, so a
server-issued cursor whose item id was replaced with [], {}, 123 or
false crashed UUID() with AttributeError and answered 500. It now checks
the types of "t" and "i" before parsing and accepts only the exact
string the server would issue for the parsed key: re-encoding must give
the received cursor, so v=true, an extra field or the id in another
notation is a 400 instead of a page.
pydantic's UUID also accepts ids without hyphens, with the urn:uuid:
prefix and in braces, wider than the contract's format: uuid. chat_id in
the path of the three chat endpoints and member_ids elements now use
UuidIn, which requires the 8-4-4-4-12 form in any case. Response models
and the OpenAPI schema are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.api.dependencies import ChatServiceDep, CurrentUser, PageQueryDep
|
||||
from src.api.schemas import Chat, ChatPage, CreateChat
|
||||
from src.api.schemas import Chat, ChatPage, CreateChat, UuidIn
|
||||
|
||||
router = APIRouter(prefix="/chats", tags=["chats"])
|
||||
|
||||
@@ -39,7 +37,7 @@ async def list_chats(
|
||||
@router.get("/{chat_id}", response_model=Chat)
|
||||
async def get_chat(
|
||||
user: CurrentUser,
|
||||
chat_id: UUID,
|
||||
chat_id: UuidIn,
|
||||
chats: ChatServiceDep,
|
||||
) -> Chat:
|
||||
chat = await chats.get_chat_for_member(chat_id=chat_id, user_id=user.id)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Header
|
||||
|
||||
from src.api.dependencies import CurrentUser, MessageServiceDep, PageQueryDep
|
||||
from src.api.schemas import CreateMessage, Message, MessagePage
|
||||
from src.api.schemas import CreateMessage, Message, MessagePage, UuidIn
|
||||
from src.utils.constants import (
|
||||
IDEMPOTENCY_KEY_HEADER,
|
||||
IDEMPOTENCY_KEY_MAX_LENGTH,
|
||||
@@ -31,7 +30,7 @@ IdempotencyKeyHeader = Annotated[
|
||||
@router.post("", status_code=201, response_model=Message)
|
||||
async def send_message(
|
||||
user: CurrentUser,
|
||||
chat_id: UUID,
|
||||
chat_id: UuidIn,
|
||||
body: CreateMessage,
|
||||
idempotency_key: IdempotencyKeyHeader,
|
||||
messages: MessageServiceDep,
|
||||
@@ -49,7 +48,7 @@ async def send_message(
|
||||
@router.get("", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
user: CurrentUser,
|
||||
chat_id: UUID,
|
||||
chat_id: UuidIn,
|
||||
page: PageQueryDep,
|
||||
messages: MessageServiceDep,
|
||||
) -> MessagePage:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from .chat import Chat, ChatPage, CreateChat
|
||||
from .common import Error, ErrorBody, ErrorCode, Health
|
||||
from .common import Error, ErrorBody, ErrorCode, Health, UuidIn
|
||||
from .message import CreateMessage, Message, MessagePage
|
||||
from .session import Session
|
||||
from .user import CreateUser, User
|
||||
@@ -18,4 +18,5 @@ __all__ = [
|
||||
"MessagePage",
|
||||
"Session",
|
||||
"User",
|
||||
"UuidIn",
|
||||
]
|
||||
|
||||
@@ -2,7 +2,7 @@ from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from src.api.schemas.common import NonBlankStr, UtcDatetime
|
||||
from src.api.schemas.common import NonBlankStr, UtcDatetime, UuidIn
|
||||
from src.utils.constants import (
|
||||
CHAT_MEMBERS_MAX,
|
||||
CHAT_MEMBERS_MIN,
|
||||
@@ -20,7 +20,7 @@ class CreateChat(BaseModel):
|
||||
)
|
||||
# только форма; повторы, существование и вызывающего в списке
|
||||
# проверяет ChatService.create_chat
|
||||
member_ids: list[UUID] = Field(
|
||||
member_ids: list[UuidIn] = Field(
|
||||
min_length=CHAT_MEMBERS_MIN,
|
||||
max_length=CHAT_MEMBERS_MAX,
|
||||
)
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
"""Общие типы HTTP-моделей: строки, время, ошибки, health."""
|
||||
"""Общие типы HTTP-моделей: строки, UUID входа, время, ошибки, health."""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, PlainSerializer, StrictStr
|
||||
from pydantic import (
|
||||
AfterValidator,
|
||||
BaseModel,
|
||||
BeforeValidator,
|
||||
PlainSerializer,
|
||||
StrictStr,
|
||||
)
|
||||
|
||||
from src.utils.constants import UUID_PATTERN
|
||||
from src.utils.utc import to_rfc3339
|
||||
|
||||
|
||||
@@ -16,9 +25,25 @@ def _reject_blank(value: str) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _require_uuid_form(value: object) -> object:
|
||||
"""Строка UUID — только в записи 8-4-4-4-12; не-строку разбирает `UUID`.
|
||||
|
||||
pydantic принимает и запись без дефисов, с `urn:uuid:` и в `{…}`, а
|
||||
контракт — только `format: uuid`. Тип не-строки (массив, число, bool)
|
||||
отвергает сам валидатор `UUID`.
|
||||
"""
|
||||
if isinstance(value, str) and not re.fullmatch(UUID_PATTERN, value):
|
||||
raise ValueError("must be a UUID in 8-4-4-4-12 form")
|
||||
return value
|
||||
|
||||
|
||||
# строгая строка: число не превращается в строку; пробелы не принимаются
|
||||
NonBlankStr = Annotated[StrictStr, AfterValidator(_reject_blank)]
|
||||
|
||||
# UUID, который передаёт клиент (путь и тело): запись контракта, цифры в
|
||||
# любом регистре. Модели ответов — обычный `UUID`
|
||||
UuidIn = Annotated[UUID, BeforeValidator(_require_uuid_form)]
|
||||
|
||||
# время в ответе: RFC 3339 UTC, всегда шесть знаков микросекунд и Z
|
||||
UtcDatetime = Annotated[
|
||||
datetime,
|
||||
|
||||
Reference in New Issue
Block a user