forked from mtusi2026/mtusi2026lab2
Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход, opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON, keyset-пагинацию по индексу, миграции, compose-стенд и собственные проверки уровня 3/4. Трек 5 — план запроса и восстановление.
320 lines
15 KiB
Python
320 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""SQL-level checks for lab2: schema constraints, unique username under
|
|
concurrency, password hashes, transaction rollback of the composite chat
|
|
operation, idempotent migrations and EXPLAIN (ANALYZE, BUFFERS) on a history
|
|
of at least 10 000 messages.
|
|
|
|
All database commands run non-interactively inside the lab2 PostgreSQL
|
|
container with ON_ERROR_STOP=1.
|
|
"""
|
|
import datetime as dt
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, Failure, arguments, check # noqa: E402
|
|
|
|
POSTGRES = 'mtusi-lab2-melnikov-postgres'
|
|
API = 'mtusi-lab2-melnikov-api'
|
|
|
|
|
|
def read_env():
|
|
values = {}
|
|
for line in (ROOT / '.env').read_text().splitlines():
|
|
line = line.strip()
|
|
if not line or line.startswith('#') or '=' not in line:
|
|
continue
|
|
key, value = line.split('=', 1)
|
|
values[key.strip()] = value.strip()
|
|
return values
|
|
|
|
|
|
ENV = read_env()
|
|
|
|
|
|
def psql(sql, allow_failure=False):
|
|
result = subprocess.run(
|
|
['docker', 'exec', '-i', POSTGRES, 'psql', '-X', '-A', '-t', '-F', '|',
|
|
'-v', 'ON_ERROR_STOP=1', '-U', ENV['POSTGRES_USER'], '-d', ENV['POSTGRES_DB']],
|
|
input=sql, capture_output=True, text=True)
|
|
if result.returncode != 0 and not allow_failure:
|
|
raise Failure('psql failed: ' + result.stderr.strip()[:400])
|
|
return result
|
|
|
|
|
|
def query(sql):
|
|
return psql(sql).stdout.strip()
|
|
|
|
|
|
def wait_ready(base_url, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
with urllib.request.urlopen(base_url + '/health/ready', timeout=3) as response:
|
|
if response.status == 200:
|
|
return
|
|
except Exception: # noqa: BLE001 - expected while the API restarts
|
|
pass
|
|
time.sleep(0.5)
|
|
raise Failure('API did not become ready after restart')
|
|
|
|
|
|
def ensure_large_history(c, output_dir):
|
|
"""Return (chat_id, message_count). Seeds 12 000 rows only when the
|
|
database does not already contain a 10 000+ message history."""
|
|
total = int(query('SELECT count(*) FROM messages;'))
|
|
if total >= 10000:
|
|
row = query("""
|
|
SELECT chat_id::text || '|' || count(*)
|
|
FROM messages GROUP BY chat_id ORDER BY count(*) DESC, min(created_at) LIMIT 1;
|
|
""")
|
|
chat_id, count = row.split('|')
|
|
return chat_id, int(count), total
|
|
|
|
owner = c.user('explain')
|
|
chat = c.call('POST', '/api/v1/chats', 201, actor=owner,
|
|
body={'title': 'level4 explain history',
|
|
'member_ids': [owner['id']]}, schema='Chat')['json']
|
|
target = 12000
|
|
psql("""
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT gen_random_uuid(), '%s'::uuid, '%s'::uuid, 'level4 row ' || g,
|
|
timestamptz '2026-02-01 00:00:00+00' + (g || ' milliseconds')::interval
|
|
FROM generate_series(1, %d) AS g;
|
|
ANALYZE messages;
|
|
""" % (chat['id'], owner['id'], target))
|
|
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
|
|
check(count == target, 'seeded history has %d rows, want %d' % (count, target))
|
|
return chat['id'], count, total + target
|
|
|
|
|
|
def explain(sql):
|
|
result = psql('EXPLAIN (ANALYZE, BUFFERS) ' + sql + ';\n')
|
|
return result.stdout.strip()
|
|
|
|
|
|
def main():
|
|
def configure(parser):
|
|
parser.add_argument('--output-dir', default='evidence')
|
|
|
|
args = arguments('SQL constraints, rollback, migrations and EXPLAIN', configure)
|
|
c = Client(args.base_url, args.ca_file)
|
|
output_dir = ROOT / args.output_dir
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
setup = c.user('dbcheck')
|
|
evidence = {'checked_at': dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')}
|
|
|
|
# --- schema and constraints -------------------------------------------
|
|
versions = query('SELECT string_agg(version::text, \',\' ORDER BY version) FROM schema_migrations;')
|
|
check(versions == '1,2', 'schema_migrations versions = %r, want 1,2' % versions)
|
|
duplicate_users = int(query("""
|
|
SELECT count(*) FROM (SELECT username FROM users GROUP BY username HAVING count(*) > 1) duplicates;
|
|
"""))
|
|
check(duplicate_users == 0, 'duplicate usernames exist despite the unique index')
|
|
required_constraints = {
|
|
'users_pkey', 'users_username_format', 'users_display_name_length',
|
|
'users_password_hash_present', 'chats_pkey', 'chats_title_length',
|
|
'chat_members_pkey', 'chat_members_chat_id_fkey', 'chat_members_user_id_fkey',
|
|
'chat_members_position_nonnegative', 'messages_pkey', 'messages_text_length',
|
|
'messages_chat_fk', 'messages_sender_membership_fk',
|
|
}
|
|
present_constraints = set(query("""
|
|
SELECT conname FROM pg_constraint
|
|
WHERE conrelid IN ('users'::regclass, 'chats'::regclass, 'chat_members'::regclass, 'messages'::regclass);
|
|
""").splitlines())
|
|
missing = required_constraints - present_constraints
|
|
check(not missing, 'missing database constraints: ' + repr(sorted(missing)))
|
|
required_indexes = {'users_username_key', 'chat_members_user_chat_idx',
|
|
'messages_chat_created_id_idx', 'chats_created_id_idx'}
|
|
present_indexes = set(query("SELECT indexname FROM pg_indexes WHERE schemaname='public';").splitlines())
|
|
missing_indexes = required_indexes - present_indexes
|
|
check(not missing_indexes, 'missing indexes: ' + repr(sorted(missing_indexes)))
|
|
check(query("""
|
|
SELECT count(*) FROM information_schema.tables
|
|
WHERE table_schema='public' AND table_name ILIKE '%session%';
|
|
""") == '0', 'sessions must not be stored in PostgreSQL')
|
|
|
|
users = int(query('SELECT count(*) FROM users;'))
|
|
hashed = int(query("SELECT count(*) FROM users WHERE password_hash LIKE '$argon2id$%';"))
|
|
check(users >= 1, 'expected at least the setup user, found %d' % users)
|
|
check(hashed == users, 'not every stored password is an Argon2id PHC string')
|
|
check(query("SELECT count(*) FROM users WHERE password_hash IN ('', 'password');") == '0',
|
|
'empty or literal password hash found')
|
|
race_duplicates = int(query("""
|
|
SELECT count(*) FROM (SELECT username FROM users WHERE username LIKE 'race_%'
|
|
GROUP BY username HAVING count(*) > 1) duplicates;
|
|
"""))
|
|
check(race_duplicates == 0, 'concurrent registration created duplicate usernames')
|
|
evidence['schema'] = {
|
|
'migration_versions': versions,
|
|
'constraints_present': sorted(required_constraints),
|
|
'indexes_present': sorted(required_indexes),
|
|
'users': users,
|
|
'argon2id_hashes': hashed,
|
|
'duplicate_usernames': duplicate_users,
|
|
'race_duplicates': race_duplicates,
|
|
}
|
|
|
|
# --- database-level sender membership FK ------------------------------
|
|
chat_id = query('SELECT id::text FROM chats ORDER BY created_at LIMIT 1;')
|
|
outsider = query("""
|
|
SELECT id::text FROM users
|
|
WHERE id NOT IN (SELECT user_id FROM chat_members WHERE chat_id='%s')
|
|
ORDER BY created_at LIMIT 1;
|
|
""" % chat_id)
|
|
check(bool(outsider), 'could not find a non-member for the FK probe')
|
|
before = int(query('SELECT count(*) FROM messages;'))
|
|
failed = psql("""
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
VALUES (gen_random_uuid(), '%s'::uuid, '%s'::uuid, 'fk probe', now());
|
|
""" % (chat_id, outsider), allow_failure=True)
|
|
after = int(query('SELECT count(*) FROM messages;'))
|
|
check(failed.returncode != 0, 'database accepted a message from a non-member sender')
|
|
check(before == after, 'failed FK insert changed the message count')
|
|
evidence['sender_membership_fk'] = {'rejected': True, 'messages_before': before, 'messages_after': after}
|
|
|
|
# --- rollback of the composite chat operation -------------------------
|
|
owner = c.user('rollback')
|
|
other = c.user('rollback')
|
|
psql("""
|
|
CREATE OR REPLACE FUNCTION lab2_rollback_probe() RETURNS trigger AS $$
|
|
BEGIN
|
|
IF EXISTS (SELECT 1 FROM chats WHERE id = NEW.chat_id AND title = 'rollback-probe') THEN
|
|
RAISE EXCEPTION 'injected composite failure';
|
|
END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$ LANGUAGE plpgsql;
|
|
DROP TRIGGER IF EXISTS lab2_rollback_probe ON chat_members;
|
|
CREATE TRIGGER lab2_rollback_probe BEFORE INSERT ON chat_members
|
|
FOR EACH ROW EXECUTE FUNCTION lab2_rollback_probe();
|
|
""")
|
|
try:
|
|
response = c.call('POST', '/api/v1/chats', 500, actor=owner,
|
|
body={'title': 'rollback-probe', 'member_ids': [owner['id'], other['id']]})
|
|
check(response['json']['error']['code'] == 'internal_error', 'rollback probe error code')
|
|
message = response['json']['error']['message'].lower()
|
|
for leaked in ('injected', 'sql', 'lab2_rollback', 'trigger'):
|
|
check(leaked not in message, '500 body leaks internal detail %r' % leaked)
|
|
finally:
|
|
psql("""
|
|
DROP TRIGGER IF EXISTS lab2_rollback_probe ON chat_members;
|
|
DROP FUNCTION IF EXISTS lab2_rollback_probe();
|
|
""")
|
|
leftover = query("SELECT count(*) FROM chats WHERE title='rollback-probe';")
|
|
check(leftover == '0', 'composite chat operation left a chat without members after rollback')
|
|
evidence['composite_rollback'] = {'chats_left': int(leftover), 'api_status': 500}
|
|
|
|
# --- migrations re-run on API restart without duplicating data --------
|
|
counts_sql = ('SELECT (SELECT count(*) FROM users) || \',\' || (SELECT count(*) FROM chats) || \',\' || '
|
|
'(SELECT count(*) FROM chat_members) || \',\' || (SELECT count(*) FROM messages);')
|
|
before_counts = query(counts_sql)
|
|
started_before = json.loads(subprocess.run(
|
|
['docker', 'inspect', API], capture_output=True, text=True, check=True).stdout)[0]['State']['StartedAt']
|
|
subprocess.run(['docker', 'restart', API], check=True, capture_output=True)
|
|
wait_ready(args.base_url)
|
|
after_counts = query(counts_sql)
|
|
migrations_after = query('SELECT count(*) FROM schema_migrations;')
|
|
started_after = json.loads(subprocess.run(
|
|
['docker', 'inspect', API], capture_output=True, text=True, check=True).stdout)[0]['State']['StartedAt']
|
|
check(before_counts == after_counts, 'API restart duplicated or lost rows: %r -> %r'
|
|
% (before_counts, after_counts))
|
|
check(migrations_after == '2', 'migrations table changed after restart')
|
|
check(started_before != started_after, 'API was not actually restarted')
|
|
evidence['migrations_idempotent'] = {
|
|
'counts_before': before_counts, 'counts_after': after_counts,
|
|
'migrations_after': int(migrations_after), 'api_restarted': True,
|
|
}
|
|
|
|
# --- EXPLAIN on a >=10 000 message history ----------------------------
|
|
chat_id, history_count, total = ensure_large_history(c, output_dir)
|
|
check(history_count >= 10000, 'EXPLAIN history has only %d messages' % history_count)
|
|
deep_offset = max(1000, history_count // 2)
|
|
row = query("""
|
|
SELECT created_at::text || '|' || id::text FROM messages
|
|
WHERE chat_id='%s' ORDER BY created_at, messages.id OFFSET %d LIMIT 1;
|
|
""" % (chat_id, deep_offset)).split('|')
|
|
cursor_time, cursor_id = row
|
|
keyset_sql = ("""
|
|
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
|
FROM messages
|
|
WHERE chat_id='%s'::uuid AND (created_at, messages.id) > ('%s'::timestamptz, '%s'::uuid)
|
|
ORDER BY created_at, messages.id LIMIT 50
|
|
""" % (chat_id, cursor_time, cursor_id))
|
|
first_sql = ("""
|
|
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
|
FROM messages WHERE chat_id='%s'::uuid
|
|
ORDER BY created_at, messages.id LIMIT 50
|
|
""" % chat_id)
|
|
offset_sql = ("""
|
|
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
|
FROM messages WHERE chat_id='%s'::uuid
|
|
ORDER BY created_at, messages.id OFFSET %d LIMIT 50
|
|
""" % (chat_id, deep_offset))
|
|
|
|
first_plan = explain(first_sql)
|
|
keyset_plan = explain(keyset_sql)
|
|
offset_plan = explain(offset_sql)
|
|
for name, plan in (('first page', first_plan), ('deep keyset page', keyset_plan)):
|
|
check('Index Scan using messages_chat_created_id_idx' in plan,
|
|
name + ' does not use the history index:\n' + plan)
|
|
check('Seq Scan on messages' not in plan, name + ' performs a sequential scan')
|
|
check('Index Scan using messages_chat_created_id_idx' in offset_plan,
|
|
'naive OFFSET plan unexpectedly avoids the index')
|
|
|
|
import re
|
|
def scanned_rows(plan):
|
|
match = re.search(
|
|
r'Index Scan using messages_chat_created_id_idx.*?actual time=[\d.]+\.[\d.]+ rows=(\d+)',
|
|
plan, re.S)
|
|
return int(match.group(1)) if match else None
|
|
|
|
first_rows = scanned_rows(first_plan)
|
|
keyset_rows = scanned_rows(keyset_plan)
|
|
offset_rows = scanned_rows(offset_plan)
|
|
check(first_rows == 50, 'first page scanned %r rows, want 50' % (first_rows,))
|
|
check(keyset_rows == 50, 'deep keyset page scanned %r rows, want 50' % (keyset_rows,))
|
|
check(offset_rows is not None and offset_rows > deep_offset,
|
|
'OFFSET comparison did not demonstrate a large scan (%r rows)' % (offset_rows,))
|
|
plan_text = (
|
|
'LAB2 LEVEL 4 EXPLAIN EVIDENCE\n'
|
|
'messages in history: %d, total messages: %d, deep offset: %d\n\n'
|
|
'=== first page ===\n%s\n\n=== keyset page after offset %d ===\n%s\n\n'
|
|
'=== naive OFFSET %d ===\n%s\n' % (
|
|
history_count, total, deep_offset, first_plan, deep_offset, keyset_plan, deep_offset, offset_plan)
|
|
)
|
|
(output_dir / 'explain-level4.txt').write_text(plan_text)
|
|
evidence['explain'] = {
|
|
'chat_id': chat_id, 'history_messages': history_count, 'total_messages': total,
|
|
'first_page_index_rows': first_rows, 'keyset_page_index_rows': keyset_rows,
|
|
'offset_page_index_rows': offset_rows, 'deep_offset': deep_offset,
|
|
'index_used': 'messages_chat_created_id_idx',
|
|
}
|
|
|
|
(output_dir / 'db-checks.json').write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + '\n')
|
|
print(json.dumps({
|
|
'migrations': versions,
|
|
'constraints': len(required_constraints),
|
|
'indexes': len(required_indexes),
|
|
'argon2id_hashes': hashed,
|
|
'composite_rollback_left_chats': int(leftover),
|
|
'migration_counts_stable': before_counts == after_counts,
|
|
'explain_history_messages': history_count,
|
|
'keyset_rows_read': keyset_rows,
|
|
'offset_rows_read': offset_rows,
|
|
}, ensure_ascii=False, sort_keys=True))
|
|
print('PASS: SQL constraints, FK, rollback, idempotent migrations and index-backed EXPLAIN')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except AssertionError as exc:
|
|
print('FAIL:', exc)
|
|
raise SystemExit(1)
|