forked from mtusi2026/mtusi2026lab3
HAProxy перед двумя репликами API, X-Instance-Id, общая идемпотентность отправки сообщения в PostgreSQL, двухшаговая остановка реплики по SIGTERM, лимиты CPU/RAM, хуки stop-one и restart. Проверки отказов, эксперимент и поочерёдное обновление в scripts/lab3_checks.py, отчёт в REPORT.md, результаты в evidence/, команды для показа в DEMO.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
220 lines
11 KiB
Python
220 lines
11 KiB
Python
"""Валидация входных данных: неверный JSON, пустое сообщение, дубликат username, пароль, Unicode."""
|
||
import json
|
||
import unittest
|
||
import uuid
|
||
|
||
import api
|
||
|
||
USERS = '/api/v1/users'
|
||
PASSWORD = 'Valid-password-123'
|
||
|
||
|
||
def registration(**fields):
|
||
"""Корректное тело регистрации; fields заменяют или добавляют поля."""
|
||
body = {'username': api.unique_username(), 'display_name': 'Имя', 'password': PASSWORD}
|
||
body.update(fields)
|
||
return body
|
||
|
||
|
||
class InvalidJsonTest(unittest.TestCase):
|
||
def assert_invalid(self, response):
|
||
self.assertEqual(response.status, 400)
|
||
self.assertEqual(response.json['error']['code'], 'invalid_request')
|
||
|
||
def test_malformed_json_on_register(self):
|
||
self.assert_invalid(api.request('POST', USERS, raw=b'{"username": "broken", '))
|
||
|
||
def test_malformed_json_on_message(self):
|
||
user = api.new_user()
|
||
chat = api.new_chat(user, [user])
|
||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||
for raw in (b'not json', b'{"text": "no closing quote}', b'', b'{"text": }'):
|
||
with self.subTest(raw=raw):
|
||
self.assert_invalid(api.request('POST', path, user=user, raw=raw))
|
||
# Неудачные запросы ничего не записали в историю.
|
||
self.assertEqual(api.pages(path, user, 100), [[]])
|
||
|
||
def test_json_that_is_not_an_object(self):
|
||
for raw in (b'[]', b'"text"', b'42', b'null'):
|
||
with self.subTest(raw=raw):
|
||
self.assert_invalid(api.request('POST', USERS, raw=raw))
|
||
|
||
def test_invalid_utf8(self):
|
||
raw = json.dumps(registration(display_name='PLACEHOLDER')).encode().replace(b'PLACEHOLDER', b'\xff\xfe')
|
||
self.assert_invalid(api.request('POST', USERS, raw=raw))
|
||
|
||
def test_lone_surrogate_is_rejected_not_crashed(self):
|
||
# Всё остальное в теле корректно: ошибка именно в одиночном суррогате.
|
||
raw = json.dumps(registration(display_name='PLACEHOLDER')).encode().replace(b'PLACEHOLDER', b'\\ud800')
|
||
self.assert_invalid(api.request('POST', USERS, raw=raw))
|
||
|
||
def test_nul_character_is_rejected_not_crashed(self):
|
||
# PostgreSQL не хранит символ NUL в text: без проверки это был бы 500.
|
||
self.assert_invalid(api.request('POST', USERS, body=registration(display_name='a\x00b')))
|
||
|
||
def test_extra_fields(self):
|
||
self.assert_invalid(api.request('POST', USERS, body=registration(is_admin=True)))
|
||
|
||
def test_wrong_types(self):
|
||
for fields in ({'username': 12345}, {'display_name': ['Имя']}, {'display_name': None}, {'password': 123456789012345}):
|
||
with self.subTest(fields=fields):
|
||
self.assert_invalid(api.request('POST', USERS, body=registration(**fields)))
|
||
|
||
def test_wrong_content_type(self):
|
||
raw = json.dumps(registration()).encode()
|
||
self.assert_invalid(api.request('POST', USERS, raw=raw, headers={'Content-Type': 'text/plain'}))
|
||
|
||
|
||
class UserValidationTest(unittest.TestCase):
|
||
def test_duplicate_username_is_409(self):
|
||
body = registration(display_name='Первый')
|
||
first = api.request('POST', USERS, body=body)
|
||
self.assertEqual(first.status, 201)
|
||
# Совпадает только username: другие имя и пароль не помогают.
|
||
second = api.request('POST', USERS, body=dict(body, display_name='Второй', password='Another-password-456'))
|
||
self.assertEqual(second.status, 409)
|
||
self.assertEqual(second.json['error']['code'], 'conflict')
|
||
# Первый пользователь не изменился: входит со своим паролем и видит своё имя.
|
||
session = api.login(body['username'], body['password'])
|
||
self.assertEqual(session.json['user'], first.json)
|
||
self.assertEqual(api.login(body['username'], 'Another-password-456').status, 401)
|
||
|
||
def test_bad_usernames(self):
|
||
for username in ('ab', 'a' * 33, 'Alice', 'with space', 'дмитрий', 'dash-name', '', 'name\n', 'colon:name'):
|
||
with self.subTest(username=username):
|
||
self.assertEqual(api.request('POST', USERS, body=registration(username=username)).status, 400)
|
||
|
||
def test_username_length_limits_are_accepted(self):
|
||
for length in (3, 32):
|
||
with self.subTest(length=length):
|
||
response = api.request('POST', USERS, body=registration(username=uuid.uuid4().hex[:length]))
|
||
# Трёхсимвольное имя могло остаться от прошлого запуска: 409 тоже значит «имя допустимо».
|
||
self.assertIn(response.status, (201, 409))
|
||
|
||
def test_bad_display_names(self):
|
||
for display_name in ('', ' ', '\t\n', 'я' * 101):
|
||
with self.subTest(display_name=display_name):
|
||
self.assertEqual(api.request('POST', USERS, body=registration(display_name=display_name)).status, 400)
|
||
|
||
def test_bad_passwords(self):
|
||
for password in ('a' * 11, 'я' * 11, 'a' * 129, ' ' * 12, '\t' * 20, 'pass\x00word-123'):
|
||
with self.subTest(password=password[:20]):
|
||
self.assertEqual(api.request('POST', USERS, body=registration(password=password)).status, 400)
|
||
|
||
def test_password_length_limits_are_accepted(self):
|
||
# Длина считается в code points: 12 кириллических букв — это 24 байта UTF-8.
|
||
for password in ('a' * 12, 'я' * 12, '👋' * 128):
|
||
with self.subTest(length=len(password)):
|
||
body = registration(password=password)
|
||
self.assertEqual(api.request('POST', USERS, body=body).status, 201)
|
||
self.assertEqual(api.login(body['username'], password).status, 201)
|
||
|
||
def test_missing_fields(self):
|
||
for field in ('username', 'display_name', 'password'):
|
||
with self.subTest(field=field):
|
||
body = registration()
|
||
del body[field]
|
||
self.assertEqual(api.request('POST', USERS, body=body).status, 400)
|
||
|
||
def test_unicode_display_name_is_kept(self):
|
||
# Длина считается в code points: 100 эмодзи — это 400 байт, но имя допустимо.
|
||
for display_name in ('Дмитрий 👋', '李雷', '👋' * 100):
|
||
with self.subTest(display_name=display_name):
|
||
response = api.request('POST', USERS, body=registration(display_name=display_name))
|
||
self.assertEqual(response.status, 201)
|
||
self.assertEqual(response.json['display_name'], display_name)
|
||
|
||
|
||
class MessageValidationTest(unittest.TestCase):
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
cls.user = api.new_user()
|
||
cls.chat = api.new_chat(cls.user, [cls.user])
|
||
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
|
||
|
||
def test_empty_message_is_400(self):
|
||
for text in ('', ' ', '\n\t \r\n', ' '):
|
||
with self.subTest(text=text):
|
||
response = api.send(self.user, self.chat, text)
|
||
self.assertEqual(response.status, 400)
|
||
self.assertEqual(response.json['error']['code'], 'invalid_request')
|
||
|
||
def test_missing_or_wrong_text(self):
|
||
for body in ({}, {'text': None}, {'text': 123}, {'text': ['a']}, {'message': 'a'}):
|
||
with self.subTest(body=body):
|
||
self.assertEqual(api.request('POST', self.path, user=self.user, body=body).status, 400)
|
||
|
||
def test_sender_id_in_body_is_rejected(self):
|
||
other = api.new_user()
|
||
body = {'text': 'подмена отправителя', 'sender_id': other['id']}
|
||
self.assertEqual(api.request('POST', self.path, user=self.user, body=body).status, 400)
|
||
|
||
def test_nul_in_text_is_400(self):
|
||
self.assertEqual(api.send(self.user, self.chat, 'до\x00после').status, 400)
|
||
|
||
def test_text_length_limit(self):
|
||
self.assertEqual(api.send(self.user, self.chat, 'я' * 4000).status, 201)
|
||
self.assertEqual(api.send(self.user, self.chat, '👋' * 4000).status, 201)
|
||
self.assertEqual(api.send(self.user, self.chat, 'я' * 4001).status, 400)
|
||
|
||
def test_unicode_text_is_kept(self):
|
||
text = 'Привет, мир 👋 — 你好\nвторая строка'
|
||
response = api.send(self.user, self.chat, text)
|
||
self.assertEqual(response.status, 201)
|
||
self.assertEqual(response.json['text'], text)
|
||
self.assertEqual(response.json['sender_id'], self.user['id'])
|
||
self.assertEqual(response.json['chat_id'], self.chat['id'])
|
||
|
||
def test_oversized_body_is_413(self):
|
||
response = api.request('POST', self.path, user=self.user, body={'text': 'a' * 70000})
|
||
self.assertEqual(response.status, 413)
|
||
self.assertEqual(response.json['error']['code'], 'payload_too_large')
|
||
|
||
|
||
class ChatValidationTest(unittest.TestCase):
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
cls.alice = api.new_user()
|
||
cls.bob = api.new_user()
|
||
|
||
def create(self, title, member_ids):
|
||
return api.request('POST', '/api/v1/chats', user=self.alice, body={'title': title, 'member_ids': member_ids})
|
||
|
||
def test_caller_must_be_a_member(self):
|
||
self.assertEqual(self.create('Без меня', [self.bob['id']]).status, 400)
|
||
|
||
def test_duplicate_members(self):
|
||
self.assertEqual(self.create('Дубликат', [self.alice['id'], self.bob['id'], self.bob['id']]).status, 400)
|
||
# Тот же UUID в другом регистре — тоже дубликат.
|
||
self.assertEqual(self.create('Дубликат', [self.alice['id'], self.alice['id'].upper()]).status, 400)
|
||
|
||
def test_unknown_member_rolls_back_the_whole_chat(self):
|
||
# Чат вставляется первым, участник — вторым; ошибка на участнике откатывает и сам чат.
|
||
title = 'Откат ' + uuid.uuid4().hex[:8]
|
||
response = self.create(title, [self.alice['id'], str(uuid.uuid4())])
|
||
self.assertEqual(response.status, 400)
|
||
chats = [chat for page in api.pages('/api/v1/chats', self.alice, 100) for chat in page]
|
||
self.assertNotIn(title, [chat['title'] for chat in chats])
|
||
|
||
def test_bad_member_ids(self):
|
||
for member_ids in ([], 'not a list', [123], ['not-a-uuid'], None):
|
||
with self.subTest(member_ids=member_ids):
|
||
self.assertEqual(self.create('Чат', member_ids).status, 400)
|
||
|
||
def test_bad_titles(self):
|
||
for title in ('', ' ', 'я' * 101, 5, 'a\x00b'):
|
||
with self.subTest(title=title):
|
||
self.assertEqual(self.create(title, [self.alice['id']]).status, 400)
|
||
|
||
def test_valid_chat_keeps_member_order(self):
|
||
response = self.create('Проект по ВНП', [self.bob['id'], self.alice['id']])
|
||
self.assertEqual(response.status, 201)
|
||
self.assertEqual(response.json['title'], 'Проект по ВНП')
|
||
self.assertEqual(response.json['member_ids'], [self.bob['id'], self.alice['id']])
|
||
again = api.request('GET', '/api/v1/chats/' + response.json['id'], user=self.bob)
|
||
self.assertEqual(again.json, response.json)
|
||
|
||
|
||
if __name__ == '__main__':
|
||
unittest.main()
|