Перенести мессенджер в PostgreSQL и сессии в Redis.

Подтверждённые сообщения и действующие сессии переживают перезапуск, история читается по индексу, копия восстанавливается в новый том.
This commit is contained in:
2026-10-23 12:50:45 +03:00
parent 65003b6119
commit f9b2fd11e0
29 changed files with 2933 additions and 35 deletions
+37
View File
@@ -0,0 +1,37 @@
import json
import urllib.error
import urllib.request
def request(method, path, base='http://127.0.0.1:8080', body=None, headers=None, timeout=10):
data = None
hdrs = {}
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
hdrs['Content-Type'] = 'application/json'
if headers:
hdrs.update(headers)
req = urllib.request.Request(base + path, data=data, headers=hdrs, method=method)
try:
response = urllib.request.urlopen(req, timeout=timeout)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw.decode('utf-8'))
except (UnicodeError, json.JSONDecodeError):
payload = None
return response.status, response.headers, payload
def basic(username, password):
import base64
token = base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
return {'Authorization': 'Basic ' + token}
def bearer(token):
return {'Authorization': 'Bearer ' + token}
+163
View File
@@ -0,0 +1,163 @@
"""Logout is covered in test_api.py. This script checks expiry and a dead Redis or Postgres.
It stops containers and starts them again. Do not run it in parallel with smoke.
"""
import json
import subprocess
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
from api import basic, bearer, request
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / 'evidence'
def docker(*args, check=True):
return subprocess.run(['docker', *args], cwd=ROOT, check=check, capture_output=True, text=True)
def wait_ready(base, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
status, _, payload = request('GET', '/health/ready', base=base, timeout=3)
if status == 200 and payload == {'status': 'ok'}:
return True
except Exception:
pass
time.sleep(0.5)
return False
def account(base):
username = 'dep_' + uuid.uuid4().hex[:8]
password = 'dep-password-1'
status, _, user = request('POST', '/api/v1/users', base=base, body={
'username': username,
'display_name': 'Проверка',
'password': password,
})
if status != 201:
raise SystemExit('register failed: %s' % status)
status, _, session = request('POST', '/api/v1/auth/sessions', base=base, headers=basic(username, password))
if status != 201:
raise SystemExit('login failed: %s' % status)
return user, session['token'], session['expires_at']
def expect(name, method, path, code, base='http://127.0.0.1:8080', headers=None):
status, response_headers, payload = request(method, path, base=base, headers=headers, timeout=12)
if status != code:
raise SystemExit('%s: expected %s, got %s %s' % (name, code, status, payload))
return {
'name': name,
'status': status,
'code': None if payload is None else payload.get('error', {}).get('code'),
'www_authenticate': response_headers.get('WWW-Authenticate'),
}
def redis_and_postgres():
base = 'http://127.0.0.1:8080'
if not wait_ready(base):
raise SystemExit('API was not ready')
user, token, _ = account(base)
auth = bearer(token)
status, _, chat = request('POST', '/api/v1/chats', base=base, headers=auth, body={
'title': 'зависимость',
'member_ids': [user['id']],
})
if status != 201:
raise SystemExit('chat failed')
status, _, message = request(
'POST', '/api/v1/chats/%s/messages' % chat['id'],
base=base, headers=auth, body={'text': 'до отказа'},
)
if status != 201:
raise SystemExit('message failed')
rows = []
docker('stop', 'mtusi-lab2-redis')
try:
rows.append(expect('redis down, no token', 'GET', '/api/v1/users/me', 401))
rows.append(expect('redis down, bearer', 'GET', '/api/v1/users/me', 503, headers=auth))
rows.append(expect('redis down, live', 'GET', '/health/live', 200))
rows.append(expect('redis down, ready', 'GET', '/health/ready', 503))
finally:
docker('start', 'mtusi-lab2-redis')
if not wait_ready(base):
raise SystemExit('API did not recover after redis start')
rows.append(expect('redis back, same token', 'GET', '/api/v1/users/me', 200, headers=auth))
status, _, page = request('GET', '/api/v1/chats/%s/messages?limit=10' % chat['id'], headers=auth)
if status != 200 or page['items'] != [message]:
raise SystemExit('message lost across redis stop')
rows.append({'name': 'history after redis stop', 'status': 200, 'same_message': True})
docker('stop', 'mtusi-lab2-postgres')
try:
rows.append(expect('postgres down, no token', 'GET', '/api/v1/users/me', 401))
rows.append(expect('postgres down, bearer', 'GET', '/api/v1/users/me', 503, headers=auth))
rows.append(expect('postgres down, live', 'GET', '/health/live', 200))
rows.append(expect('postgres down, ready', 'GET', '/health/ready', 503))
finally:
docker('start', 'mtusi-lab2-postgres')
if not wait_ready(base, timeout=90):
raise SystemExit('API did not recover after postgres start')
rows.append(expect('postgres back, same token', 'GET', '/api/v1/users/me', 200, headers=auth))
status, _, page = request('GET', '/api/v1/chats/%s/messages?limit=10' % chat['id'], headers=auth)
if status != 200 or page['items'] != [message]:
raise SystemExit('message lost across postgres stop')
rows.append({'name': 'history after postgres stop', 'status': 200, 'same_message': True})
return rows
def short_ttl():
subprocess.run(
['docker', 'compose', '--env-file', '.env', '--profile', 'shortttl', 'up', '-d', 'api-short'],
cwd=ROOT, check=True,
)
base = 'http://127.0.0.1:8081'
try:
if not wait_ready(base, timeout=90):
raise SystemExit('short TTL API was not ready')
_, token, expires_at = account(base)
expires = datetime.fromisoformat(expires_at.replace('Z', '+00:00'))
delta = (expires - datetime.now(timezone.utc)).total_seconds()
if not 0 < delta < 10:
raise SystemExit('expected a short session, delta=%s' % delta)
status, _, _ = request('GET', '/api/v1/users/me', base=base, headers=bearer(token))
if status != 200:
raise SystemExit('fresh short session was rejected')
time.sleep(delta + 1.5)
status, headers, payload = request('GET', '/api/v1/users/me', base=base, headers=bearer(token), timeout=10)
if status != 401:
raise SystemExit('expired session returned %s' % status)
return {
'ttl_window_seconds': round(delta, 3),
'after_expiry': status,
'www_authenticate': headers.get('WWW-Authenticate'),
'error_code': payload['error']['code'],
}
finally:
docker('stop', 'mtusi-lab2-api-short', check=False)
def main():
report = {
'redis_and_postgres': redis_and_postgres(),
'short_ttl': short_ttl(),
}
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / 'dependencies.json').write_text(
json.dumps(report, ensure_ascii=False, indent=2) + '\n',
encoding='utf-8',
)
print('PASS dependencies')
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
+517
View File
@@ -0,0 +1,517 @@
"""Track 2: uneven history, two indexes, backup into a new Postgres volume.
The bench database is not the API database. Scratch containers are removed at the end.
"""
import json
import platform
import subprocess
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
import psycopg
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'src'))
import db # noqa: E402
EVIDENCE = ROOT / 'evidence'
BACKUPS = ROOT / 'backups'
RESTORE_NAME = 'mtusi-lab2-restore'
RESTORE_VOLUME = 'mtusi-lab2-restore-data'
def load_env():
env = {}
for line in (ROOT / '.env').read_text(encoding='utf-8').splitlines():
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
env[key] = value
return env
def connect(url):
return psycopg.connect(url, connect_timeout=10)
def chat_sizes():
sizes = [80000] + [4000] * 4 + [300] * 10 + [40] * 20 + [10] * 20 + [1] * 100
if sum(sizes) < 100000:
raise SystemExit('fixture is smaller than 100000 messages')
return sizes
def reset_bench(admin_url):
with psycopg.connect(admin_url, autocommit=True) as conn:
conn.execute(
"""
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'messenger_bench' AND pid <> pg_backend_pid()
"""
)
conn.execute('DROP DATABASE IF EXISTS messenger_bench')
conn.execute('CREATE DATABASE messenger_bench')
def seed(url):
users = []
with connect(url) as conn:
for name in ('bench_a', 'bench_b', 'bench_c'):
user_id = uuid.uuid4()
conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(user_id, name, 'Стенд ' + name, 'bench-not-a-login-hash', datetime.now(timezone.utc)),
)
users.append(user_id)
conn.commit()
sizes = chat_sizes()
chats = []
for index, size in enumerate(sizes):
chat_id = uuid.uuid4()
conn.execute(
'INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)',
(chat_id, 'чат %s' % index, datetime.now(timezone.utc)),
)
member_ids = users if size >= 4000 else users[:1]
for ordinal, member_id in enumerate(member_ids):
conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, member_ord)
VALUES (%s, %s, %s)
""",
(chat_id, member_id, ordinal),
)
chats.append((chat_id, size))
conn.commit()
samples = {}
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
# Spread one chat's messages across the whole timeline. An index on
# created_at alone then has to skip other chats; (chat_id, created_at, id) does not.
chat_count = len(chats)
sender = users[0]
with conn.cursor() as cur:
with cur.copy(
'COPY messages (id, chat_id, sender_id, body, created_at) FROM STDIN'
) as copy:
for chat_index, (chat_id, size) in enumerate(chats):
for i in range(size):
message_id = uuid.uuid4()
created = base + timedelta(microseconds=i * chat_count + chat_index)
if i % 1000 == 0:
body = ('длинное-%s-' % i) + ('я' * 180)
else:
body = 'm-%s-%s' % (chat_index, i)
copy.write_row((message_id, chat_id, sender, body, created))
mark = {
'id': str(message_id),
'chat_id': str(chat_id),
'sender_id': str(sender),
'body': body,
'created_at': created.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}
if chat_index == 0 and i == 0:
samples['huge_first'] = mark
elif chat_index == 0 and i == 40000:
samples['huge_middle'] = mark
elif chat_index == 0 and i == size - 1:
samples['huge_last'] = mark
elif chat_index == 1 and i == 2000:
samples['medium'] = mark
elif size == 1 and 'tiny' not in samples:
samples['tiny'] = mark
if chat_index % 20 == 0:
print('seeded chat %s/%s' % (chat_index + 1, len(chats)), flush=True)
conn.commit()
conn.execute('ANALYZE users, chats, chat_members, messages')
conn.commit()
huge_id = chats[0][0]
return {
'sizes': sizes,
'samples': samples,
'huge_chat_id': str(huge_id),
'sender_id': str(sender),
'message_count': sum(sizes),
'chat_count': len(sizes),
'user_count': len(users),
}
def explain(conn, sql, params):
text = ''
for _ in range(2):
rows = conn.execute('EXPLAIN (ANALYZE, BUFFERS) ' + sql, params).fetchall()
text = '\n'.join(row[0] for row in rows)
return text
def summary_line(text, needle):
for line in text.splitlines():
if needle in line:
return line.strip()
return ''
def plan_brief(text):
scan = ''
for line in text.splitlines():
stripped = line.strip()
if 'Scan' in stripped or 'Seq Scan' in stripped:
scan = stripped
break
return {
'scan': scan,
'buffers': summary_line(text, 'Buffers:'),
'execution_time': summary_line(text, 'Execution Time:'),
'planning_time': summary_line(text, 'Planning Time:'),
}
KEYSET = """
SELECT id, chat_id, sender_id, body, created_at
FROM messages
WHERE chat_id = %s
AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT 50
"""
OFFSET = """
SELECT id, chat_id, sender_id, body, created_at
FROM messages
WHERE chat_id = %s
ORDER BY created_at, id
OFFSET 40000
LIMIT 50
"""
def _mark_params(mark):
created = datetime.strptime(mark['created_at'], '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=timezone.utc)
return (uuid.UUID(mark['chat_id']), created, uuid.UUID(mark['id']))
def plans(url, seeded):
# Page inside the 80k chat. Past the smaller chats this timestamp is mostly one chat,
# so the created_at-only index is judged on the 4k chat instead, where other chats still overlap.
huge_params = _mark_params(seeded['samples']['huge_middle'])
medium_params = _mark_params(seeded['samples']['medium'])
huge = uuid.UUID(seeded['huge_chat_id'])
with connect(url) as conn:
keyset = explain(conn, KEYSET, huge_params)
offset = explain(conn, OFFSET, (huge,))
conn.execute('DROP INDEX messages_chat_history_idx')
conn.commit()
seqscan = explain(conn, KEYSET, medium_params)
conn.execute('CREATE INDEX messages_created_only_idx ON messages (created_at)')
conn.execute('ANALYZE messages')
conn.commit()
created_only = explain(conn, KEYSET, medium_params)
conn.execute('DROP INDEX messages_created_only_idx')
started = time.perf_counter()
conn.execute(
'CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id)'
)
conn.commit()
create_index_ms = (time.perf_counter() - started) * 1000
conn.execute('ANALYZE messages')
conn.commit()
return {
'keyset': keyset,
'offset': offset,
'seqscan': seqscan,
'created_only': created_only,
'create_index_ms': round(create_index_ms, 1),
}
def timed_insert(conn, chat_id, sender_id, n):
base = datetime(2027, 1, 1, tzinfo=timezone.utc)
started = time.perf_counter()
try:
with conn.cursor() as cur:
with cur.copy(
'COPY messages (id, chat_id, sender_id, body, created_at) FROM STDIN'
) as copy:
for i in range(n):
copy.write_row((
uuid.uuid4(),
chat_id,
sender_id,
'cost-%s' % i,
base + timedelta(microseconds=i),
))
return (time.perf_counter() - started) * 1000
finally:
conn.rollback()
def write_cost(url, seeded):
chat_id = uuid.UUID(seeded['huge_chat_id'])
sender_id = uuid.UUID(seeded['sender_id'])
with connect(url) as conn:
with_index = timed_insert(conn, chat_id, sender_id, 2000)
conn.execute('DROP INDEX messages_chat_history_idx')
conn.commit()
without_index = timed_insert(conn, chat_id, sender_id, 2000)
conn.execute(
'CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id)'
)
conn.commit()
return {
'rows': 2000,
'with_history_index_ms': round(with_index, 1),
'without_secondary_index_ms': round(without_index, 1),
}
def counts(url):
with connect(url) as conn:
row = conn.execute(
"""
SELECT
(SELECT count(*) FROM users),
(SELECT count(*) FROM chats),
(SELECT count(*) FROM chat_members),
(SELECT count(*) FROM messages),
(SELECT version()),
(SELECT current_setting('synchronous_commit')),
(SELECT current_setting('fsync')),
(SELECT current_setting('shared_buffers'))
"""
).fetchone()
return {
'users': row[0],
'chats': row[1],
'chat_members': row[2],
'messages': row[3],
'version': row[4],
'synchronous_commit': row[5],
'fsync': row[6],
'shared_buffers': row[7],
}
def fetch_sample(url, message_id):
with connect(url) as conn:
row = conn.execute(
"""
SELECT id::text, chat_id::text, sender_id::text, body,
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')
FROM messages
WHERE id = %s
""",
(uuid.UUID(message_id),),
).fetchone()
if row is None:
return None
return {
'id': row[0],
'chat_id': row[1],
'sender_id': row[2],
'body': row[3],
'created_at': row[4],
}
def dump_bench(password):
started = time.perf_counter()
# pg_dump writes the custom archive to stdout. No TTY, so the bytes stay intact.
data = subprocess.check_output(
[
'docker', 'exec', 'mtusi-lab2-postgres',
'pg_dump', '-U', 'messenger', '-d', 'messenger_bench',
'-Fc', '--no-owner', '--no-acl',
]
)
BACKUPS.mkdir(exist_ok=True)
path = BACKUPS / 'messenger_bench.dump'
path.write_bytes(data)
return path, round(time.perf_counter() - started, 3), len(data)
def image_of_source():
return subprocess.check_output(
['docker', 'inspect', '-f', '{{.Config.Image}}', 'mtusi-lab2-postgres'],
text=True,
).strip()
def restore_into_new_volume(dump_path, password, image):
subprocess.run(['docker', 'rm', '-f', RESTORE_NAME], capture_output=True)
subprocess.run(['docker', 'volume', 'rm', RESTORE_VOLUME], capture_output=True)
subprocess.run(
[
'docker', 'run', '-d', '--name', RESTORE_NAME,
'-e', 'POSTGRES_USER=messenger',
'-e', 'POSTGRES_PASSWORD=' + password,
'-e', 'POSTGRES_DB=messenger',
'-p', '127.0.0.1:5433:5432',
'-v', RESTORE_VOLUME + ':/var/lib/postgresql/data',
image,
],
check=True,
capture_output=True,
)
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
probe = subprocess.run(
['docker', 'exec', RESTORE_NAME, 'pg_isready', '-U', 'messenger', '-d', 'messenger'],
capture_output=True,
)
if probe.returncode == 0:
break
time.sleep(1)
else:
raise SystemExit('restore postgres did not become ready')
subprocess.run(
['docker', 'cp', str(dump_path), RESTORE_NAME + ':/tmp/bench.dump'],
check=True,
)
started = time.perf_counter()
subprocess.run(
[
'docker', 'exec', RESTORE_NAME,
'pg_restore', '-U', 'messenger', '-d', 'messenger',
'--no-owner', '--exit-on-error', '/tmp/bench.dump',
],
check=True,
)
return round(time.perf_counter() - started, 3)
def cleanup_restore():
subprocess.run(['docker', 'rm', '-f', RESTORE_NAME], capture_output=True)
subprocess.run(['docker', 'volume', 'rm', RESTORE_VOLUME], capture_output=True)
def drop_bench(admin_url):
with psycopg.connect(admin_url, autocommit=True) as conn:
conn.execute(
"""
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'messenger_bench' AND pid <> pg_backend_pid()
"""
)
conn.execute('DROP DATABASE IF EXISTS messenger_bench')
def main():
env = load_env()
password = env['POSTGRES_PASSWORD']
admin_url = 'postgresql://messenger:%s@127.0.0.1:5432/messenger' % password
bench_url = 'postgresql://messenger:%s@127.0.0.1:5432/messenger_bench' % password
restored_url = 'postgresql://messenger:%s@127.0.0.1:5433/messenger' % password
EVIDENCE.mkdir(exist_ok=True)
try:
print('reset bench', flush=True)
reset_bench(admin_url)
print('migrate bench', flush=True)
applied = db.apply_migrations(bench_url)
print('applied %s' % applied, flush=True)
print('seed', flush=True)
started = time.perf_counter()
seeded = seed(bench_url)
seed_seconds = round(time.perf_counter() - started, 3)
print('seeded %s messages in %ss' % (seeded['message_count'], seed_seconds), flush=True)
print('explain', flush=True)
explained = plans(bench_url, seeded)
(EVIDENCE / 'explain-keyset.txt').write_text(explained['keyset'] + '\n', encoding='utf-8')
(EVIDENCE / 'explain-offset.txt').write_text(explained['offset'] + '\n', encoding='utf-8')
(EVIDENCE / 'explain-seqscan.txt').write_text(explained['seqscan'] + '\n', encoding='utf-8')
(EVIDENCE / 'explain-created-only.txt').write_text(explained['created_only'] + '\n', encoding='utf-8')
print('write cost', flush=True)
cost = write_cost(bench_url, seeded)
source_counts = counts(bench_url)
print('dump', flush=True)
dump_path, dump_seconds, dump_bytes = dump_bench(password)
image = image_of_source()
print('restore into %s' % image, flush=True)
restore_seconds = restore_into_new_volume(dump_path, password, image)
restored_counts = counts(restored_url)
compared = {}
for name, sample in seeded['samples'].items():
got = fetch_sample(restored_url, sample['id'])
compared[name] = got == sample
if got != sample:
print('mismatch', name, file=sys.stderr)
print('expected', sample, file=sys.stderr)
print('got', got, file=sys.stderr)
with connect(restored_url) as conn:
conn.execute('ANALYZE messages')
conn.commit()
mark = seeded['samples']['huge_middle']
created = datetime.strptime(mark['created_at'], '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=timezone.utc)
restored_plan = explain(conn, KEYSET, (
uuid.UUID(mark['chat_id']), created, uuid.UUID(mark['id']),
))
(EVIDENCE / 'explain-restored.txt').write_text(restored_plan + '\n', encoding='utf-8')
indexes = []
with connect(restored_url) as conn:
indexes = [row[0] for row in conn.execute(
"SELECT indexname FROM pg_indexes WHERE tablename = 'messages' ORDER BY 1"
).fetchall()]
report = {
'platform': platform.platform(),
'processor': platform.processor(),
'python': platform.python_version(),
'seed_seconds': seed_seconds,
'chat_sizes_head': seeded['sizes'][:8],
'chat_count': seeded['chat_count'],
'smallest_chat': min(seeded['sizes']),
'largest_chat': max(seeded['sizes']),
'source': {key: source_counts[key] for key in (
'users', 'chats', 'chat_members', 'messages', 'version',
'synchronous_commit', 'fsync', 'shared_buffers',
)},
'restored': {key: restored_counts[key] for key in (
'users', 'chats', 'chat_members', 'messages',
)},
'counts_match': (
source_counts['users'] == restored_counts['users']
and source_counts['chats'] == restored_counts['chats']
and source_counts['chat_members'] == restored_counts['chat_members']
and source_counts['messages'] == restored_counts['messages']
),
'samples_match': compared,
'dump_seconds': dump_seconds,
'dump_bytes': dump_bytes,
'restore_seconds': restore_seconds,
'create_index_ms': explained['create_index_ms'],
'write_cost': cost,
'keyset': plan_brief(explained['keyset']),
'offset': plan_brief(explained['offset']),
'seqscan': plan_brief(explained['seqscan']),
'created_only': plan_brief(explained['created_only']),
'restored_keyset': plan_brief(restored_plan),
'restored_message_indexes': indexes,
'dump_file': 'backups/messenger_bench.dump',
}
(EVIDENCE / 'track2.json').write_text(
json.dumps(report, ensure_ascii=False, indent=2) + '\n',
encoding='utf-8',
)
print(json.dumps(report, ensure_ascii=False, indent=2))
if not report['counts_match'] or not all(compared.values()):
raise SystemExit('restore comparison failed')
print('PASS track2')
finally:
cleanup_restore()
try:
drop_bench(admin_url)
except Exception as exc:
print('bench cleanup: %s' % type(exc).__name__, flush=True)
if __name__ == '__main__':
main()
+215
View File
@@ -0,0 +1,215 @@
import subprocess
import threading
import unittest
import uuid
from urllib.parse import quote
from api import basic, bearer, request
def psql(sql):
result = subprocess.run(
[
'docker', 'exec', '-i', 'mtusi-lab2-postgres',
'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-tAc', sql,
],
check=True,
capture_output=True,
text=True,
)
return result.stdout.strip()
def register(username, password, display_name='Студент'):
status, headers, payload = request('POST', '/api/v1/users', body={
'username': username,
'display_name': display_name,
'password': password,
})
return status, headers, payload
class ApiTests(unittest.TestCase):
def test_lab1_edges_still_hold(self):
status, headers, payload = request(
'POST', '/api/v1/users',
body={'username': 'not a user', 'display_name': 'Имя', 'password': 'long-enough-pass'},
headers={'Content-Type': 'application/jsonx'},
)
self.assertEqual(status, 415)
self.assertEqual(payload['error']['code'], 'unsupported_media_type')
self.assertTrue(headers['X-Request-Id'])
username = 'edge_' + uuid.uuid4().hex[:8]
password = 'edge-password-1'
status, _, user = register(username, password)
self.assertEqual(status, 201)
self.assertNotIn('password', user)
self.assertNotIn('password_hash', user)
status, _, session = request('POST', '/api/v1/auth/sessions', headers=basic(username, password))
self.assertEqual(status, 201)
token = session['token']
auth = bearer(token)
status, _, chat = request('POST', '/api/v1/chats', headers=auth, body={
'title': 'края',
'member_ids': [user['id']],
})
self.assertEqual(status, 201)
path = '/api/v1/chats/' + chat['id'] + '/messages'
status, _, _ = request('GET', path + '?limit=999999999', headers=auth)
self.assertEqual(status, 400)
status, _, _ = request('GET', path + '?cursor=@@@', headers=auth)
self.assertEqual(status, 400)
status, _, _ = request('POST', '/api/v1/users', body={
'username': username,
'display_name': 'Имя',
'password': 'long-enough-pass',
'extra': 1,
})
self.assertEqual(status, 400)
def test_password_hash_is_argon2id_and_quotes_stay_data(self):
username = 'hash_' + uuid.uuid4().hex[:8]
password = 'hash-password-1'
display = "a'; drop table users;--"
status, _, user = register(username, password, display)
self.assertEqual(status, 201)
stored_name = psql("SELECT display_name FROM users WHERE username = '%s'" % username)
self.assertEqual(stored_name, display)
prefix = psql("SELECT left(password_hash, 9) FROM users WHERE username = '%s'" % username)
self.assertEqual(prefix, '$argon2id')
leaked = psql(
"SELECT position('%s' in password_hash) FROM users WHERE username = '%s'" % (password, username)
)
self.assertEqual(leaked, '0')
self.assertEqual(psql("SELECT to_regclass('public.users')"), 'users')
status, headers, _ = request(
'POST', '/api/v1/auth/sessions',
headers=basic(username, 'wrong-password'),
)
self.assertEqual(status, 401)
self.assertTrue(headers['WWW-Authenticate'].lower().startswith('basic'))
def test_colon_in_password_and_logout(self):
username = 'colon_' + uuid.uuid4().hex[:8]
password = 'left:right:pass'
status, _, user = register(username, password)
self.assertEqual(status, 201)
status, _, session = request('POST', '/api/v1/auth/sessions', headers=basic(username, password))
self.assertEqual(status, 201)
auth = bearer(session['token'])
status, _, me = request('GET', '/api/v1/users/me', headers=auth)
self.assertEqual(status, 200)
self.assertEqual(me['id'], user['id'])
status, _, me = request(
'GET', '/api/v1/users/me',
headers={**auth, 'X-User-Id': str(uuid.uuid4())},
)
self.assertEqual(me['id'], user['id'])
status, headers, _ = request('GET', '/api/v1/users/me', headers={'X-User-Id': user['id']})
self.assertEqual(status, 401)
self.assertTrue(headers['WWW-Authenticate'].lower().startswith('bearer'))
status, headers, _ = request('GET', '/api/v1/users/me', headers=basic(username, password))
self.assertEqual(status, 401)
self.assertTrue(headers['WWW-Authenticate'].lower().startswith('bearer'))
status, _, raw = request('DELETE', '/api/v1/auth/sessions/current', headers=auth)
self.assertEqual(status, 204)
self.assertIsNone(raw)
status, _, _ = request('GET', '/api/v1/users/me', headers=auth)
self.assertEqual(status, 401)
status, _, _ = request('DELETE', '/api/v1/auth/sessions/current', headers=auth)
self.assertEqual(status, 401)
def test_duplicate_username_race(self):
username = 'race_' + uuid.uuid4().hex[:8]
password = 'race-password-1'
barrier = threading.Barrier(8)
results = []
lock = threading.Lock()
def once():
barrier.wait()
status, _, _ = register(username, password)
with lock:
results.append(status)
threads = [threading.Thread(target=once) for _ in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertEqual(results.count(201), 1, results)
self.assertEqual(results.count(409), 7, results)
self.assertEqual(psql("SELECT count(*) FROM users WHERE username = '%s'" % username), '1')
def test_chat_create_rolls_back(self):
username = 'roll_' + uuid.uuid4().hex[:8]
password = 'roll-password-1'
status, _, user = register(username, password)
self.assertEqual(status, 201)
status, _, session = request('POST', '/api/v1/auth/sessions', headers=basic(username, password))
auth = bearer(session['token'])
title = 'rollback_' + uuid.uuid4().hex[:10]
missing = str(uuid.uuid4())
before = psql('SELECT count(*) FROM chats')
status, _, _ = request('POST', '/api/v1/chats', headers=auth, body={
'title': title,
'member_ids': [user['id'], missing],
})
self.assertEqual(status, 400)
self.assertEqual(psql("SELECT count(*) FROM chats WHERE title = '%s'" % title), '0')
self.assertEqual(psql('SELECT count(*) FROM chats'), before)
def test_read_after_write_and_pages(self):
username = 'page_' + uuid.uuid4().hex[:8]
password = 'page-password-1'
status, _, user = register(username, password)
status, _, session = request('POST', '/api/v1/auth/sessions', headers=basic(username, password))
auth = bearer(session['token'])
status, _, chat = request('POST', '/api/v1/chats', headers=auth, body={
'title': 'страницы',
'member_ids': [user['id']],
})
sent = []
for text in ('раз', 'два', 'три'):
status, _, message = request(
'POST', '/api/v1/chats/%s/messages' % chat['id'],
headers=auth,
body={'text': text},
)
self.assertEqual(status, 201)
sent.append(message)
status, _, page = request(
'GET', '/api/v1/chats/%s/messages?limit=2' % chat['id'],
headers=auth,
)
self.assertEqual(page['items'], sent[:2])
self.assertIsNotNone(page['next_cursor'])
status, _, rest = request(
'GET', '/api/v1/chats/%s/messages?limit=2&cursor=%s' % (
chat['id'], quote(page['next_cursor'], safe=''),
),
headers=auth,
)
self.assertEqual(rest['items'], sent[2:])
self.assertIsNone(rest['next_cursor'])
def test_migrations_do_not_duplicate(self):
before = psql('SELECT count(*) FROM users')
versions = psql('SELECT count(*) FROM schema_migrations')
self.assertEqual(versions, '1')
out = subprocess.check_output(
[
'docker', 'exec', 'mtusi-lab2-api', 'python', '-c',
"import sys; sys.path.insert(0, '/app/src'); import db; print(len(db.apply_migrations()))",
],
text=True,
)
self.assertEqual(out.strip(), '0')
self.assertEqual(psql('SELECT count(*) FROM users'), before)
self.assertEqual(psql("SELECT version FROM schema_migrations"), '001_init.sql')
if __name__ == '__main__':
unittest.main()