forked from mtusi2026/mtusi2026lab2
126 lines
5.2 KiB
Python
126 lines
5.2 KiB
Python
"""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_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
|