#!/usr/bin/env python3 """Own black-box tests for lab2. They complement, and never weaken, tests/smoke.py. The suite assumes a running stack (make up) and creates only synthetic data. It checks the contract expectations derived from contracts/openapi.json and contracts/README.md: exact JSON keys, strict input validation, Bearer-only business API, membership hiding as 404, keyset pagination, concurrent username registration and concurrent message writes. Python 3.9+, standard library only. """ import base64 import concurrent.futures import datetime as dt import json import sys import threading import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, arguments, check, timestamp # noqa: E402 CHECKS = 0 def ok(condition, message): global CHECKS CHECKS += 1 check(condition, message) def expect_keys(payload, expected, where): ok(set(payload) == set(expected), where + ': JSON keys differ: ' + repr(sorted(payload))) def basic(username, password): return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii') def register(c, username=None, display_name=None, password=None): username = username or 'bb_' + uuid.uuid4().hex[:12] password = password or 'B3st-' + uuid.uuid4().hex display_name = display_name or 'Тестовый пользователь' body = {'username': username, 'display_name': display_name, 'password': password} user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json'] expect_keys(user, {'id', 'username', 'display_name', 'created_at'}, 'User') return {'id': user['id'], 'user': user, 'registration': body, 'password': password} def login(c, actor): response = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(actor['registration']['username'], actor['password'])}, schema='Session')['json'] expect_keys(response, {'token', 'token_type', 'expires_at', 'user'}, 'Session') actor['token'] = response['token'] actor['session'] = response return actor def new_chat(c, actor, title, member_ids): return c.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': title, 'member_ids': member_ids}, schema='Chat')['json'] def send(c, actor, chat, text, headers=None): return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor, body={'text': text}, headers=headers, schema='Message')['json'] def all_messages(c, actor, chat, limit=100): path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) items, seen = [], set() for _ in range(1000): page = c.call('GET', path, actor=actor, schema='MessagePage')['json'] items.extend(page['items']) if page['next_cursor'] is None: return items ok(page['next_cursor'] not in seen, 'message cursor cycle') seen.add(page['next_cursor']) from urllib.parse import quote path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) + '&cursor=' + quote(page['next_cursor'], safe='')) raise AssertionError('message pagination exceeded safety bound') def sorted_messages(items): return sorted(items, key=lambda x: (timestamp(x['created_at']), uuid.UUID(x['id']).int)) def test_health(c): live = c.call('GET', '/health/live', schema='Health') ok(live['json'] == {'status': 'ok'}, 'liveness body') ok(bool(live['headers'].get('X-Request-Id')), 'liveness X-Request-Id') ok(bool(live['headers'].get('X-Instance-Id')), 'liveness X-Instance-Id') ready = c.call('GET', '/health/ready', schema='Health') ok(ready['json'] == {'status': 'ok'}, 'readiness body') print('PASS health') def test_registration_and_login(c): alice = register(c) bob = register(c) login(c, alice) login(c, bob) ok(len(alice['session']['token']) >= 32, 'session token shorter than contract minimum') ok(alice['session']['token_type'] == 'Bearer', 'token_type') ok(timestamp(alice['session']['expires_at']) > dt.datetime.now(dt.timezone.utc), 'expiry in the past') ok(alice['session']['user'] == alice['user'], 'session user differs from created user') # Duplicate username, including a different display name/password. c.call('POST', '/api/v1/users', 409, body={ 'username': alice['registration']['username'], 'display_name': 'Другой', 'password': 'Another-password-123', }) # Wrong / unknown / malformed credentials all give the same Basic 401. c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic(alice['registration']['username'], 'wrong-password-123')}) c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic('definitely_unknown', 'wrong-password-123')}) c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!!'}) c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode(b'no-colon').decode()}) c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'}) # Basic is not accepted on business endpoints; X-User-Id grants nothing. c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': basic(alice['registration']['username'], alice['password'])}) c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']}) c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'a' * 43}) c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'X-User-Id ' + alice['id']}) me = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')['json'] ok(me['id'] == alice['id'], 'X-User-Id overrode the bearer identity') # A UTF-8 password containing colons is valid and is not truncated at the # first colon by Basic parsing. unicode_password = 'pässwörd:with:12' unicode_user = register(c, password=unicode_password) login(c, unicode_user) ok(unicode_user['session']['user']['username'] == unicode_user['registration']['username'], 'unicode password login') # Session JSON must never contain the password or its hash. serialized = json.dumps(alice['session'], ensure_ascii=False) for forbidden in ('password', 'argon2', 'salt'): ok(forbidden not in serialized, 'session leaks ' + forbidden) print('PASS registration/auth') def test_registration_validation(c): username = 'bb_' + uuid.uuid4().hex[:10] password = 'B3st-' + uuid.uuid4().hex valid = {'username': username, 'display_name': 'Имя', 'password': password} def bad(body, status=400, raw=None, headers=None): c.call('POST', '/api/v1/users', status, body=body if raw is None else None, raw=raw, headers=headers) bad({'username': username, 'display_name': 'Имя'}) bad({'username': username, 'display_name': 'Имя', 'password': 'short'}) bad({'username': username, 'display_name': 'Имя', 'password': 'p' * 129}) bad({'username': username, 'display_name': 'Имя', 'password': ' ' * 12}) bad({'username': 'ab', 'display_name': 'Имя', 'password': password}) bad({'username': 'a' * 33, 'display_name': 'Имя', 'password': password}) bad({'username': 'UPPER', 'display_name': 'Имя', 'password': password}) bad({'username': 'bad-name', 'display_name': 'Имя', 'password': password}) bad({'username': 'бвт', 'display_name': 'Имя', 'password': password}) bad({'username': username, 'display_name': '', 'password': password}) bad({'username': username, 'display_name': ' ', 'password': password}) bad({'username': username, 'display_name': 'Имя', 'password': password, 'extra': 1}) bad({'username': username, 'display_name': 'Имя', 'password': password, 'Password': 'x'}) bad({'Username': username, 'display_name': 'Имя', 'password': password}) bad({'username': username, 'display_name': 'Имя', 'password': 123456789012}) bad({'username': None, 'display_name': 'Имя', 'password': password}) bad({}, raw=b'{', headers={'Content-Type': 'application/json'}) bad({}, raw=b'[]', headers={'Content-Type': 'application/json'}) bad({}, status=415, raw=json.dumps(valid).encode(), headers={'Content-Type': 'text/plain'}) bad({}, raw=(json.dumps(valid)[:-1] + ', "username": "x"}').encode(), headers={'Content-Type': 'application/json'}) # Exact code-point boundaries. long_name = register(c, display_name='😀' * 100) ok(long_name['user']['display_name'] == '😀' * 100, '100 code points display_name changed') c.call('POST', '/api/v1/users', 400, body={ 'username': 'bb_' + uuid.uuid4().hex[:10], 'display_name': '😀' * 101, 'password': password, }) c.call('POST', '/api/v1/users', 400, body={ 'username': 'a' * 32 + 'b', 'display_name': 'Имя', 'password': password, }) register(c, username='a' * 24 + uuid.uuid4().hex[:8]) print('PASS registration validation') def test_chats(c, alice, bob, eve): chat = new_chat(c, alice, 'Комната с Unicode 🚀', [alice['id'], bob['id']]) ok(set(chat['member_ids']) == {alice['id'], bob['id']}, 'chat member set') expect_keys(chat, {'id', 'title', 'member_ids', 'created_at'}, 'Chat') def bad(body, status=400): c.call('POST', '/api/v1/chats', status, actor=alice, body=body) bad({'title': 'Без автора', 'member_ids': [bob['id']]}) bad({'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]}) bad({'title': 'Неизвестный', 'member_ids': [alice['id'], str(uuid.uuid4())]}) bad({'title': 'Не UUID', 'member_ids': [alice['id'], 'not-a-uuid']}) bad({'title': 'Слишком много', 'member_ids': [alice['id']] + [str(uuid.uuid4()) for _ in range(100)]}) bad({'title': '', 'member_ids': [alice['id']]}) bad({'title': ' ', 'member_ids': [alice['id']]}) bad({'title': 'я' * 101, 'member_ids': [alice['id']]}) bad({'title': 'Лишнее', 'member_ids': [alice['id']], 'extra': True}) bad({'title': 'Нет списка'}) own = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json'] ok(own['id'] == chat['id'], 'member cannot read chat') c.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve) c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice) c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice) c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve, body={'text': 'чужое'}) hidden = c.call('GET', '/api/v1/chats?limit=100', actor=eve, schema='ChatPage')['json'] ok(all(item['id'] != chat['id'] for item in hidden['items']), 'foreign chat leaked into list') listed = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json'] ok(any(item['id'] == chat['id'] for item in listed['items']), 'member chat missing from list') print('PASS chats/membership') def test_messages(c, alice, bob, eve, chat): text = 'Привет 👋 e\u0301 中文' message = send(c, alice, chat, text) expect_keys(message, {'id', 'chat_id', 'sender_id', 'text', 'created_at'}, 'Message') ok(message['text'] == text, 'message text changed') ok(message['sender_id'] == alice['id'] and message['chat_id'] == chat['id'], 'message identity') # X-User-Id cannot substitute for the Bearer owner. spoofed = send(c, alice, chat, 'не от Боба', headers={'X-User-Id': bob['id']}) ok(spoofed['sender_id'] == alice['id'], 'X-User-Id changed the message sender') def bad(actor, body, status=400, raw=None): c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=actor, body=body, raw=raw) bad(alice, {'text': ''}) bad(alice, {'text': ' '}) bad(alice, {'text': None}) bad(alice, {}) bad(alice, {'text': 'x' * 4001}) bad(alice, {'text': 'ok', 'sender_id': alice['id']}) bad(alice, {'text': 'ok', 'attachment_ids': []}) bad(alice, {'Text': 'ok'}) c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice, raw=b'{', headers={'Content-Type': 'application/json'}) # Resource access is checked before body parsing: a foreign chat with a # malformed body still looks like a missing chat. c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve, raw=b'{', headers={'Content-Type': 'application/json'}) boundary = send(c, alice, chat, 'я' * 4000) ok(len(boundary['text']) == 4000, '4000 code point message changed') history = all_messages(c, bob, chat) ok(any(item == boundary for item in history), 'member cannot read message history') print('PASS messages') def test_pagination(c, alice, bob): chat = new_chat(c, alice, 'Пагинация', [alice['id'], bob['id']]) for index in range(23): send(c, alice if index % 2 == 0 else bob, chat, 'строка %02d' % index) expected = sorted_messages(all_messages(c, alice, chat, limit=100)) collected = [] cursor = None limits = [7, 5, 100, 1, 3, 9] step = 0 while True: path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limits[step % len(limits)]) if cursor: from urllib.parse import quote path += '&cursor=' + quote(cursor, safe='') page = c.call('GET', path, actor=bob, schema='MessagePage')['json'] collected.extend(page['items']) step += 1 if page['next_cursor'] is None: break cursor = page['next_cursor'] ok(step < 100, 'pagination did not finish') ok(collected == expected, 'pagination lost, duplicated or reordered messages') ids = [item['id'] for item in collected] ok(len(ids) == len(set(ids)), 'pagination repeated an id') first = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=3', actor=alice, schema='MessagePage')['json'] ok(first['next_cursor'] is not None, 'first page cursor missing') other = new_chat(c, alice, 'Другой чат', [alice['id']]) c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice) c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-base64!!', 400, actor=alice) c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice) c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=101', 400, actor=alice) c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=abc', 400, actor=alice) c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1&limit=2', 400, actor=alice) c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=', 400, actor=alice) # A message cursor is scoped to a chat and cannot continue the chat list. c.call('GET', '/api/v1/chats?cursor=' + first['next_cursor'], 400, actor=alice) listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json'] ok(any(item['id'] == chat['id'] for item in listed['items']), 'paginated chat missing from list') ok(any(item['id'] == other['id'] for item in listed['items']), 'other chat missing from list') print('PASS pagination') def test_concurrent_registration(c): username = 'race_' + uuid.uuid4().hex[:10] body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-123'} def attempt(_): local = Client(c.base) try: return local.call('POST', '/api/v1/users', (201, 409), body=body)['status'] except Exception as exc: # failures are assertions for this test return 'error:' + type(exc).__name__ barrier = threading.Barrier(8) def synchronized_attempt(index): barrier.wait() return attempt(index) with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: statuses = list(pool.map(synchronized_attempt, range(8))) ok(statuses.count(201) == 1, 'concurrent registration: expected exactly one 201, got ' + repr(statuses)) ok(statuses.count(409) == 7, 'concurrent registration: expected seven 409, got ' + repr(statuses)) c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(username, 'Race-password-123')}, schema='Session') print('PASS concurrent registration') def test_concurrent_messages(c, alice, bob): chat = new_chat(c, alice, 'Конкурентная запись', [alice['id'], bob['id']]) def worker(index): local = Client(c.base) actor = alice if index % 2 == 0 else bob return local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor, body={'text': 'concurrent %02d' % index}, schema='Message')['json'] with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: messages = list(pool.map(worker, range(24))) ids = [message['id'] for message in messages] ok(len(ids) == 24 and len(set(ids)) == 24, 'concurrent messages produced duplicate ids') for index, message in enumerate(messages): ok(message['sender_id'] == (alice['id'] if index % 2 == 0 else bob['id']), 'concurrent sender mismatch') history = all_messages(c, alice, chat) ok(len(history) == 24, 'concurrent history has %d rows, want 24' % len(history)) ok(sorted_messages(history) == history, 'concurrent history is not ordered by (created_at, id)') ok([item['text'] for item in history].count('concurrent 00') == 1, 'concurrent duplicate text') print('PASS concurrent messages') def test_logout(c, alice): second = login(c, {'id': alice['id'], 'user': alice['user'], 'registration': alice['registration'], 'password': alice['password']}) first_token = alice['token'] c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) c.call('GET', '/api/v1/users/me', 401, actor={'token': first_token}) c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor={'token': first_token}) me = c.call('GET', '/api/v1/users/me', actor=second, schema='User')['json'] ok(me['id'] == alice['id'], 'logout revoked another session of the same user') alice['token'] = second['token'] print('PASS logout') def main(): args = arguments('Lab2 own black-box suite; creates synthetic data') c = Client(args.base_url, args.ca_file) test_health(c) alice = register(c) bob = register(c) eve = register(c) login(c, alice) login(c, bob) login(c, eve) test_registration_and_login(c) test_registration_validation(c) test_chats(c, alice, bob, eve) chat = new_chat(c, alice, 'Основной чат blackbox', [alice['id'], bob['id']]) test_messages(c, alice, bob, eve, chat) test_pagination(c, alice, bob) test_concurrent_registration(c) test_concurrent_messages(c, alice, bob) test_logout(c, alice) print('PASS: lab2 student black-box suite, %d checks' % CHECKS) if __name__ == '__main__': try: main() except AssertionError as exc: print('FAIL:', exc) raise SystemExit(1)