forked from mtusi2026/mtusi2026lab2
128 lines
4.9 KiB
Python
128 lines
4.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Дополнительные проверки уровня 4: auth, expiry, гонка username, rollback чата."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, check # noqa: E402
|
|
|
|
|
|
BASE = os.environ.get('BASE_URL', 'http://localhost:8080').rstrip('/')
|
|
|
|
|
|
def raw_request(method, path, expected, body=None, headers=None):
|
|
data = None
|
|
h = {'Accept': 'application/json'}
|
|
if body is not None:
|
|
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
h['Content-Type'] = 'application/json'
|
|
h.update(headers or {})
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
response = urllib.request.urlopen(req, timeout=10)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
payload = response.read()
|
|
check(response.code == expected, f'{method} {path}: expected {expected}, got {response.code}')
|
|
return response.code, response.headers, json.loads(payload) if payload else None
|
|
|
|
|
|
class Lab2Grade4Tests(unittest.TestCase):
|
|
def test_logout_revokes_session(self):
|
|
c = Client(BASE)
|
|
actor = c.user('logout')
|
|
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
|
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
|
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
|
|
|
def test_wrong_password_rejected(self):
|
|
c = Client(BASE)
|
|
actor = c.user('pwd')
|
|
bad = base64.b64encode(
|
|
(actor['registration']['username'] + ':wrong-password-x').encode()
|
|
).decode()
|
|
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + bad})
|
|
|
|
def test_readiness_requires_dependencies(self):
|
|
c = Client(BASE)
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
|
|
@unittest.skipUnless(
|
|
os.environ.get('RUN_EXPIRY_TEST') == '1',
|
|
'Set RUN_EXPIRY_TEST=1 and SESSION_TTL_SECONDS=2 on the API, then rerun',
|
|
)
|
|
def test_session_expiry(self):
|
|
c = Client(BASE)
|
|
username = 'u_exp_' + uuid.uuid4().hex[:12]
|
|
password = 'T3st-' + uuid.uuid4().hex
|
|
body = {'username': username, 'display_name': 'Expiry', 'password': password}
|
|
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
|
|
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
|
session = c.call(
|
|
'POST', '/api/v1/auth/sessions', 201,
|
|
headers={'Authorization': 'Basic ' + credential},
|
|
schema='Session',
|
|
)['json']
|
|
actor = {'id': user['id'], 'user': user, 'registration': body, 'token': session['token']}
|
|
time.sleep(3)
|
|
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
|
|
|
def test_duplicate_username_race(self):
|
|
c = Client(BASE)
|
|
username = 'u_race_' + uuid.uuid4().hex[:10]
|
|
password = 'T3st-' + uuid.uuid4().hex
|
|
body = {
|
|
'username': username,
|
|
'display_name': 'Race',
|
|
'password': password,
|
|
}
|
|
|
|
def register():
|
|
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
req = urllib.request.Request(
|
|
BASE + '/api/v1/users',
|
|
data=data,
|
|
headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
|
|
method='POST',
|
|
)
|
|
try:
|
|
response = urllib.request.urlopen(req, timeout=10)
|
|
except urllib.error.HTTPError as error:
|
|
return error.code
|
|
with response:
|
|
return response.code
|
|
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
statuses = list(pool.map(lambda _: register(), range(8)))
|
|
check(all(code in (201, 409) for code in statuses), f'unexpected race statuses: {set(statuses)}')
|
|
check(sum(1 for code in statuses if code == 201) == 1, 'expected exactly one 201')
|
|
|
|
def test_chat_creation_rollback_unknown_member(self):
|
|
c = Client(BASE)
|
|
alice = c.user('rb_alice')
|
|
bob = c.user('rb_bob')
|
|
fake = str(uuid.uuid4())
|
|
c.call(
|
|
'POST', '/api/v1/chats', 400, actor=alice,
|
|
body={'title': 'Bad', 'member_ids': [alice['id'], fake]},
|
|
)
|
|
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
|
|
check(all(item['title'] != 'Bad' for item in listed['items']), 'chat row leaked after rollback')
|
|
listed_bob = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
|
|
check(all(item['title'] != 'Bad' for item in listed_bob['items']), 'chat row leaked to bob')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|