forked from mtusi2026/mtusi2026lab3
164 lines
9.7 KiB
Python
164 lines
9.7 KiB
Python
"""Проверки замечаний преподавателя: HTTP, повреждённый Redis и точный курсор."""
|
||
import base64
|
||
import json
|
||
import subprocess
|
||
import uuid
|
||
from pathlib import Path
|
||
from urllib.parse import quote
|
||
|
||
from client import Client, arguments, check, run
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
|
||
|
||
def database(code):
|
||
container = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], cwd=ROOT, text=True).split()[0]
|
||
result = subprocess.run(['docker', 'exec', '-i', container, 'python'],
|
||
input=code, cwd=ROOT, text=True, capture_output=True, timeout=30)
|
||
check(result.returncode == 0, 'Ошибка подготовки/удаления ORM-фикстуры')
|
||
return json.loads(result.stdout) if result.stdout.strip() else None
|
||
|
||
|
||
def main():
|
||
args = arguments('Регрессии по замечаниям преподавателя')
|
||
c = Client(args.base_url, args.ca_file)
|
||
alice, bob, eve, chat = c.bootstrap()
|
||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||
registration = {**alice['registration'], 'username': 'blank_' + uuid.uuid4().hex[:16]}
|
||
for field, value in [('password', ' ' * 12), ('password', '\t\n' * 6),
|
||
('display_name', ' \t\n')]:
|
||
c.call('POST', '/api/v1/users', 400, body={**registration, field: value})
|
||
for body in ({'title': ' \t\n', 'member_ids': [alice['id']]},
|
||
{'title': 'Duplicate', 'member_ids': [alice['id'], alice['id']]},
|
||
{'title': 'Unknown', 'member_ids': [alice['id'], str(uuid.uuid4())]},
|
||
{'title': 'Missing actor', 'member_ids': [bob['id']]}):
|
||
c.call('POST', '/api/v1/chats', 400, actor=alice, body=body)
|
||
basic = {'Authorization': 'Basic ' + base64.b64encode((
|
||
alice['registration']['username'] + ':' + alice['registration']['password']
|
||
).encode()).decode()}
|
||
for raw in (b'{"extra":"forbidden"}', b'{}', b'null', b' ', b'{'):
|
||
c.call('POST', '/api/v1/auth/sessions', 400, headers=basic, raw=raw)
|
||
c.call('POST', '/api/v1/auth/sessions', 401)
|
||
for credential in ('Basic !!!', 'Basic /w==', 'Bearer something',
|
||
'Basic ' + base64.b64encode(b'no-colon').decode()):
|
||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': credential})
|
||
for payload in ('null', '[]', '{}', '123', '{broken'):
|
||
cursor = base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=')
|
||
c.call('GET', path + '?cursor=' + quote(cursor, safe=''), 400, actor=alice)
|
||
for endpoint, body, actor in (
|
||
('/api/v1/users', registration, None),
|
||
('/api/v1/chats', {'title': 'MIME', 'member_ids': [alice['id']]}, alice),
|
||
(path, {'text': 'valid'}, alice),
|
||
):
|
||
response = c.call('POST', endpoint, 415, actor=actor, body=body,
|
||
headers={'Content-Type': 'text/plain'})
|
||
check(response['json']['error']['code'] == 'unsupported_media_type', 'Неверный код MIME-ошибки')
|
||
for raw in (b'{"text":"valid"}}', b'{"text":"valid"}]', b'{"text":"valid"}{}'):
|
||
c.call('POST', path, 400, actor=alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||
for body in ({'text': ' ' * 12}, {'text': ' ' + 'a' * 4000}, {'text': 123},
|
||
{'text': 'valid', 'sender_id': eve['id']}):
|
||
c.call('POST', path, 400, actor=alice, body=body)
|
||
check(c.call('GET', path, actor=alice, schema='MessagePage')['json']['items'] == [],
|
||
'Отклонённый запрос сохранил сообщение')
|
||
print('PASS: обязательные пробельные строки, malformed JSON, типы/лишние поля, MIME 415, Basic без тела')
|
||
|
||
# Создаём только синтетические строки через SQLAlchemy; пароли/токены в команды не передаются.
|
||
fixture = database(f'''
|
||
import asyncio, json
|
||
from datetime import datetime, timezone
|
||
from uuid import UUID, uuid4
|
||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||
from src.core.db.session import create_engine
|
||
from src.core.db.models import User, Message
|
||
async def main():
|
||
engine = create_engine()
|
||
ids = [uuid4() for _ in range(100)]
|
||
base = uuid4().int & ~65535
|
||
message_ids = [UUID(int=base+4), UUID(int=base+3), UUID(int=base+2), UUID(int=base+1)]
|
||
times = [100000, 200000, 200000, 200000]
|
||
async with async_sessionmaker(engine).begin() as session:
|
||
session.add_all([User(id=i, username='fixture_' + i.hex[:20], display_name='Fixture',
|
||
password_hash='not-for-login', created_at=datetime.now(timezone.utc)) for i in ids])
|
||
session.add_all([Message(id=i, chat_id=UUID('{chat['id']}'), sender_id=UUID('{alice['id']}'),
|
||
text='precision', created_at=datetime(2026, 1, 1, 0, 0, 0, us, timezone.utc))
|
||
for i, us in zip(message_ids, times)])
|
||
await engine.dispose()
|
||
print(json.dumps({{'users': [str(i) for i in ids], 'messages': [str(i) for i in message_ids]}}))
|
||
asyncio.run(main())
|
||
''')
|
||
try:
|
||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||
body={'title': '101 участников', 'member_ids': [alice['id'], *fixture['users']]})
|
||
hundred = c.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
|
||
body={'title': '100 участников',
|
||
'member_ids': [alice['id'], *fixture['users'][:99]]})['json']
|
||
check(len(hundred['member_ids']) == 100, 'Допустимые 100 участников не сохранены')
|
||
received = []
|
||
cursor = None
|
||
while True:
|
||
url = path + '?limit=1' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
|
||
page = c.call('GET', url, actor=bob, schema='MessagePage')['json']
|
||
received.extend(item['id'] for item in page['items'])
|
||
if cursor is None:
|
||
first_cursor = page['next_cursor']
|
||
cursor = page['next_cursor']
|
||
if cursor is None:
|
||
break
|
||
check(len(received) <= 4, 'Курсор зациклился')
|
||
expected = [fixture['messages'][0], *reversed(fixture['messages'][1:])]
|
||
check(received == expected, 'Потеря/повтор сообщений при микросекундах или равном времени')
|
||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||
body={'title': 'Other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(first_cursor, safe=''),
|
||
400, actor=alice)
|
||
print('PASS: 101 существующий участник отклонён; курсор сохраняет микросекунды и UUID-порядок, привязан к чату')
|
||
finally:
|
||
database(f'''
|
||
import asyncio
|
||
from uuid import UUID
|
||
from sqlalchemy import delete, select
|
||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||
from src.core.db.session import create_engine
|
||
from src.core.db.models import User, Chat, ChatMember, Message
|
||
async def main():
|
||
engine = create_engine()
|
||
ids = [UUID(i) for i in {fixture['users']!r}]
|
||
async with async_sessionmaker(engine).begin() as session:
|
||
chats = list(await session.scalars(select(ChatMember.chat_id).where(ChatMember.user_id.in_(ids))))
|
||
await session.execute(delete(Message).where(Message.chat_id.in_(chats)))
|
||
await session.execute(delete(Chat).where(Chat.id.in_(chats)))
|
||
await session.execute(delete(User).where(User.id.in_(ids)))
|
||
await engine.dispose()
|
||
asyncio.run(main())
|
||
''')
|
||
text = ' строка\nс пробелами '
|
||
saved = c.message(alice, chat, text)['json']
|
||
check(saved['text'] == text, 'Текст обрезан до сохранения')
|
||
history = c.call('GET', path, actor=alice, schema='MessagePage')['json']
|
||
check(next(m for m in history['items'] if m['id'] == saved['id'])['text'] == text,
|
||
'Сохранённый текст изменён')
|
||
print('PASS: исходный текст и его длина сохраняются без strip')
|
||
|
||
key = 'user:v1:' + alice['id']
|
||
def redis(*args):
|
||
return subprocess.check_output(['docker', 'compose', 'exec', '-T', 'redis',
|
||
'redis-cli', '--raw', *args], cwd=ROOT, text=True, timeout=10).strip()
|
||
for corrupted in ('null', '[]', '{}', '{broken', '"text"', '{"id":123}',
|
||
json.dumps({**alice['user'], 'id': bob['id']})):
|
||
redis('SET', key, corrupted)
|
||
me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
|
||
check(me == alice['user'], 'Повреждённый профиль отвергает сессию или меняет пользователя')
|
||
check(json.loads(redis('GET', key))['id'] == alice['id'], 'Повреждённый кэш не заменён')
|
||
check(0 < int(redis('TTL', key)) <= 60, 'Восстановленному профилю не назначен TTL')
|
||
print('PASS: null/повреждённый/чужой профиль заменяется из PostgreSQL с TTL; сессия работает')
|
||
|
||
spec = json.loads(c.call('GET', '/openapi.json')['bytes'])
|
||
login = spec['paths']['/api/v1/auth/sessions']['post']
|
||
check('requestBody' not in login and {'basicAuth': []} in login['security'], 'Swagger вход не Basic')
|
||
check({'bearerAuth': []} in spec['paths']['/api/v1/users/me']['get']['security'], 'Swagger не передаёт Bearer')
|
||
print('PASS: Swagger объявляет Basic для входа и Bearer для защищённых методов')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
run(main)
|