Files
mtusi2026lab2/student-tests/extra_checks.py
T

105 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Собственные проверки lab2 поверх публичных (stdlib, Python 3.9+; работают на Windows/Linux).
python student-tests/extra_checks.py # гонка регистрации, откат чата, auth-негативы
python student-tests/extra_checks.py --expiry # истечение сессии; API запущен с SESSION_TTL_SECONDS=2
Создаёт синтетических пользователей; токены не печатаются. Публичные tests/ не изменяются и не ослабляются.
"""
import base64
import sys
import threading
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, arguments, check, run, timestamp # noqa: E402
import datetime as dt # noqa: E402
def basic(username, password):
return {'Authorization': 'Basic ' + base64.b64encode((username + ':' + password).encode()).decode()}
def register_race(c):
"""12 одновременных регистраций одного username: ровно одна 201, остальные 409."""
username = 'race_' + uuid.uuid4().hex[:12]
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-' + uuid.uuid4().hex}
codes, lock = [], threading.Lock()
def worker():
r = c.call('POST', '/api/v1/users', [201, 409], body=body)
with lock:
codes.append(r['status'])
threads = [threading.Thread(target=worker) for _ in range(12)]
[t.start() for t in threads]
[t.join() for t in threads]
check(codes.count(201) == 1 and codes.count(409) == 11, 'race: expected one 201 and eleven 409, got %r' % sorted(codes))
print('OK регистрация одного username в гонке: 1×201 + 11×409')
def chat_atomicity(c):
"""Чат с несуществующим участником: 400 и ни одного «половинчатого» чата у пользователя."""
alice = c.user('atom')
ghost = str(uuid.uuid4())
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'призрак', 'member_ids': [alice['id'], ghost]})
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
check(listed['items'] == [], 'failed chat creation left a chat behind')
print('OK создание чата с неизвестным участником: 400, чатов нет (атомарность)')
def auth_negatives(c):
alice = c.user('neg')
reg = alice['registration']
# неверный пароль и неизвестный пользователь неразличимы
a = c.call('POST', '/api/v1/auth/sessions', 401, headers=basic(reg['username'], 'wrong-password-123'))
b = c.call('POST', '/api/v1/auth/sessions', 401, headers=basic('nobody_' + uuid.uuid4().hex[:8], 'wrong-password-123'))
check(a['json']['error']['message'] == b['json']['error']['message'], 'login errors reveal whether the user exists')
# Bearer вместо Basic и отсутствие заголовка на /auth/sessions
c.call('POST', '/api/v1/auth/sessions', 401, actor=alice)
c.call('POST', '/api/v1/auth/sessions', 401)
# токен выглядит как случайный непрозрачный (>=256 бит), а не как username/UUID
token = alice['token']
check(len(token) >= 43 and reg['username'] not in token and alice['id'] not in token, 'token is not opaque/random enough')
# пароль не возвращается нигде
me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
check('password' not in me and 'password_hash' not in me, 'password data leaked in User')
# пароль короче 12 символов и лишние поля — 400
c.call('POST', '/api/v1/users', 400, body={'username': 'short_' + uuid.uuid4().hex[:8], 'display_name': 'x', 'password': 'short'})
c.call('POST', '/api/v1/users', 400, body={'username': 'extra_' + uuid.uuid4().hex[:8], 'display_name': 'x', 'password': 'long-enough-password', 'is_admin': True})
print('OK негативные сценарии аутентификации (401/400, токен непрозрачный)')
def expiry(c):
username = 'ttl_' + uuid.uuid4().hex[:12]
password = 'Ttl-password-' + uuid.uuid4().hex
c.call('POST', '/api/v1/users', 201, body={'username': username, 'display_name': 'TTL', 'password': password}, schema='User')
s = c.call('POST', '/api/v1/auth/sessions', 201, headers=basic(username, password), schema='Session')['json']
now = dt.datetime.now(dt.timezone.utc)
ttl = (timestamp(s['expires_at']) - now).total_seconds()
check(ttl <= 30, 'expiry check needs a short TTL: start API with SESSION_TTL_SECONDS=2 (now %.0fs)' % ttl)
actor = {'id': s['user']['id'], 'token': s['token']}
c.call('GET', '/api/v1/users/me', 200, actor=actor)
time.sleep(max(0.0, ttl) + 1.2)
c.call('GET', '/api/v1/users/me', 401, actor=actor)
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
print('OK сессия с TTL≈%.0f с действовала, после истечения — 401' % ttl)
def main():
args = arguments('Extra lab2 checks', lambda p: p.add_argument('--expiry', action='store_true'))
c = Client(args.base_url, args.ca_file)
if args.expiry:
expiry(c)
else:
register_race(c)
chat_atomicity(c)
auth_negatives(c)
print('PASS')
if __name__ == '__main__':
run(main)