Майорова Софья, БВТ2301, на 5. Трек1. HTTPS/TLS/ACL,18 API tests,13 pipeline groups,3 compromise runs,clean clone,persistence. Original tests/API contract preserved; residual CVE triage in REPORT/security.
99 lines
2.8 KiB
Python
99 lines
2.8 KiB
Python
"""Shared HTTP contract; storage is supplied by each laboratory."""
|
|
import base64
|
|
import datetime as dt
|
|
import json
|
|
import re
|
|
import uuid
|
|
|
|
|
|
class APIError(Exception):
|
|
def __init__(self, status, code, message):
|
|
self.status, self.code, self.message = status, code, message
|
|
|
|
|
|
def invalid():
|
|
raise APIError(400, 'invalid_request', 'Неверные параметры запроса')
|
|
|
|
|
|
def unauthorized():
|
|
raise APIError(401, 'unauthorized', 'Требуется действительная идентификация')
|
|
|
|
|
|
def missing():
|
|
raise APIError(404, 'not_found', 'Объект не найден')
|
|
|
|
|
|
def identifier(value):
|
|
try:
|
|
if not isinstance(value, str):
|
|
invalid()
|
|
return str(uuid.UUID(value))
|
|
except ValueError:
|
|
invalid()
|
|
|
|
|
|
def text(value, maximum, minimum=1):
|
|
if not isinstance(value, str) or not minimum <= len(value) <= maximum or not value.strip():
|
|
invalid()
|
|
try:
|
|
value.encode('utf-8')
|
|
except UnicodeError:
|
|
invalid()
|
|
return value
|
|
|
|
|
|
def fields(value, required):
|
|
if not isinstance(value, dict) or set(value) != set(required):
|
|
invalid()
|
|
|
|
|
|
def username(value):
|
|
if not isinstance(value, str) or not re.fullmatch(r'[a-z0-9_]{3,32}', value):
|
|
invalid()
|
|
return value
|
|
|
|
|
|
def now():
|
|
return dt.datetime.now(dt.timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
|
|
|
|
|
def page_args(query, scope):
|
|
if set(query) - {'limit', 'cursor'} or any(len(v) != 1 for v in query.values()):
|
|
invalid()
|
|
limit = query.get('limit', ['50'])[0]
|
|
if not re.fullmatch(r'[0-9]+', limit):
|
|
invalid()
|
|
try:
|
|
limit = int(limit)
|
|
except ValueError:
|
|
invalid()
|
|
if not 1 <= limit <= 100:
|
|
invalid()
|
|
cursor = None
|
|
if 'cursor' in query:
|
|
raw = query['cursor'][0]
|
|
try:
|
|
if not raw or len(raw) > 1024:
|
|
invalid()
|
|
decoded = json.loads(base64.b64decode(raw + '=' * (-len(raw) % 4), altchars=b'-_', validate=True))
|
|
if not isinstance(decoded, list) or len(decoded) != 3 or decoded[0] != scope:
|
|
invalid()
|
|
stamp = decoded[1]
|
|
if not isinstance(stamp, str) or not stamp.endswith('Z'):
|
|
invalid()
|
|
stamp = dt.datetime.fromisoformat(stamp[:-1] + '+00:00').isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
|
cursor = (stamp, identifier(decoded[2]))
|
|
except (ValueError, TypeError, UnicodeError):
|
|
invalid()
|
|
return limit, cursor
|
|
|
|
|
|
def page(items, limit, scope):
|
|
more = len(items) > limit
|
|
items = items[:limit]
|
|
cursor = None
|
|
if more:
|
|
last = items[-1]
|
|
cursor = base64.urlsafe_b64encode(json.dumps([scope, last['created_at'], last['id']]).encode()).decode().rstrip('=')
|
|
return {'items': items, 'next_cursor': cursor}
|