Files
mtusi2026lab5/src/messenger/validation.py
T

143 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Strict request payload validation; any deviation is 400 invalid_request."""
from __future__ import annotations
import re
import uuid
from .errors import InvalidRequest
USERNAME_PATTERN = re.compile(r'[a-z0-9_]{3,32}')
DIGITS_PATTERN = re.compile(r'[0-9]+')
def safe_label(value):
"""Render untrusted text for an error message without breaking its encoding.
Field names come straight from the client JSON, so they may contain the same
lone surrogates that the payload itself is rejected for.
"""
text = value if isinstance(value, str) else repr(value)
return text.encode('utf-8', 'replace').decode('utf-8')
def require_encodable(value, name):
"""Reject text that cannot survive a UTF-8 round trip.
`json.loads` happily produces lone surrogates from `\ud800` escapes. Such a
string cannot be UTF-8 encoded, so it must be rejected before it is stored;
otherwise the write is committed and the response encoding fails afterwards.
"""
try:
value.encode('utf-8')
except UnicodeEncodeError:
raise InvalidRequest(
'Поле %s содержит недопустимые символы Unicode' % name) from None
return value
def require_object(payload):
if not isinstance(payload, dict):
raise InvalidRequest('Тело запроса должно быть JSON-объектом')
return payload
def require_fields(payload, required, allowed):
"""Reject missing required fields and any unknown field."""
missing = [name for name in required if name not in payload]
if missing:
raise InvalidRequest('Отсутствуют обязательные поля: ' + ', '.join(sorted(missing)))
extra = [name for name in payload if name not in allowed]
if extra:
raise InvalidRequest('Неизвестные поля: ' + ', '.join(sorted(safe_label(n) for n in extra)))
return payload
def require_text_field(payload, name, minimum, maximum, strip_check=True):
value = payload.get(name)
if not isinstance(value, str):
raise InvalidRequest('Поле %s должно быть строкой' % name)
require_encodable(value, name)
if strip_check and not value.strip():
raise InvalidRequest('Поле %s не может быть пустым или состоять из пробелов' % name)
if len(value) < minimum:
raise InvalidRequest('Поле %s короче %d символов' % (name, minimum))
if len(value) > maximum:
raise InvalidRequest('Поле %s длиннее %d символов' % (name, maximum))
return value
def require_username(payload):
username = payload.get('username')
# fullmatch, not match: a trailing "$" would also accept a final newline.
if not isinstance(username, str) or USERNAME_PATTERN.fullmatch(username) is None:
raise InvalidRequest('username должен соответствовать ^[a-z0-9_]{3,32}$')
return require_encodable(username, 'username')
def require_uuid_string(value, name):
if not isinstance(value, str):
raise InvalidRequest('Поле %s должно быть строкой UUID' % name)
try:
return str(uuid.UUID(value))
except ValueError:
raise InvalidRequest('Поле %s не является корректным UUID' % name) from None
def require_attachment_ids(payload):
value = payload.get('attachment_ids', [])
if not isinstance(value, list) or len(value) > 10:
raise InvalidRequest('attachment_ids должен содержать от 0 до 10 UUID')
identifiers = [require_uuid_string(item, 'attachment_ids') for item in value]
if len(set(identifiers)) != len(identifiers):
raise InvalidRequest('attachment_ids содержит повторяющиеся UUID')
return identifiers
def require_member_ids(payload, maximum, minimum=1):
value = payload.get('member_ids')
if not isinstance(value, list):
raise InvalidRequest('member_ids должен быть массивом UUID')
if not minimum <= len(value) <= maximum:
raise InvalidRequest('member_ids должен содержать от %d до %d участников' % (minimum, maximum))
identifiers = [require_uuid_string(item, 'member_ids') for item in value]
if len(set(identifiers)) != len(identifiers):
raise InvalidRequest('member_ids содержит повторяющихся участников')
return identifiers
def parse_limit(raw, default, maximum):
"""Parse a limit query value strictly: absent means default, anything else must be a plain integer.
An empty value is a client error rather than an absent parameter, and the
digit run is length-bounded before int() because Python refuses to convert
strings longer than its integer-string limit, which would surface as a 500.
"""
if raw is None:
return default
if not DIGITS_PATTERN.fullmatch(raw):
raise InvalidRequest('limit должен быть целым числом от 1 до %d' % maximum)
# int() refuses absurdly long digit strings (ValueError -> 500). Comparing the
# significant digits against the maximum first rejects them without converting.
significant = raw.lstrip('0') or '0'
if len(significant) > len(str(maximum)):
raise InvalidRequest('limit должен быть в диапазоне 1..%d' % maximum)
value = int(significant)
if not 1 <= value <= maximum:
raise InvalidRequest('limit должен быть в диапазоне 1..%d' % maximum)
return value
def parse_cursor(raw):
if raw is None:
return None
if not isinstance(raw, str) or not raw:
raise InvalidRequest('cursor должен быть непустой строкой')
return raw
def require_idempotency_key(value):
"""Only the contract's bounded ASCII token is accepted."""
if not isinstance(value, str) or re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', value) is None:
raise InvalidRequest('Требуется корректный Idempotency-Key (1–128 ASCII символов)')
return value